Python asyncio.TimeoutError() Examples

The following are 30 code examples of asyncio.TimeoutError(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module asyncio , or try the search function .
Example #1
Source File: websockets.py    From gql with MIT License 9 votes vote down vote up
def _send_init_message_and_wait_ack(self) -> None:
        """Send init message to the provided websocket and wait for the connection ACK.

        If the answer is not a connection_ack message, we will return an Exception.
        """

        init_message = json.dumps(
            {"type": "connection_init", "payload": self.init_payload}
        )

        await self._send(init_message)

        # Wait for the connection_ack message or raise a TimeoutError
        init_answer = await asyncio.wait_for(self._receive(), self.ack_timeout)

        answer_type, answer_id, execution_result = self._parse_answer(init_answer)

        if answer_type != "connection_ack":
            raise TransportProtocolError(
                "Websocket server did not return a connection ack"
            ) 
Example #2
Source File: websockets.py    From gql with MIT License 8 votes vote down vote up
def _clean_close(self, e: Exception) -> None:
        """Coroutine which will:

        - send stop messages for each active subscription to the server
        - send the connection terminate message
        """

        # Send 'stop' message for all current queries
        for query_id, listener in self.listeners.items():

            if listener.send_stop:
                await self._send_stop_message(query_id)
                listener.send_stop = False

        # Wait that there is no more listeners (we received 'complete' for all queries)
        try:
            await asyncio.wait_for(self._no_more_listeners.wait(), self.close_timeout)
        except asyncio.TimeoutError:  # pragma: no cover
            pass

        # Finally send the 'connection_terminate' message
        await self._send_connection_terminate_message() 
Example #3
Source File: pool.py    From aioredis with MIT License 6 votes vote down vote up
def discover_slave(self, service, timeout, **kwargs):
        """Perform Slave discovery for specified service."""
        # TODO: use kwargs to change how slaves are picked up
        #   (eg: round-robin, priority, random, etc)
        idle_timeout = timeout
        pools = self._pools[:]
        for sentinel in pools:
            try:
                with async_timeout(timeout):
                    address = await self._get_slave_address(
                        sentinel, service)  # add **kwargs
                pool = self._slaves[service]
                with async_timeout(timeout), \
                        contextlib.ExitStack() as stack:
                    conn = await pool._create_new_connection(address)
                    stack.callback(conn.close)
                    await self._verify_service_role(conn, 'slave')
                    stack.pop_all()
                return conn
            except asyncio.CancelledError:
                raise
            except asyncio.TimeoutError:
                continue
            except DiscoverError:
                await asyncio.sleep(idle_timeout)
                continue
            except RedisError as err:
                raise SlaveReplyError("Service {} error".format(service), err)
            except Exception:
                await asyncio.sleep(idle_timeout)
                continue
        raise SlaveNotFoundError("No slave found for {}".format(service)) 
Example #4
Source File: comms.py    From kivy-smoothie-host with GNU General Public License v3.0 6 votes vote down vote up
def _parse_sdcard_list(self, done_cb):
        self.log.debug('Comms: _parse_sdcard_list')

        # setup callback to receive and parse listing data
        files = []
        f = asyncio.Future()
        self.redirect_incoming(lambda x: self._rcv_sdcard_line(x, files, f))

        # issue command
        self._write('M20\n')

        # wait for it to complete and get all the lines
        # add a long timeout in case it fails and we don't want to wait for ever
        try:
            await asyncio.wait_for(f, 10)

        except asyncio.TimeoutError:
            self.log.warning("Comms: Timeout waiting for sd card list")
            files = []

        self.redirect_incoming(None)

        # call upstream callback with results
        done_cb(files) 
Example #5
Source File: tcpmtproxy.py    From Telethon with MIT License 6 votes vote down vote up
def _connect(self, timeout=None, ssl=None):
        await super()._connect(timeout=timeout, ssl=ssl)

        # Wait for EOF for 2 seconds (or if _wait_for_data's definition
        # is missing or different, just sleep for 2 seconds). This way
        # we give the proxy a chance to close the connection if the current
        # codec (which the proxy detects with the data we sent) cannot
        # be used for this proxy. This is a work around for #1134.
        # TODO Sleeping for N seconds may not be the best solution
        # TODO This fix could be welcome for HTTP proxies as well
        try:
            await asyncio.wait_for(self._reader._wait_for_data('proxy'), 2)
        except asyncio.TimeoutError:
            pass
        except Exception:
            await asyncio.sleep(2)

        if self._reader.at_eof():
            await self.disconnect()
            raise ConnectionError(
                'Proxy closed the connection after sending initial payload') 
Example #6
Source File: gitter.py    From fishroom with GNU General Public License v3.0 6 votes vote down vote up
def fetch(self, session, room, id_blacklist):
        url = self._stream_api.format(room=room)
        while True:
            # print("polling on url %s" % url)
            try:
                with aiohttp.Timeout(300):
                    async with session.get(url, headers=self.headers) as resp:
                        while True:
                            line = await resp.content.readline()
                            line = bytes.decode(line, 'utf-8').strip()
                            if not line:
                                continue
                            msg = self.parse_jmsg(room, json.loads(line))
                            if msg.sender in id_blacklist:
                                continue
                            self.send_to_bus(msg)
            except asyncio.TimeoutError:
                pass
            except:
                raise 
Example #7
Source File: test_base.py    From bot with MIT License 6 votes vote down vote up
def test_wait_for_confirmation(self):
        """The message should always be edited and only return True if the emoji is a check mark."""
        subtests = (
            (constants.Emojis.check_mark, True, None),
            ("InVaLiD", False, None),
            (None, False, asyncio.TimeoutError),
        )

        for emoji, ret_val, side_effect in subtests:
            for bot in (True, False):
                with self.subTest(emoji=emoji, ret_val=ret_val, side_effect=side_effect, bot=bot):
                    # Set up mocks
                    message = helpers.MockMessage()
                    member = helpers.MockMember(bot=bot)

                    self.bot.wait_for.reset_mock()
                    self.bot.wait_for.return_value = (helpers.MockReaction(emoji=emoji), None)
                    self.bot.wait_for.side_effect = side_effect

                    # Call the function
                    actual_return = await self.syncer._wait_for_confirmation(member, message)

                    # Perform assertions
                    self.bot.wait_for.assert_called_once()
                    self.assertIn("reaction_add", self.bot.wait_for.call_args[0])

                    message.edit.assert_called_once()
                    kwargs = message.edit.call_args[1]
                    self.assertIn("content", kwargs)

                    # Core devs should only be mentioned if the author is a bot.
                    if bot:
                        self.assertIn(self.syncer._CORE_DEV_MENTION, kwargs["content"])
                    else:
                        self.assertNotIn(self.syncer._CORE_DEV_MENTION, kwargs["content"])

                    self.assertIs(actual_return, ret_val) 
Example #8
Source File: help.py    From bot with MIT License 6 votes vote down vote up
def help_cleanup(bot: Bot, author: Member, message: Message) -> None:
    """
    Runs the cleanup for the help command.

    Adds the :trashcan: reaction that, when clicked, will delete the help message.
    After a 300 second timeout, the reaction will be removed.
    """
    def check(reaction: Reaction, user: User) -> bool:
        """Checks the reaction is :trashcan:, the author is original author and messages are the same."""
        return str(reaction) == DELETE_EMOJI and user.id == author.id and reaction.message.id == message.id

    await message.add_reaction(DELETE_EMOJI)

    try:
        await bot.wait_for("reaction_add", check=check, timeout=300)
        await message.delete()
    except TimeoutError:
        await message.remove_reaction(DELETE_EMOJI, bot.user)
    except NotFound:
        pass 
Example #9
Source File: pool.py    From aioredis with MIT License 6 votes vote down vote up
def _connect_sentinel(self, address, timeout, pools):
        """Try to connect to specified Sentinel returning either
        connections pool or exception.
        """
        try:
            with async_timeout(timeout):
                pool = await create_pool(
                    address, minsize=1, maxsize=2,
                    parser=self._parser_class,
                    )
            pools.append(pool)
            return pool
        except asyncio.TimeoutError as err:
            sentinel_logger.debug(
                "Failed to connect to Sentinel(%r) within %ss timeout",
                address, timeout)
            return err
        except Exception as err:
            sentinel_logger.debug(
                "Error connecting to Sentinel(%r): %r", address, err)
            return err 
Example #10
Source File: barrier.py    From aiozk with MIT License 6 votes vote down vote up
def wait(self, timeout=None):
        deadline = Deadline(timeout)
        barrier_lifted = self.client.wait_for_events(
            [WatchEvent.DELETED], self.path
        )

        exists = await self.client.exists(path=self.path, watch=True)
        if not exists:
            return

        try:
            if not deadline.is_indefinite:
                await asyncio.wait_for(barrier_lifted, deadline.timeout)
            else:
                await barrier_lifted
        except asyncio.TimeoutError:
            raise exc.TimeoutError 
Example #11
Source File: base.py    From backend.ai-manager with GNU Lesser General Public License v3.0 6 votes vote down vote up
def simple_db_mutate_returning_item(result_cls, context, mutation_query, *,
                                          item_query, item_cls):
    async with context['dbpool'].acquire() as conn, conn.begin():
        try:
            result = await conn.execute(mutation_query)
            if result.rowcount > 0:
                result = await conn.execute(item_query)
                item = await result.first()
                return result_cls(True, 'success', item_cls.from_row(item))
            else:
                return result_cls(False, 'no matching record', None)
        except (pg.IntegrityError, sa.exc.IntegrityError) as e:
            return result_cls(False, f'integrity error: {e}', None)
        except (asyncio.CancelledError, asyncio.TimeoutError):
            raise
        except Exception as e:
            return result_cls(False, f'unexpected error: {e}', None) 
Example #12
Source File: guessing_game.py    From discord.py with MIT License 6 votes vote down vote up
def on_message(self, message):
        # we do not want the bot to reply to itself
        if message.author.id == self.user.id:
            return

        if message.content.startswith('$guess'):
            await message.channel.send('Guess a number between 1 and 10.')

            def is_correct(m):
                return m.author == message.author and m.content.isdigit()

            answer = random.randint(1, 10)

            try:
                guess = await self.wait_for('message', check=is_correct, timeout=5.0)
            except asyncio.TimeoutError:
                return await message.channel.send('Sorry, you took too long it was {}.'.format(answer))

            if int(guess.content) == answer:
                await message.channel.send('You are right!')
            else:
                await message.channel.send('Oops. It is actually {}.'.format(answer)) 
Example #13
Source File: state.py    From discord.py with MIT License 6 votes vote down vote up
def request_offline_members(self, guilds, *, shard_id):
        # get all the chunks
        chunks = []
        for guild in guilds:
            chunks.extend(self.chunks_needed(guild))

        # we only want to request ~75 guilds per chunk request.
        splits = [guilds[i:i + 75] for i in range(0, len(guilds), 75)]
        for split in splits:
            await self.chunker([g.id for g in split], shard_id=shard_id)

        # wait for the chunks
        if chunks:
            try:
                await utils.sane_wait_for(chunks, timeout=len(chunks) * 30.0)
            except asyncio.TimeoutError:
                log.info('Somehow timed out waiting for chunks.')
            else:
                log.info('Finished requesting guild member chunks for %d guilds.', len(guilds)) 
Example #14
Source File: sheetManager.py    From avrae with GNU General Public License v3.0 6 votes vote down vote up
def character_delete(self, ctx, *, name):
        """Deletes a character."""
        user_characters = await self.bot.mdb.characters.find(
            {"owner": str(ctx.author.id)}, ['name', 'upstream']
        ).to_list(None)
        if not user_characters:
            return await ctx.send('You have no characters.')

        selected_char = await search_and_select(ctx, user_characters, name, lambda e: e['name'],
                                                selectkey=lambda e: f"{e['name']} (`{e['upstream']}`)")

        await ctx.send(f"Are you sure you want to delete {selected_char['name']}? (Reply with yes/no)")
        try:
            reply = await self.bot.wait_for('message', timeout=30, check=auth_and_chan(ctx))
        except asyncio.TimeoutError:
            reply = None
        reply = get_positivity(reply.content) if reply is not None else None
        if reply is None:
            return await ctx.send('Timed out waiting for a response or invalid response.')
        elif reply:
            await Character.delete(ctx, str(ctx.author.id), selected_char['upstream'])
            return await ctx.send(f"{selected_char['name']} has been deleted.")
        else:
            return await ctx.send("OK, cancelling.") 
Example #15
Source File: sheetManager.py    From avrae with GNU General Public License v3.0 6 votes vote down vote up
def transferchar(self, ctx, user: discord.Member):
        """Gives a copy of the active character to another user."""
        character: Character = await Character.from_ctx(ctx)
        overwrite = ''

        conflict = await self.bot.mdb.characters.find_one({"owner": str(user.id), "upstream": character.upstream})
        if conflict:
            overwrite = "**WARNING**: This will overwrite an existing character."

        await ctx.send(f"{user.mention}, accept a copy of {character.name}? (Type yes/no)\n{overwrite}")
        try:
            m = await self.bot.wait_for('message', timeout=300,
                                        check=lambda msg: msg.author == user
                                                          and msg.channel == ctx.channel
                                                          and get_positivity(msg.content) is not None)
        except asyncio.TimeoutError:
            m = None

        if m is None or not get_positivity(m.content): return await ctx.send("Transfer not confirmed, aborting.")

        character.owner = str(user.id)
        await character.commit(ctx)
        await ctx.send(f"Copied {character.name} to {user.display_name}'s storage.") 
Example #16
Source File: functions.py    From avrae with GNU General Public License v3.0 6 votes vote down vote up
def confirm(ctx, message, delete_msgs=False):
    """
    Confirms whether a user wants to take an action.
    :rtype: bool|None
    :param ctx: The current Context.
    :param message: The message for the user to confirm.
    :param delete_msgs: Whether to delete the messages.
    :return: Whether the user confirmed or not. None if no reply was recieved
    """
    msg = await ctx.channel.send(message)
    try:
        reply = await ctx.bot.wait_for('message', timeout=30, check=auth_and_chan(ctx))
    except asyncio.TimeoutError:
        return None
    replyBool = get_positivity(reply.content) if reply is not None else None
    if delete_msgs:
        try:
            await msg.delete()
            await reply.delete()
        except:
            pass
    return replyBool 
Example #17
Source File: streammanagerclient.py    From aws-greengrass-core-sdk-python with Apache License 2.0 6 votes vote down vote up
def read_messages(self, stream_name: str, options: Optional[ReadMessagesOptions] = None) -> List[Message]:
        """
        Read message(s) from a chosen stream with options. If no options are specified it will try to read
        1 message from the stream.

        :param stream_name: The name of the stream to read from.
        :param options: (Optional) Options used when reading from the stream of type :class:`.data.ReadMessagesOptions`.
            Defaults are:

            * desired_start_sequence_number: 0,
            * min_message_count: 1,
            * max_message_count: 1,
            * read_timeout_millis: 0 ``# Where 0 here represents that the server will immediately return the messages``
                                     ``# or an exception if there were not enough messages available.``
            If desired_start_sequence_number is specified in the options and is less
            than the current beginning of the stream, returned messages will start
            at the beginning of the stream and not necessarily the desired_start_sequence_number.
        :return: List of at least 1 message.
        :raises: :exc:`~.exceptions.StreamManagerException` and subtypes based on the precise error.
        :raises: :exc:`asyncio.TimeoutError` if the request times out.
        :raises: :exc:`ConnectionError` if the client is unable to reconnect to the server.
        """
        self.__check_closed()
        return Util.sync(self._read_messages(stream_name, options), loop=self.__loop) 
Example #18
Source File: state.py    From discord.py with MIT License 6 votes vote down vote up
def request_offline_members(self, guilds):
        # get all the chunks
        chunks = []
        for guild in guilds:
            chunks.extend(self.chunks_needed(guild))

        # we only want to request ~75 guilds per chunk request.
        splits = [guilds[i:i + 75] for i in range(0, len(guilds), 75)]
        for split in splits:
            await self.chunker([g.id for g in split])

        # wait for the chunks
        if chunks:
            try:
                await utils.sane_wait_for(chunks, timeout=len(chunks) * 30.0)
            except asyncio.TimeoutError:
                log.warning('Somehow timed out waiting for chunks.')
            else:
                log.info('Finished requesting guild member chunks for %d guilds.', len(guilds)) 
Example #19
Source File: connection_async.py    From azure-uamqp-python with MIT License 6 votes vote down vote up
def destroy_async(self):
        """Close the connection asynchronously, and close any associated
        CBS authentication session.
        """
        try:
            await self.lock_async()
            _logger.debug("Unlocked connection %r to close.", self.container_id)
            await self._close_async()
        except asyncio.TimeoutError:
            _logger.debug(
                "Connection %r timed out while waiting for lock acquisition on destroy. Destroying anyway.",
                self.container_id)
            await self._close_async()
        finally:
            self.release_async()
        uamqp._Platform.deinitialize()  # pylint: disable=protected-access 
Example #20
Source File: test_web_client.py    From python-slackclient with MIT License 6 votes vote down vote up
def test_unclosed_client_session_issue_645_in_async_mode(self):
        def exception_handler(_, context):
            nonlocal session_unclosed
            if context["message"] == "Unclosed client session":
                session_unclosed = True

        async def issue_645():
            client = WebClient(base_url="http://localhost:8888", timeout=1, run_async=True)
            try:
                await client.users_list(token="xoxb-timeout")
            except asyncio.TimeoutError:
                pass

        session_unclosed = False
        loop = asyncio.get_event_loop()
        loop.set_exception_handler(exception_handler)
        loop.run_until_complete(issue_645())
        gc.collect()  # force Python to gc unclosed client session
        self.assertFalse(session_unclosed, "Unclosed client session") 
Example #21
Source File: connection_async.py    From azure-uamqp-python with MIT License 6 votes vote down vote up
def work_async(self):
        """Perform a single Connection iteration asynchronously."""
        try:
            raise self._error
        except TypeError:
            pass
        except Exception as e:
            _logger.warning("%r", e)
            raise
        try:
            await self.lock_async()
            if self._closing:
                _logger.debug("Connection unlocked but shutting down.")
                return
            await asyncio.sleep(0, loop=self.loop)
            self._conn.do_work()
        except asyncio.TimeoutError:
            _logger.debug("Connection %r timed out while waiting for lock acquisition.", self.container_id)
        finally:
            await asyncio.sleep(0, loop=self.loop)
            self.release_async() 
Example #22
Source File: connection_async.py    From azure-uamqp-python with MIT License 6 votes vote down vote up
def redirect_async(self, redirect_error, auth):
        """Redirect the connection to an alternative endpoint.
        :param redirect: The Link DETACH redirect details.
        :type redirect: ~uamqp.errors.LinkRedirect
        :param auth: Authentication credentials to the redirected endpoint.
        :type auth: ~uamqp.authentication.common.AMQPAuth
        """
        _logger.info("Redirecting connection %r.", self.container_id)
        try:
            await self.lock_async()
            if self.hostname == redirect_error.hostname:
                return
            if self._state != c_uamqp.ConnectionState.END:
                await self._close_async()
            self.hostname = redirect_error.hostname
            self.auth = auth
            self._conn = self._create_connection(auth)
            for setting, value in self._settings.items():
                setattr(self, setting, value)
            self._error = None
            self._closing = False
        except asyncio.TimeoutError:
            _logger.debug("Connection %r timed out while waiting for lock acquisition.", self.container_id)
        finally:
            self.release_async() 
Example #23
Source File: voice_client.py    From discord.py with MIT License 5 votes vote down vote up
def poll_voice_ws(self, reconnect):
        backoff = ExponentialBackoff()
        while True:
            try:
                await self.ws.poll_event()
            except (ConnectionClosed, asyncio.TimeoutError) as exc:
                if isinstance(exc, ConnectionClosed):
                    # The following close codes are undocumented so I will document them here.
                    # 1000 - normal closure (obviously)
                    # 4014 - voice channel has been deleted.
                    # 4015 - voice server has crashed
                    if exc.code in (1000, 4014, 4015):
                        log.info('Disconnecting from voice normally, close code %d.', exc.code)
                        await self.disconnect()
                        break

                if not reconnect:
                    await self.disconnect()
                    raise

                retry = backoff.delay()
                log.exception('Disconnected from voice... Reconnecting in %.2fs.', retry)
                self._connected.clear()
                await asyncio.sleep(retry)
                await self.terminate_handshake()
                try:
                    await self.connect(reconnect=True)
                except asyncio.TimeoutError:
                    # at this point we've retried 5 times... let's continue the loop.
                    log.warning('Could not connect to voice... Retrying...')
                    continue 
Example #24
Source File: snekbox.py    From bot with MIT License 5 votes vote down vote up
def continue_eval(self, ctx: Context, response: Message) -> Optional[str]:
        """
        Check if the eval session should continue.

        Return the new code to evaluate or None if the eval session should be terminated.
        """
        _predicate_eval_message_edit = partial(predicate_eval_message_edit, ctx)
        _predicate_emoji_reaction = partial(predicate_eval_emoji_reaction, ctx)

        with contextlib.suppress(NotFound):
            try:
                _, new_message = await self.bot.wait_for(
                    'message_edit',
                    check=_predicate_eval_message_edit,
                    timeout=REEVAL_TIMEOUT
                )
                await ctx.message.add_reaction(REEVAL_EMOJI)
                await self.bot.wait_for(
                    'reaction_add',
                    check=_predicate_emoji_reaction,
                    timeout=10
                )

                code = await self.get_code(new_message)
                await ctx.message.clear_reactions()
                with contextlib.suppress(HTTPException):
                    await response.delete()

            except asyncio.TimeoutError:
                await ctx.message.clear_reactions()
                return None

            return code 
Example #25
Source File: state.py    From discord.py with MIT License 5 votes vote down vote up
def query_members(self, guild, query, limit, user_ids, cache):
        guild_id = guild.id
        ws = self._get_websocket(guild_id)
        if ws is None:
            raise RuntimeError('Somehow do not have a websocket for this guild_id')

        # Limits over 1000 cannot be supported since
        # the main use case for this is guild_subscriptions being disabled
        # and they don't receive GUILD_MEMBER events which make computing
        # member_count impossible. The only way to fix it is by limiting
        # the limit parameter to 1 to 1000.
        nonce = self.get_nonce()
        future = self.receive_member_query(guild_id, nonce)
        try:
            # start the query operation
            await ws.request_chunks(guild_id, query=query, limit=limit, user_ids=user_ids, nonce=nonce)
            members = await asyncio.wait_for(future, timeout=5.0)

            if cache:
                for member in members:
                    guild._add_member(member)

            return members
        except asyncio.TimeoutError:
            log.warning('Timed out waiting for chunks with query %r and limit %d for guild_id %d', query, limit, guild_id)
            raise 
Example #26
Source File: sheetManager.py    From avrae with GNU General Public License v3.0 5 votes vote down vote up
def _confirm_overwrite(self, ctx, _id):
        """Prompts the user if command would overwrite another character.
        Returns True to overwrite, False or None otherwise."""
        conflict = await self.bot.mdb.characters.find_one({"owner": str(ctx.author.id), "upstream": _id})
        if conflict:
            await ctx.channel.send(
                "Warning: This will overwrite a character with the same ID. Do you wish to continue (reply yes/no)?\n"
                f"If you only wanted to update your character, run `{ctx.prefix}update` instead.")
            try:
                reply = await self.bot.wait_for('message', timeout=30, check=auth_and_chan(ctx))
            except asyncio.TimeoutError:
                reply = None
            replyBool = get_positivity(reply.content) if reply is not None else None
            return replyBool
        return True 
Example #27
Source File: client.py    From clashroyale with MIT License 5 votes vote down vote up
def _arequest(self, url, **params):
        timeout = params.pop('timeout', None) or self.timeout
        try:
            async with self.session.get(url, timeout=timeout, headers=self.headers, params=params) as resp:
                return self._raise_for_status(resp, await resp.text())
        except asyncio.TimeoutError:
            raise NotResponding
        except aiohttp.ServerDisconnectedError:
            raise NetworkError 
Example #28
Source File: streammanagerclient.py    From aws-greengrass-core-sdk-python with Apache License 2.0 5 votes vote down vote up
def __send_and_receive(self, operation, data):
        async def inner(operation, data):
            if data.request_id is None:
                data.request_id = Util.get_request_id()

            validation = Util.is_invalid(data)
            if validation:
                raise ValidationException(validation)

            # If we're not connected, immediately try to reconnect
            if not self.connected:
                await self.__connect()

            self.__requests[data.request_id] = asyncio.Queue(1)

            # Write request to socket
            frame = MessageFrame(operation=operation, payload=cbor2.dumps(data.as_dict()))
            self.__writer.write(Util.encode_frame(frame))
            await self.__writer.drain()

            # Wait for reader to come back with the response
            result = await self.__requests[data.request_id].get()
            # Drop async queue from request map
            del self.__requests[data.request_id]
            if isinstance(result, MessageFrame) and result.operation == Operation.Unknown:
                raise ClientException("Received response with unknown operation from server")
            return result

        # Perform the actual work as async so that we can put a timeout on the whole operation
        try:
            return await asyncio.wait_for(inner(operation, data), timeout=self.request_timeout, loop=self.__loop)
        except asyncio.TimeoutError:
            # Drop async queue from request map
            del self.__requests[data.request_id]
            raise 
Example #29
Source File: client.py    From clashroyale with MIT License 5 votes vote down vote up
def _arequest(self, url, **params):
        method = params.get('method', 'GET')
        json_data = params.get('json', {})
        timeout = params.pop('timeout', None) or self.timeout
        try:
            async with self.session.request(
                method, url, timeout=timeout, headers=self.headers, params=params, data=json_data
            ) as resp:
                return self._raise_for_status(resp, await resp.text())
        except asyncio.TimeoutError:
            raise NotResponding
        except aiohttp.ServerDisconnectedError:
            raise NetworkError 
Example #30
Source File: state.py    From discord.py with MIT License 5 votes vote down vote up
def _delay_ready(self):
        launch = self._ready_state.launch
        while True:
            # this snippet of code is basically waiting 2 * shard_ids seconds
            # until the last GUILD_CREATE was sent
            try:
                await asyncio.wait_for(launch.wait(), timeout=2.0 * len(self.shard_ids))
            except asyncio.TimeoutError:
                break
            else:
                launch.clear()

        guilds = sorted(self._ready_state.guilds, key=lambda g: g[0].shard_id)

        for shard_id, sub_guilds_info in itertools.groupby(guilds, key=lambda g: g[0].shard_id):
            sub_guilds, sub_available = zip(*sub_guilds_info)
            if self._fetch_offline:
                await self.request_offline_members(sub_guilds, shard_id=shard_id)

            for guild, unavailable in zip(sub_guilds, sub_available):
                if unavailable is False:
                    self.dispatch('guild_available', guild)
                else:
                    self.dispatch('guild_join', guild)
            self.dispatch('shard_ready', shard_id)

        # remove the state
        try:
            del self._ready_state
        except AttributeError:
            pass # already been deleted somehow

        # regular users cannot shard so we won't worry about it here.

        # clear the current task
        self._ready_task = None

        # dispatch the event
        self.call_handlers('ready')
        self.dispatch('ready')