def chunk(text: str, length: int) -> Iterator[str]: """ Chunks the text. This is useful for getting pages that'll be passed to the Paginator object. This will yield the chunked text split by whitespaces if applicable. """ view = StringView(text) while not view.eof: view.skip_ws() sliced = view.read(length) if (not (space := utils.find(string.whitespace, lambda x: x in sliced)) or view.eof): if sliced: yield sliced continue view.undo() if sub := view.read( text.rfind(space, view.index, view.index + length + 1) - view.index): yield sub
def deserialize_member_presence( self, payload: data_binding.JSONObject, *, guild_id: undefined.UndefinedOr[snowflakes.Snowflake] = undefined.UNDEFINED, ) -> presences.MemberPresence: user_id = Snowflake(payload["user"]["id"]) if spotify := find( payload["activities"], lambda x: x.get("name") == "Spotify" and "sync_id" in x, ): self._app._sync_ids[user_id] = spotify["sync_id"]
async def search_member(app: hikari.GatewayBotAware, guild_id: int, name: str) -> typing.Optional[hikari.Member]: members = _member_cache.values() username, _, discriminator = name.rpartition("#") valid_discriminator = username and len(discriminator) == 4 name = username if valid_discriminator else name for i in range(2): if valid_discriminator and (member := utils.get( members, username=name, discriminator=discriminator)): return member if not valid_discriminator and (member := utils.find( members, lambda m: name in (m.username, m.nickname))): return member
async def member_converter(arg: WrappedArg) -> hikari.Member: """ Converter to transform a command argument into a :obj:`~hikari.Member` object. Args: arg (:obj:`WrappedArg`): Argument to transform. Returns: :obj:`~hikari.Member`: The member object resolved from the argument. Raises: :obj:`~.errors.ConverterFailure`: If the argument could not be resolved into a member object. """ try: user_id = _resolve_id_from_arg(arg.data, USER_MENTION_REGEX) except ValueError: members = arg.context.bot.cache.get_members_view_for_guild( arg.context.guild_id) member = utils.find( members.values(), lambda m: m.username == arg.data or m.nickname == arg.data or f"{m.username}#{m.discriminator}" == arg.data, ) else: member = arg.context.bot.cache.get_member(arg.context.guild_id, user_id) if member is None: member = await arg.context.bot.rest.fetch_member( arg.context.guild_id, user_id) return _raise_if_not_none(member)
async def user_converter(arg: WrappedArg) -> hikari.User: """ Converter to transform a command argument into a :obj:`hikari.UserImpl` object. Args: arg (:obj:`WrappedArg`): Argument to transform. Returns: :obj:`hikari.UserImpl`: The user object resolved from the argument. Raises: :obj:`~.errors.ConverterFailure`: If the argument could not be resolved into a user object. Example: .. code-block:: python @bot.command() async def username(ctx, user: lightbulb.user_converter): await ctx.reply(user.username) """ try: user_id = _resolve_id_from_arg(arg.data, USER_MENTION_REGEX) except ValueError: users = arg.context.bot.cache.get_users_view() user = utils.find( users.values(), lambda u: u.username == arg.data or f"{u.username}#{u.discriminator}" == arg.data) else: user = arg.context.bot.cache.get_user(user_id) if user is None: user = await arg.context.bot.rest.fetch_user(user_id) return _raise_if_not_none(user)
def parse_short_keys(self, argument: str) -> str: key = argument[1:] option = utils.find(self._short_options, key.startswith) if option: self.current = self.short_options[f"-{option}"] return key[len(option) :] while key: flag = utils.find(self._short_flags, key.startswith) if not flag: break self._short_flags.remove(flag) key = key[len(flag) :] self.data[self.short_flags[f"-{flag}"]] = [TRUE] else: return key self.current = self.remainder return key
async def on_error(self, event: lightbulb.CommandErrorEvent) -> None: """A listener that handles command errors.""" embed = hikari.Embed() author = event.message.author embed.set_author( name=str(author), icon=author.avatar_url or author.default_avatar_url, ) error = event.exception class_t = error if hasattr(error, "__mro__") else error.__class__ func = self.handlers.get( class_t, self.handlers.get( parent # pylint: disable=used-before-assignment if ( parent := utils.find( class_t.__mro__, lambda cls: cls in self.handlers, ) ) else None ), ) if func: func(event.context, error, embed) if embed.description: await event.context.respond(embed=embed) if isinstance( error, lightbulb.errors.CommandNotFound ) and event.message.content.startswith(error.invoked_with): # might not be the best thing to do # but since the context will be None if the command wasn't found # we'll just assume if the prefix was the same as the command name # then it's an empty prefix return _LOGGER.error( "Ignoring exception in command %s", event.command and event.command.qualified_name, exc_info=error, )
... def _get_spotify_act(self, user: typing.Any, raise_if_none: typing.Any = True) -> typing.Any: exc = NoSpotifyPresenceError("The member has no Spotify presences") if not (seq := self.bot.cache._presences_garbage.get(user.id)): raise exc if not (presence := next(iter(seq)).build_entity(self.bot)).activities: raise exc if (act := utils.find( presence.activities, lambda x: x.name and x.name == "Spotify" and x.type is hikari. ActivityType.LISTENING, )) is None and raise_if_none: raise exc return act and Spotify(act) @staticmethod def _get_font_color( base: typing.Sequence[int], seq: typing.Sequence[typing.Sequence[int]] ) -> typing.Tuple[int, ...]: """Gets the font color.""" base_y = get_luminance(base) for rgb in seq: y = get_luminance(rgb)