Пример #1
0
    async def inline_handler(self, event: telethon.events.InlineQuery.Event):
        offset = int(event.offset) if event.offset.isdigit() else 0
        next_offset = str(offset + RESULTS_PER_QUERY)

        terms = event.pattern_match.group(1).split(': ', 1)

        self.logger.debug('Inline query %s (offset=%s): %s', event.id, offset,
                          terms)

        if len(terms) == 2:
            tags_or_genres, search = terms
        else:
            tags_or_genres, search = terms[0], None

        tokens = {
            x.lower()
            for x in tags_or_genres.replace(', ', ',').split(',')
        }
        genres = tuple(tokens.intersection(self.GENRES))
        tags = tuple(tokens.intersection(self.TAGS))

        if not genres and not tags:
            search = tags_or_genres.replace(
                ',', ' ')  # none were found, use as search term

        body = {
            'query': self.QUERY,
            'variables': {
                'page': (offset // RESULTS_PER_QUERY) + 1,
                'perPage': RESULTS_PER_QUERY,
                'type': 'ANIME',
                'search': search,
                'genres': genres,
                'tags': tags
            }
        }

        for k, v in tuple(body['variables'].items()):
            if not v:
                body['variables'].pop(k)

        async with self.http.post(self.base_url, json=body) as resp:
            api_result = (await resp.json()) or {}
            api_result = (api_result.get('data') or {}).get('Page')

        if not api_result:
            await event.answer()

        if not api_result['pageInfo'].get('hasNextPage'):
            next_offset = None

        results = []
        for i, result in enumerate(api_result.get('media', tuple())):
            # manually unescape to avoid unexpected escapes
            d = self.HTML_REGEX.sub('', result['description']).replace(
                '"', '"')

            title = result['title']
            native = title.get('native')
            english = title.get('english')
            native_emoji = "🇯🇵" if result[
                'countryOfOrigin'] == 'JP' else ''
            img = result['coverImage']['large']
            links = f"<a href='{result['siteUrl']}'>AniList</a>"
            if result['idMal']:
                links += f" | <a href='https://myanimelist.net/anime/{result['idMal']}'>MAL</a>"

            results.append(await self.builder.article(
                title['romaji'],
                id=str(i),
                parse_mode='html',
                thumb=InputWebDocument(img, 0, 'image/jpeg', []),
                text=f"<a href=\"{escape(img)}\">\u200d</a>"
                f"<b>{escape(title['romaji'])}</b>\n" +
                (f"🇬🇧<b>{escape(english)}</b>\n" if english
                 and english.lower() != title['romaji'].lower() else '') +
                (f"{native_emoji}<b>{escape(native)}</b>\n" if native else '')
                +
                f"\n<b>{result['format'].capitalize()}</b>: {result['episodes']} episodes \n"  # NB: \n at start is to separate titles
                f"<b>Score</b>: {result['meanScore']}\n" +
                (f"<b>Genres</b>: {', '.join(result['genres'])}\n"
                 if result['genres'] else '') + f"<b>Description</b>:\n{d}"
                f"\n\n{links}"))

        self.logger.debug("Inline query %d: Processed %d results", event.id,
                          len(results))

        try:
            await event.answer(results,
                               next_offset=next_offset,
                               cache_time=self.cache_time)
        except telethon.errors.QueryIdInvalidError:
            pass
        except telethon.errors.RPCError:
            self.logger.warning("Inline QUERY %d: Sending results failed",
                                event.id,
                                exc_info=True)
        else:
            self.logger.debug("Inline QUERY %d: Complete", event.id)
Пример #2
0
async def ibuild(e):
    n = e.pattern_match.group(1).strip()
    builder = e.builder
    if not (n and n.isdigit()):
        return
    ok = STUFF.get(int(n))
    txt = ok.get("msg")
    pic = ok.get("media")
    btn = ok.get("button")
    if not (pic or txt):
        txt = "Hey!"
    if pic:
        try:
            include_media = True
            mime_type, _pic = None, None
            cont, results = None, None
            try:
                ext = str(pic).split(".")[-1].lower()
            except BaseException:
                ext = None
            if ext in ["img", "jpg", "png"]:
                _type = "photo"
                mime_type = "image/jpg"
            elif ext in ["mp4", "mkv", "gif"]:
                mime_type = "video/mp4"
                _type = "gif"
            else:
                try:
                    if "telethon.tl.types" in str(type(pic)):
                        _pic = pic
                    else:
                        _pic = resolve_bot_file_id(pic)
                except BaseException:
                    pass
                if _pic:
                    results = [
                        await builder.document(
                            _pic,
                            title="Ultroid Op",
                            text=txt,
                            description="@TheUltroid",
                            buttons=btn,
                            link_preview=False,
                        )
                    ]
                else:
                    _type = "article"
                    include_media = False
            if not results:
                if include_media:
                    cont = InputWebDocument(pic, 0, mime_type, [])
                results = [
                    await builder.article(
                        title="Ultroid Op",
                        type=_type,
                        text=txt,
                        description="@TeamUltroid",
                        include_media=include_media,
                        buttons=btn,
                        thumb=cont,
                        content=cont,
                        link_preview=False,
                    )
                ]
            return await e.answer(results)
        except Exception as er:
            LOGS.exception(er)
    result = [
        await builder.article("Ultroid Op",
                              text=txt,
                              link_preview=False,
                              buttons=btn)
    ]
    await e.answer(result)
Пример #3
0
 async def inline_handler(event):
     builder = event.builder
     result = None
     query = event.text
     if event.query.user_id == uid and query.startswith(
             "@SharingUserbot"):
         buttons = paginate_help(0, dugmeler, "helpme")
         result = builder.photo(
             file=logoman,
             link_preview=False,
             text=
             f"**✗ Man-Userbot Inline Menu ✗**\n\n✣ **Owner** [{user.first_name}](tg://user?id={user.id})\n✣ **Jumlah** `{len(dugmeler)}` Modules",
             buttons=buttons,
         )
     elif query.startswith("repo"):
         result = builder.article(
             title="Repository",
             description="Repository Man - Userbot",
             url="https://t.me/SharingUserbot",
             thumb=InputWebDocument(INLINE_PIC, 0, "image/jpeg", []),
             text=
             "**Man - UserBot**\n➖➖➖➖➖➖➖➖➖➖\n✣ **Owner Repo :** [Risman](https://t.me/mrismanaziz)\n✣ **Support :** @Lunatic0de\n✣ **Repository :** [Man-Userbot](https://github.com/mrismanaziz/Man-Userbot)\n➖➖➖➖➖➖➖➖➖➖",
             buttons=[
                 [
                     custom.Button.url("ɢʀᴏᴜᴘ",
                                       "https://t.me/SharingUserbot"),
                     custom.Button.url(
                         "ʀᴇᴘᴏ",
                         "https://github.com/mrismanaziz/Man-Userbot"),
                 ],
             ],
             link_preview=False,
         )
     elif query.startswith("Inline buttons"):
         markdown_note = query[14:]
         prev = 0
         note_data = ""
         buttons = []
         for match in BTN_URL_REGEX.finditer(markdown_note):
             n_escapes = 0
             to_check = match.start(1) - 1
             while to_check > 0 and markdown_note[to_check] == "\\":
                 n_escapes += 1
                 to_check -= 1
             if n_escapes % 2 == 0:
                 buttons.append((match.group(2), match.group(3),
                                 bool(match.group(4))))
                 note_data += markdown_note[prev:match.start(1)]
                 prev = match.end(1)
             elif n_escapes % 2 == 1:
                 note_data += markdown_note[prev:to_check]
                 prev = match.start(1) - 1
             else:
                 break
         else:
             note_data += markdown_note[prev:]
         message_text = note_data.strip()
         tl_ib_buttons = build_keyboard(buttons)
         result = builder.article(
             title="Inline creator",
             text=message_text,
             buttons=tl_ib_buttons,
             link_preview=False,
         )
     else:
         result = builder.article(
             title="✗ Man-Userbot ✗",
             description="Man - UserBot | Telethon",
             url="https://t.me/SharingUserbot",
             thumb=InputWebDocument(INLINE_PIC, 0, "image/jpeg", []),
             text=
             f"**Man - UserBot**\n➖➖➖➖➖➖➖➖➖➖\n✣ **UserMode:** [{user.first_name}](tg://user?id={user.id})\n✣ **Assistant:** {tgbotusername}\n➖➖➖➖➖➖➖➖➖➖\n**Support:** @Lunatic0de\n➖➖➖➖➖➖➖➖➖➖",
             buttons=[
                 [
                     custom.Button.url("ɢʀᴏᴜᴘ",
                                       "https://t.me/SharingUserbot"),
                     custom.Button.url(
                         "ʀᴇᴘᴏ",
                         "https://github.com/mrismanaziz/Man-Userbot"),
                 ],
             ],
             link_preview=False,
         )
     await event.answer([result],
                        switch_pm="👥 USERBOT PORTAL",
                        switch_pm_param="start")