コード例 #1
0
ファイル: funtions.py プロジェクト: zeki039/Geez-UserBot
async def ytsearch(query, limit):
    result = ""
    videolinks = VideosSearch(query.lower(), limit=limit)
    for v in videolinks.result()["result"]:
        textresult = f"[{v['title']}](https://www.youtube.com/watch?v={v['id']})\n"
        try:
            textresult += f"**Description : **`{v['descriptionSnippet'][-1]['text']}`\n"
        except Exception:
            textresult += "**Description : **`None`\n"
        textresult += f"**Duration : **__{v['duration']}__  **Views : **__{v['viewCount']['short']}__\n"
        result += f"☞ {textresult}\n"
    return result
コード例 #2
0
async def inline_id_handler(event: events.InlineQuery.Event):
    builder = event.builder
    if event.query.user_id != bot.uid:
        resultm = builder.article(
            title="Not Allowded",
            text=
            f"You Can't Use This Bot. \nDeploy VirtualUserbot To Get Your Own Assistant, Repo Link [Here](https://github.com/Inukaasith/virtualuserbot)",
        )
        await event.answer([resultm])
        return
    testinput = event.pattern_match.group(1)
    urllib.parse.quote_plus(testinput)
    results = []
    search = VideosSearch(f"{testinput}", limit=20)
    mi = search.result()
    moi = mi["result"]
    fk = 0
    if search == None:
        resultm = builder.article(
            title="No Results Found.",
            description="Check Your Spelling / Keyword",
            text="**Please, Search Again With Correct Keyword, Thank you !**",
            buttons=[
                [
                    Button.switch_inline("Search Again",
                                         query="yt ",
                                         same_peer=True)
                ],
            ],
        )
        await event.answer([resultm])
        return
    for mio in moi:
        mo = mio["link"]
        thum = mio["title"]
        fridayz = mio["id"]
        thums = mio["channel"]
        td = mio["duration"]
        kk = moi[fk]
        tw = kk["viewCount"]["text"]
        fk = fk + 1
        kekme = f"https://img.youtube.com/vi/{fridayz}/hqdefault.jpg"
        okayz = f"**Title :** `{thum}` \n**Link :** `{mo}` \n**Channel :** `{thums}` \n**Views :** `{tw}` \n**Duration :** `{td}`"
        hmmkek = f"Channel : {thums} \nDuration : {td} \nViews : {tw}"
        results.append(await event.builder.article(
            title=thum,
            description=hmmkek,
            text=okayz,
            buttons=Button.switch_inline("Search Again",
                                         query="yt ",
                                         same_peer=True),
        ))
    await event.answer(results)
コード例 #3
0
ファイル: ytdl.py プロジェクト: jpeiterson/ULTROID-BOT
async def _(event):
    try:
        string = event.text.split(" ", maxsplit=1)[1]
    except IndexError:
        fuk = event.builder.article(
            title="Search Something",
            thumb=wb(ytt, 0, "image/jpeg", []),
            text="**YᴏᴜTᴜʙᴇ Sᴇᴀʀᴄʜ**\n\nYou didn't search anything",
            buttons=Button.switch_inline(
                "Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
                query="yt ",
                same_peer=True,
            ),
        )
        await event.answer([fuk])
        return
    results = []
    search = VideosSearch(string, limit=10)
    nub = search.result()
    nibba = nub["result"]
    for v in nibba:
        link = v["link"]
        title = v["title"]
        ids = v["id"]
        duration = v["duration"]
        thumb = f"https://img.youtube.com/vi/{ids}/hqdefault.jpg"
        text = f"**•Tɪᴛʟᴇ•** `{title}`\n\n**••[Lɪɴᴋ]({link})••**\n\n**••Dᴜʀᴀᴛɪᴏɴ••** `{duration}`\n\n\n"
        desc = f"Title : {title}\nDuration : {duration}"
        results.append(
            await event.builder.document(
                file=thumb,
                title=title,
                description=desc,
                text=text,
                include_media=True,
                buttons=[
                    [
                        Button.inline("Audio", data=f"audio{link}"),
                        Button.inline("Video", data=f"video{link}"),
                    ],
                    [
                        Button.switch_inline(
                            "Sᴇᴀʀᴄʜ Aɢᴀɪɴ", query="yt ", same_peer=True
                        ),
                        Button.switch_inline(
                            "Sʜᴀʀᴇ", query=f"yt {string}", same_peer=False
                        ),
                    ],
                ],
            )
        )
    await event.answer(results)
コード例 #4
0
def search_videos(limit=30):
    video_search = VideosSearch('videos for cats to watch',
                                limit=limit,
                                language='en',
                                region='US')
    video_set = []
    while limit > len(video_set):
        if len(video_set) != 0:
            video_search.next()
        for vid in video_search.result()['result']:
            video_set.append(vid['link'])
            print(f"{vid['title']} - {vid['link']}")
    return video_set
コード例 #5
0
async def yts_search(video_q):
    approved_userss = approved_users.find({})
    for ch in approved_userss:
        iid = ch["id"]
        userss = ch["user"]
    if video_q.is_group:
        if await is_register_admin(video_q.input_chat,
                                   video_q.message.sender_id):
            pass
        elif video_q.chat_id == iid and video_q.sender_id == userss:
            pass
        else:
            return
    query = video_q.pattern_match.group(1)
    if not query.startswith("https://youtu.be/"):
        await video_q.reply("Invalid youtube link")
        return
    r = requests.get(query)
    if "Video unavailable" in r.text:
        await video_q.reply("Invalid youtube link")
        return
    videosSearch = VideosSearch(query, limit=1)
    h = videosSearch.result()
    if h["result"] == []:
        await video_q.reply("Invalid youtube link")
        return
    title = h["result"][0]["title"]
    ptime = h["result"][0]["publishedTime"]
    dur = h["result"][0]["duration"]
    views = h["result"][0]["viewCount"]["short"]
    des = h["result"][0]["descriptionSnippet"][0]["text"]
    chn = h["result"][0]["channel"]["name"]
    chnl = h["result"][0]["channel"]["link"]
    vlink = h["result"][0]["link"]
    g = h["result"][0]["thumbnails"][0]["url"]
    f = re.sub("\?.*$", "", g)
    final = f"""**Extracted information from youtube**:\n
**Title**: `{title}`
**Published Time**: `{ptime}`
**Duration**: `{dur}`
**Views**: `{views}`
**Description**: `{des}`
**Channel Name**: `{chn}`
**Channel Link**: `{chnl}`
**Video Link**: `{vlink}`
"""
    await tbot.send_file(video_q.chat_id,
                         f,
                         reply_to=video_q.id,
                         file_name="thumb.jpg",
                         caption=final)
コード例 #6
0
ファイル: inline.py プロジェクト: dashamoolam/MusicPlayer
async def search(client, query):
    answers = []
    if query.query == "ORU_MANDAN_PM_VANNU":
        answers.append(
            InlineQueryResultArticle(
                title="Deploy",
                input_message_content=InputTextMessageContent(f"{REPLY_MESSAGE}\n\n<b>You can't use this bot in your group, for that you have to make your own bot from the [SOURCE CODE](https://github.com/subinps/MusicPlayer) below.</b>", disable_web_page_preview=True),
                reply_markup=InlineKeyboardMarkup(buttons)
                )
            )
        await query.answer(results=answers, cache_time=0)
        return
    string = query.query.lower().strip().rstrip()
    if string == "":
        await client.answer_inline_query(
            query.id,
            results=answers,
            switch_pm_text=("Search a youtube video"),
            switch_pm_parameter="help",
            cache_time=0
        )
    else:
        videosSearch = VideosSearch(string.lower(), limit=50)
        for v in videosSearch.result()["result"]:
            answers.append(
                InlineQueryResultArticle(
                    title=v["title"],
                    description=("Duration: {} Views: {}").format(
                        v["duration"],
                        v["viewCount"]["short"]
                    ),
                    input_message_content=InputTextMessageContent(
                        "/play https://www.youtube.com/watch?v={}".format(
                            v["id"]
                        )
                    ),
                    thumb_url=v["thumbnails"][0]["url"]
                )
            )
        try:
            await query.answer(
                results=answers,
                cache_time=0
            )
        except errors.QueryIdInvalid:
            await query.answer(
                results=answers,
                cache_time=0,
                switch_pm_text=("Nothing found"),
                switch_pm_parameter="",
            )
コード例 #7
0
ファイル: youTube.py プロジェクト: a96lex/hackviolet
def getYoutubeVideos(query):
    search = VideosSearch(query)
    print("search", search)

    response = search.result()["result"]

    count = 0

    print("len response", len(response))
    while len(response) < 100 and count < 10:
        search.next()
        response += search.result()["result"]
        count += 1

    response = response[:2]

    print("link", response[0]["link"])

    for video in response:
        # if isFemale(video["link"]):
        addToDb(video, query)
        # else:
        #     continue
    return None
コード例 #8
0
def search_youtube(value: str, parameters={'limit': 1}) -> dict:
    """
    Function to search only first video on YouTube
    :param value: what we need to search
    :param parameters: some parameters, such as limit, language, region
    :return: dictionary with main information
    """
    search = VideosSearch(value, **parameters)
    result = search.result()['result'][0]
    return {
        'title': result['title'],
        'duration': result['duration'],
        'views': result['viewCount']['short'],
        'song_id': result['link'].split('https://www.youtube.com/watch?v=')[-1],
    }
コード例 #9
0
    async def play(self, ctx, *, url=None):
        if not ctx.voice_client:
            channel = ctx.author.voice
            if not channel:
                await ctx.send(
                    "You need to be in a voice channel to use this command.")
            await channel.channel.connect()

        if url is None:
            if self.queue.is_paused:
                self.queue.resume()
            else:
                raise commands.BadArgument

        if not ("http://" in url or "https://" in url):
            search_term = url

            if "-list" in search_term:
                search_term = search_term.replace("-list", "")
                await ctx.invoke(self.bot.get_command("search"),
                                 search_term=search_term)

                return
            else:
                search = VideosSearch(search_term, limit=1)
                watch_id = search.result()["result"][0]["id"]

                url = f"https://www.youtube.com/watch?v={watch_id}"

        self.queue.add(url, ctx)

        songs = self.queue.get_queue_songs()

        if len(songs) == 1:
            await ctx.send(embed=discord.Embed(
                title="Playing now! :musical_note:",
                description=
                f"**{songs[0].title}**\nDuration: {self.formatted_time(songs[0].duration)}"
            ))
        else:
            playtime = sum(song.duration for song in songs[1:]
                           ) + self.queue.song_time_left().total_seconds()
            await ctx.send(embed=discord.Embed(
                title="Added to queue! :musical_note:",
                description=
                f"**{songs[-1].title}**\n Time until playing: {self.formatted_time(playtime)}"
            ))
コード例 #10
0
    async def search(self, ctx, *, search_term):
        if not search_term:
            raise commands.UserInputError()

        search = VideosSearch(search_term, limit=10)
        res = search.result()["result"]

        # display search message
        send = self.formatted_search(res)
        msg = await ctx.send(embed=discord.Embed(
            title=f"Search results: {search_term}", description=send))

        emoji_list = [
            "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟"
        ]
        for emoji in emoji_list:
            await msg.add_reaction(emoji)

        def check(reaction, user):
            return user == ctx.message.author and reaction.emoji in emoji_list

        react = None

        try:
            reaction, user = await self.bot.wait_for('reaction_add',
                                                     timeout=60.0,
                                                     check=check)
            react = reaction.emoji
        except asyncio.TimeoutError:
            await ctx.channel.send(embed=discord.Embed(
                description="**Search timed out.**"))
            await msg.clear_reactions()
        else:
            if not ctx.voice_client:
                channel = ctx.author.voice
                if not channel:
                    await ctx.send(
                        "You need to be in a voice channel to use this command."
                    )
                await channel.channel.connect()

            url = res[emoji_list.index(react)]['link']
            await ctx.invoke(self.bot.get_command("play"), url=url)

            await msg.clear_reactions()
コード例 #11
0
ファイル: inline.py プロジェクト: abbasdurakk/zevzekbot
async def inline(client: Client, query: InlineQuery):
    answers = []
    search_query = query.query.lower().strip().rstrip()

    if search_query == "":
        await client.answer_inline_query(
            query.id,
            results=answers,
            switch_pm_text="YouTube videosu adı yazın ...",
            switch_pm_parameter="help",
            cache_time=0
        )
    else:
        search = VideosSearch(search_query, limit=50)

        for result in search.result()["sonuç"]:
            answers.append(
                InlineQueryResultArticle(
                    title=result["Başlık"],
                    description="{}, {} görüntüleme.".format(
                        result["süre"],
                        result["viewCount"]["short"]
                    ),
                    input_message_content=InputTextMessageContent(
                        "https://www.youtube.com/watch?v={}".format(
                            result["id"]
                        )
                    ),
                    thumb_url=result["fotografı"][0]["url"]
                )
            )

        try:
            await query.answer(
                results=answers,
                cache_time=0
            )
        except errors.QueryIdInvalid:
            await query.answer(
                results=answers,
                cache_time=0,
                switch_pm_text="Hata: Arama zaman aşımına uğradı",
                switch_pm_parameter="",
            )
コード例 #12
0
ファイル: inline.py プロジェクト: matalata02/gatau
async def inline(client: Client, query: InlineQuery):
    answers = []
    search_query = query.query.lower().strip().rstrip()

    if search_query == "":
        await client.answer_inline_query(
            query.id,
            results=answers,
            switch_pm_text="Ketikkan nama Lagu/video di YouTube...",
            switch_pm_parameter="help",
            cache_time=0
        )
    else:
        search = VideosSearch(search_query, limit=50)

        for result in search.result()["result"]:
            answers.append(
                InlineQueryResultArticle(
                    title=result["title"],
                    description="{}, {} views.".format(
                        result["duration"],
                        result["viewCount"]["short"]
                    ),
                    input_message_content=InputTextMessageContent(
                        "https://www.youtube.com/watch?v={}".format(
                            result["id"]
                        )
                    ),
                    thumb_url=result["thumbnails"][0]["url"]
                )
            )

        try:
            await query.answer(
                results=answers,
                cache_time=0
            )
        except errors.QueryIdInvalid:
            await query.answer(
                results=answers,
                cache_time=0,
                switch_pm_text="Error: Search timed out",
                switch_pm_parameter="",
            )
コード例 #13
0
ファイル: inline.py プロジェクト: LEGENDXOP/VCMUSIC
def search(client, query):
    answers = []
    string = query.query.lower().strip().rstrip()

    if string == "":
        client.answer_inline_query(
            query.id,
            results=answers,
            switch_pm_text=_("inline_1"),
            switch_pm_parameter="help",
            cache_time=0
        )
        return
    else:
        videosSearch = VideosSearch(string.lower(), limit=50)
        for v in videosSearch.result()["result"]:
            answers.append(
                InlineQueryResultArticle(
                    title=v["title"],
                    description=_("inline_2").format(
                        v["duration"],
                        v["viewCount"]["short"]
                    ),
                    input_message_content=InputTextMessageContent(
                        "https://www.youtube.com/watch?v={}".format(
                            v["id"]
                        )
                    ),
                    thumb_url=v["thumbnails"][0]["url"]
                )
            )
        try:
            query.answer(
                results=answers,
                cache_time=0
            )
        except errors.QueryIdInvalid:
            query.answer(
                results=answers,
                cache_time=0,
                switch_pm_text=_("inline_3"),
                switch_pm_parameter="",
            )
コード例 #14
0
async def songs(ctx):
    l = len(song_url)
    if (l == 0):
        await ctx.send("No music to play")
    for i in range(0, l):
        videosSearch = VideosSearch(song_url[i], limit=1)
        result_song_list = videosSearch.result()
        # print(result_song_list)
        title_song = result_song_list['result'][0]['title']
        text = discord.Embed(
            description=f"{i+1}# Song Name : {title_song} ",
            color=53380,
        )
        text.set_author(
            name="Discord_music_bot",
            icon_url=
            "https://static.vecteezy.com/system/resources/thumbnails/000/371/212/small/1781.jpg"
        )
        await ctx.send(embed=text)
コード例 #15
0
def search(title, dur, info = {}):
    vsearch = VideosSearch(f'{title} {info["album"]} music', limit = 5)
    result = vsearch.result()

    final = []
    
    for item in result["result"]:
        print("-"*20)
        print(f'time: {item["duration"]} -> {countSec(item["duration"])}')
        print(item["type"])

        data = {
            "origin": item,
            "dur_count": dur - countSec(item["duration"])
        }

        final.append(data)
    
    return final
コード例 #16
0
    async def play(self, ctx, *, url):
        """Streams from an url or searches for song name"""
        vc = ctx.voice_client
        if not validators.url(url):
            search_result = VideosSearch(url, limit=1)
            url = search_result.result()['result'][0]['link']

        if vc.is_playing():
            self.player_queue.append(await self.from_url(url,
                                                         loop=self.bot.loop,
                                                         stream=True))
            await ctx.respond("🎶 Added: " + self.song_queue[-1] +
                              " to the playlist")
            return

        player = await self.from_url(url, loop=self.bot.loop, stream=True)
        self.player_queue.append(player)
        ctx.voice_client.play(player, after=lambda e: self.play_next(ctx))
        await ctx.respond("🎶 Now Playing: " + self.song_queue[-1])
コード例 #17
0
            def Youtube(self):
                videosSearch = VideosSearch(motcle, limit=50)
                for keys, values in videosSearch.result().items():
                    res = values[0:11]
                    link_list = []
                    i = 0
                    while i < 10:
                        res1 = res[i]
                        for key, value in res1.items():
                            if key == 'link':
                                link_list.append(value)
                                i += 1

                    label = tk.Label(
                        self,
                        text=
                        "Les dix premiers résultats de la recherche avec le mot clé ''"
                        + motcle + "'' sont :\n\n",
                        justify=LEFT,
                        anchor=NE)
                    label.grid(column=3, sticky="NE", padx=800)
                    label.place(x=300, relx=0.8, rely=0.15, anchor=NE)

                    passortie = 0.2
                    j = 1
                    for i in link_list:
                        print(i + "\n")
                        label1 = tk.Label(self,
                                          text="Sortie " + str(j) + " : " + i +
                                          "\n",
                                          justify=LEFT,
                                          anchor=NE)
                        label1.grid(column=3, sticky="NE", padx=800)
                        label1.place(x=300,
                                     relx=0.8,
                                     rely=passortie,
                                     anchor=NE)
                        passortie += 0.05
                        # Get first result
                        if j == 1:
                            global url_firstvideo
                            url_firstvideo = i
                        j += 1
コード例 #18
0
ファイル: yt-ds.py プロジェクト: IBR-41379/yt-ds
def searchyoutube():
    a = input("Enter items to be searched :")
    b = int(input("Enter number of results you want to search :"))
    videosSearch = VideosSearch(a, limit=b)
    x = videosSearch.result()
    for r in x:
        l = x[r]
        for i in range(b):
            j = str(i)
            m = l[i]
            n = m['channel']
            p = n['name']
            o = m['title']
            print()
            print(j + ')' + 'channel name :' + p + '\n' + 'Videoname :' + o +
                  '\n' + 'link :' + m['link'])
        s = int(input("\nEnter number :"))
        t = l[s]
        u = t['link']
        return u
コード例 #19
0
ファイル: query.py プロジェクト: goncrust/pyMP
def queryKeywordPlus(keyword, count):
    """Query video title, URL and duration
    """

    result = VideosSearch(keyword, limit=count)
    resultParsed = {}

    i = 1
    for r in result.result()['result']:
        resultParsed[str(i)] = {}
        resultParsed[str(i)]['title'] = r['title']
        resultParsed[str(i)]['link'] = r['link']
        resultParsed[str(i)]['duration'] = r['duration']

        i += 1

    if not len(resultParsed):
        return -1

    return resultParsed
コード例 #20
0
ファイル: downloader.py プロジェクト: bentrey/WKSLG
def youtube_downloader(numberOfSongs, dir="library"):
    for n in range(numberOfSongs):
        try:
            title = np.random.choice(os.listdir('library/rotation/'))
            artist = title.split("-")[0]
            videosSearch = VideosSearch(artist, limit=10)
            choice = np.random.choice(videosSearch.result()['result'])
            title = choice['title']
            duration = choice['duration']
            times = duration.split(':')
            if len(times) == 2:
                if int(times[0]) < 20:
                    artist = title.split("-")[0]
                    song = "-".join(title.split("-"))
                    get_file(artist, song)
            elif len(times) == 1:
                artist = title.split("-")[0]
                song = "-".join(title.split("-"))
                get_file(artist, song)
        except:
            pass
コード例 #21
0
ファイル: query_script.py プロジェクト: CUQS/YoutubeWorker
def youtube_query(query, json_file, language='en', page=30, max_minu=30):
    json_worker = JsonWorker(json_file)
    page_finish = False
    video_list = []
    videosSearch = VideosSearch(query, language=language)
    print("---------------- {} ----------------".format(query))
    for page_i in tqdm(range(page)):
        error_flag = False
        video_meta = search_results_select(
            videosSearch.result(), max_duration=[0, max_minu, 0])
        if len(video_meta) > 1:
            video_list.extend(video_meta)
        try:
            videosSearch.next()
        except:
            error_flag = True
        if error_flag:
            break
        time.sleep(2)
        if page_i == page-1:
            page_finish = True
    if len(video_list) >= 1:
        count = 0
        for vi in video_list:
            if json_worker.check_in(vi["vid"]):
                continue
            count += 1
            vi["query"] = query_all[language][query]
            json_worker.add_one(vi, vi["vid"])
        if count >= 1:
            print("{}: {}".format(query, count))
            json_worker.save()
        else:
            print("{}: {}".format(query, 0))
    else:
        print("{}: {}".format(query, 0))

    return page_finish
コード例 #22
0
async def yts_search(video_q):
    query = video_q.pattern_match.group(1)
    videosSearch = VideosSearch(query, limit=1)
    h = videosSearch.result()
    title = (h['result'][0]['title'])
    ptime = (h['result'][0]['publishedTime'])
    dur = (h['result'][0]['duration'])
    views = (h['result'][0]['viewCount']['short'])
    des = (h['result'][0]['descriptionSnippet'][0]['text'])
    chn = (h['result'][0]['channel']['name'])
    chnl = (h['result'][0]['channel']['link'])
    vlink = (h['result'][0]['link'])
    final = f"""**Extracted information from youtube**:
**Title**: `{title}`
**Published Time**: `{ptime}`
**Duration**: `{dur}`
**Views**: `{views}`
**Description**: `{des}`
**Channel Name**: `{chn}`
**Channel Link**: `{chnl}`
**Video Link**: `{vlink}`
"""
    await video_q.reply(final)
コード例 #23
0
async def add(ctx, *, searched_song):
    print(searched_song)

    videosSearch = VideosSearch(searched_song, limit=1)
    result_song_list = videosSearch.result()
    # print(result_song_list)
    title_song = result_song_list['result'][0]['title']
    urllink = result_song_list['result'][0]['link']

    song_url.append(urllink)
    text = discord.Embed(
        title="**Song Added**",
        description=f"{title_song} is added to the Queue\nLink : {urllink}",
        color=53380,
    )
    # text.add_image(url=f"{result_song_list['result'][0]['thumbnail']['url']}")
    text.set_author(
        name="Discord_music_bot",
        icon_url=
        "https://static.vecteezy.com/system/resources/thumbnails/000/371/212/small/1781.jpg"
    )
    text.set_footer(text="m.help to know commands")
    await ctx.send(embed=text)
コード例 #24
0
async def ytplay(client, chat_id, requested_by, query):
    m = await client.send_message(chat_id,
                                  f"__**Searching for {query} on YouTube.**__",
                                  disable_web_page_preview=True)
    try:
        videosSearch = VideosSearch(query[0], limit=6)
        results = videosSearch.result()['result']
        # results = await arq.youtube(query[0], 6)
        text = "**Results:**\n\n"
        songbt = []
        for num in range(0, len(results) - 1):
            title = results[num]['title']
            duration = results[num]['duration']
            views = results[num]['viewCount']['short']
            url = f"{results[num]['id']}"
            text += f"  __{num + 1}.__ **{title}** {duration} views: {views}\n"
            songbt.append(
                InlineKeyboardButton(f"{num + 1}",
                                     f'choose_{requested_by}_{url}'))
        await m.edit(text, reply_markup=InlineKeyboardMarkup([songbt]))
    except Exception as e:
        await m.edit("__**Found No Song Matching Your Query.**__")
        print(str(e))
        return
コード例 #25
0
async def _(event):
    try:
        string = event.text.split(" ", maxsplit=1)[1]
    except IndexError:
        fuk = event.builder.article(
            title="Search Something",
            thumb=wb(ytt, 0, "image/jpeg", []),
            text="**YᴏᴜTᴜʙᴇ Sᴇᴀʀᴄʜ**\n\nYou didn't search anything",
            buttons=Button.switch_inline(
                "Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
                query="yt ",
                same_peer=True,
            ),
        )
        await event.answer([fuk])
        return
    results = []
    search = VideosSearch(string, limit=10)
    nub = search.result()
    nibba = nub["result"]
    for v in nibba:
        ids = v["id"]
        link = _yt_base_url + ids
        title = v["title"]
        duration = v["duration"]
        views = v["viewCount"]["short"]
        publisher = v["channel"]["name"]
        published_on = v["publishedTime"]
        description = (
            v["descriptionSnippet"][0]["text"] if v.get("descriptionSnippet")
            and len(v["descriptionSnippet"][0]["text"]) < 500 else "None")
        thumb = f"https://i.ytimg.com/vi/{ids}/hqdefault.jpg"
        text = f"<strong>Title:- <a href={link}>{title}</a></strong>\n"
        text += f"<strong>⏳ Duration:-</strong> <code>{duration}</code>\n"
        text += f"<strong>👀 Views:- </strong> <code>{views}</code>\n"
        text += f"<strong>🎙️ Publisher:- </strong> <code>{publisher}</code>\n"
        text += f"<strong>🗓️ Published on:- </strong> <code>{published_on}</code>\n"
        text += f"<strong>📝 Description:- </strong> <code>{description}</code>"
        desc = f"{title}\n{duration}"
        file = wb(thumb, 0, "image/jpeg", [])
        buttons = [
            [
                Button.inline("Audio", data=f"ytdl:audio:{ids}"),
                Button.inline("Video", data=f"ytdl:video:{ids}"),
            ],
            [
                Button.switch_inline(
                    "Sᴇᴀʀᴄʜ Aɢᴀɪɴ",
                    query="yt ",
                    same_peer=True,
                ),
                Button.switch_inline(
                    "Sʜᴀʀᴇ",
                    query=f"yt {string}",
                    same_peer=False,
                ),
            ],
        ]
        BACK_BUTTON.update(
            {ids: {
                "text": text,
                "buttons": buttons,
                "parse_mode": "html"
            }})
        results.append(
            await event.builder.article(
                type="photo",
                title=title,
                description=desc,
                thumb=file,
                content=file,
                text=text,
                include_media=True,
                parse_mode="html",
                buttons=buttons,
            ), )
    await event.answer(results[:50])
コード例 #26
0
ファイル: help.py プロジェクト: sandy1709/USERGE-X
    async def inline_answer(_, inline_query: InlineQuery):
        results = []
        i_q = inline_query.query
        string = i_q.lower()  # All lower
        str_x = i_q.split(" ", 2)  # trigger @username Text
        str_y = i_q.split(" ", 1)  # trigger and Text
        string_split = string.split()  # All lower and Split each word

        if (inline_query.from_user.id in Config.OWNER_ID
                or inline_query.from_user.id in Config.SUDO_USERS):

            if string == "syntax":
                owner = [[
                    InlineKeyboardButton(text="Contact",
                                         url="https://t.me/deleteduser420")
                ]]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url=
                        "https://coverfiles.alphacoders.com/123/123388.png",
                        caption="Hey I solved **𝚂𝚢𝚗𝚝𝚊𝚡's ░ Σrr♢r**",
                        reply_markup=InlineKeyboardMarkup(owner),
                    ))

            if string == "age_verification_alert":
                buttons = [[
                    InlineKeyboardButton(
                        text="Yes I'm 18+",
                        callback_data="age_verification_true"),
                    InlineKeyboardButton(
                        text="No I'm Not",
                        callback_data="age_verification_false"),
                ]]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url="https://i.imgur.com/Zg58iXc.jpg",
                        caption="**ARE YOU OLD ENOUGH FOR THIS ?**",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if str_y[0] == "reddit":
                reddit_api = "https://meme-api.herokuapp.com/gimme/"
                if len(str_y) == 2:
                    subreddit_regex = r"^([a-zA-Z]+)\.$"
                    match = re.search(subreddit_regex, str_y[1])
                    if match:
                        subreddit_name = match.group(1)
                        reddit_api += f"{subreddit_name}/30"
                    else:
                        return
                else:
                    reddit_api += "30"
                try:
                    r = await get_response.json(reddit_api)
                except ValueError:
                    results.append(
                        InlineQueryResultArticle(
                            title="Reddit Api is Down !",
                            input_message_content=InputTextMessageContent(
                                "**Error Code: Status != 200**"),
                            thumb_url="https://i.imgur.com/7a7aPVa.png",
                        ))
                else:
                    if "code" in r:
                        bool_is_gallery = False
                        code = r["code"]
                        code_message = r["message"]
                        results.append(
                            InlineQueryResultArticle(
                                title=str(code),
                                input_message_content=InputTextMessageContent(
                                    f"**Error Code: {code}**\n`{code_message}`"
                                ),
                                description="Enter A Valid Subreddit Name !",
                                thumb_url="https://i.imgur.com/7a7aPVa.png",
                            ))
                    else:
                        bool_is_gallery = True
                        for post in r["memes"]:
                            if "url" in post:
                                postlink = post["postLink"]
                                subreddit = post["subreddit"]
                                title = post["title"]
                                media_url = post["url"]
                                author = post["author"]
                                upvote = post["ups"]
                                captionx = f"<b>{title}</b>\n"
                                captionx += f"`Posted by u/{author}`\n"
                                captionx += f"↕️ <code>{upvote}</code>\n"
                                thumbnail = reddit_thumb_link(post["preview"])
                                if post["spoiler"]:
                                    captionx += "⚠️ Post marked as SPOILER\n"
                                if post["nsfw"]:
                                    captionx += "🔞 Post marked Adult \n"
                                buttons = [[
                                    InlineKeyboardButton(
                                        f"Source: r/{subreddit}", url=postlink)
                                ]]
                                if media_url.endswith(".gif"):
                                    results.append(
                                        InlineQueryResultAnimation(
                                            animation_url=media_url,
                                            thumb_url=thumbnail,
                                            caption=captionx,
                                            reply_markup=InlineKeyboardMarkup(
                                                buttons),
                                        ))
                                else:
                                    results.append(
                                        InlineQueryResultPhoto(
                                            photo_url=media_url,
                                            thumb_url=thumbnail,
                                            caption=captionx,
                                            reply_markup=InlineKeyboardMarkup(
                                                buttons),
                                        ))
                    await inline_query.answer(
                        results=results,
                        cache_time=1,
                        is_gallery=bool_is_gallery,
                        switch_pm_text="Available Commands",
                        switch_pm_parameter="inline",
                    )
                    return

            # if string == "rick":
            #     rick = [[InlineKeyboardButton(text="🔍", callback_data="mm")]]
            #     results.append(
            #         InlineQueryResultArticle(
            #             title="Not a Rick Roll",
            #             input_message_content=InputTextMessageContent("Search Results"),
            #             description="Definately Not a Rick Roll",
            #             thumb_url="https://i.imgur.com/hRCaKAy.png",
            #             reply_markup=InlineKeyboardMarkup(rick),
            #         )
            #     )

            if string == "alive":
                buttons = [[
                    InlineKeyboardButton("🔧 SETTINGS",
                                         callback_data="settings_btn"),
                    InlineKeyboardButton(text="⚡️ REPO",
                                         url=Config.UPSTREAM_REPO),
                ]]

                alive_info = f"""
    **[USERGE-X](https://telegram.dog/x_xtests) is Up and Running**

 • 🐍 Python :  `v{versions.__python_version__}`
 • 🔥 Pyrogram :  `v{versions.__pyro_version__}`
 • 🧬 𝑿 :  `v{get_version()}`

{_get_mode()}  |  🕔: {userge.uptime}
"""

                if not MEDIA_URL and Config.ALIVE_MEDIA:
                    await get_alive_()

                if MEDIA_URL:
                    if MEDIA_TYPE == "url_gif":
                        results.append(
                            InlineQueryResultAnimation(
                                animation_url=MEDIA_URL,
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons),
                            ))
                    elif MEDIA_TYPE == "url_image":
                        results.append(
                            InlineQueryResultPhoto(
                                photo_url=MEDIA_URL,
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons),
                            ))
                    elif MEDIA_TYPE == "tg_image":
                        results.append(
                            InlineQueryResultCachedPhoto(
                                file_id=MEDIA_URL,
                                caption=alive_info,
                                reply_markup=InlineKeyboardMarkup(buttons),
                            ))
                    else:
                        results.append(
                            InlineQueryResultCachedDocument(
                                title="USERGE-X",
                                file_id=MEDIA_URL,
                                caption=alive_info,
                                description="ALIVE",
                                reply_markup=InlineKeyboardMarkup(buttons),
                            ))
                else:  # default
                    random_alive = random.choice(ALIVE_IMGS)
                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=random_alive,
                            caption=alive_info,
                            reply_markup=InlineKeyboardMarkup(buttons),
                        ))

            if string == "geass":
                results.append(
                    InlineQueryResultAnimation(
                        animation_url="https://i.imgur.com/DeZHcRK.gif",
                        caption="To defeat evil, I must become a greater evil",
                    ))

            if string == "gapps":
                buttons = [
                    [
                        InlineKeyboardButton("Open GApps",
                                             callback_data="open_gapps"),
                        InlineKeyboardButton("Flame GApps",
                                             callback_data="flame_gapps"),
                    ],
                    [
                        InlineKeyboardButton("Nik GApps",
                                             callback_data="nik_gapps")
                    ],
                ]
                results.append(
                    InlineQueryResultArticle(
                        title="GApps",
                        input_message_content=InputTextMessageContent(
                            "[\u200c](https://i.imgur.com/BZBMrfn.jpg) **LATEST Android 10 arm64 GApps**"
                        ),
                        description=
                        "Get Latest GApps Download Links Directly from SF",
                        thumb_url="https://i.imgur.com/Npzw8Ph.png",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if len(string_split) == 2 and (string_split[0] == "ofox"):
                codename = string_split[1]
                t = TelegraphPoster(use_api=True)
                t.create_api_token("Userge-X")
                photo = "https://i.imgur.com/582uaSk.png"
                api_host = "https://api.orangefox.download/v2/device/"
                try:
                    cn = requests.get(f"{api_host}{codename}")
                    r = cn.json()
                except ValueError:
                    return
                s = requests.get(
                    f"{api_host}{codename}/releases/stable/last").json()
                info = f"📱 **Device**: {r['fullname']}\n"
                info += f"👤 **Maintainer**: {r['maintainer']['name']}\n\n"
                recovery = f"🦊 <code>{s['file_name']}</code>\n"
                recovery += f"📅 {s['date']}\n"
                recovery += f"ℹ️ **Version:** {s['version']}\n"
                recovery += f"📌 **Build Type:** {s['build_type']}\n"
                recovery += f"🔰 **Size:** {s['size_human']}\n\n"
                recovery += "📍 **Changelog:**\n"
                recovery += f"<code>{s['changelog']}</code>\n\n"
                msg = info
                msg += recovery
                notes_ = s.get("notes")
                if notes_:
                    notes = t.post(title="READ Notes", author="", text=notes_)
                    buttons = [[
                        InlineKeyboardButton("🗒️ NOTES", url=notes["url"]),
                        InlineKeyboardButton("⬇️ DOWNLOAD", url=s["url"]),
                    ]]
                else:
                    buttons = [[
                        InlineKeyboardButton(text="⬇️ DOWNLOAD", url=s["url"])
                    ]]

                results.append(
                    InlineQueryResultPhoto(
                        photo_url=photo,
                        thumb_url="https://i.imgur.com/o0onLYB.jpg",
                        title="Latest OFOX RECOVERY",
                        description=f"For device : {codename}",
                        caption=msg,
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if string == "repo":
                results.append(REPO_X)

            if len(str_y) == 2 and str_y[0] == "anime":
                for i in await Anime.search(str_y[1]):
                    results.append(
                        InlineQueryResultArticle(
                            title=i.get("title"),
                            input_message_content=InputTextMessageContent(
                                f'[\u200c]({i.get("image")})**{i.get("title")}**\n{i.get("release")}'
                            ),
                            description=i.get("release"),
                            thumb_url=i.get("image"),
                            reply_markup=InlineKeyboardMarkup([[
                                InlineKeyboardButton(
                                    text="⬇️  Download",
                                    callback_data=f'get_eps{i.get("key")}',
                                )
                            ]]),
                        ))
                if len(results) != 0:
                    await inline_query.answer(
                        results=results[:50],
                        cache_time=1,
                        switch_pm_text="Available Commands",
                        switch_pm_parameter="inline",
                    )
                    return

            if str_y[0] == "spoiler":
                if not os.path.exists("./userge/xcache/spoiler_db.json"):
                    results.append(
                        InlineQueryResultArticle(
                            title="No Spoiler Found",
                            input_message_content=InputTextMessageContent(
                                "No Spoiler Found !\nLet's Add Some 😈"),
                            description="See .help spoiler for more info",
                        ))
                else:
                    bot_name = (await userge.bot.get_me()).username
                    if len(str_y) == 2:
                        link = f"https://t.me/{bot_name}?start=spoiler_{str_y[1]}"
                        buttons = [[
                            InlineKeyboardButton(text="View Spoiler", url=link)
                        ]]
                        results.append(
                            InlineQueryResultArticle(
                                title="Spoiler",
                                input_message_content=InputTextMessageContent(
                                    "<b>Click To View The Spoiler !</b>"),
                                description="Click To Send",
                                thumb_url=
                                "https://telegra.ph/file/ee3a6439494463acd1a3a.jpg",
                                reply_markup=InlineKeyboardMarkup(buttons),
                            ))
                    else:
                        fo = open("./userge/xcache/spoiler_db.json")
                        view_db = ujson.load(fo)
                        fo.close()
                        if len(view_db) != 0:
                            for numm, spoilerr in enumerate(view_db, start=1):
                                buttons = [[
                                    InlineKeyboardButton(
                                        text="View Spoiler",
                                        url=
                                        f"https://t.me/{bot_name}?start=spoiler_{spoilerr}",
                                    )
                                ]]
                                saved_at = view_db.get(spoilerr, None)
                                savetime = (saved_at.get("savetime", None)
                                            if saved_at else None)
                                results.append(
                                    InlineQueryResultArticle(
                                        title=f"#{numm}  Spoiler",
                                        input_message_content=
                                        InputTextMessageContent(
                                            "<b>Click To View The Spoiler !</b>"
                                        ),
                                        description=f"Created At: {savetime}",
                                        thumb_url=
                                        "https://telegra.ph/file/ee3a6439494463acd1a3a.jpg",
                                        reply_markup=InlineKeyboardMarkup(
                                            buttons),
                                    ))

            if str_x[0].lower() == "op" and len(str_x) > 1:
                txt = i_q[3:]

                opinion = os.path.join(PATH, "emoji_data.txt")
                if os.path.exists(opinion):
                    with open(opinion) as fo:
                        view_data = ujson.load(fo)
                    # Uniquely identifies an inline message
                    new_id = {int(inline_query.id): [{}]}
                    view_data.update(new_id)
                else:
                    view_data = {int(inline_query.id): [{}]}

                with open(opinion, "w") as outfile:
                    ujson.dump(view_data, outfile)

                buttons = [[
                    InlineKeyboardButton(
                        "👍", callback_data=f"op_y_{inline_query.id}"),
                    InlineKeyboardButton(
                        "👎", callback_data=f"op_n_{inline_query.id}"),
                ]]
                results.append(
                    InlineQueryResultArticle(
                        title="Ask For Opinion",
                        input_message_content=InputTextMessageContent(txt),
                        description=f"Q. {txt}",
                        thumb_url="https://i.imgur.com/Zlc98qS.jpg",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if "btn_" in str_y[0] or str_y[0] == "btn":

                inline_db_path = "./userge/xcache/inline_db.json"
                if os.path.exists(inline_db_path):
                    with open(inline_db_path, "r") as data_file:
                        view_db = ujson.load(data_file)

                    data_count_n = 1
                    reverse_list = list(view_db)
                    reverse_list.reverse()
                    for butt_ons in reverse_list:
                        if data_count_n > 15:
                            view_db.pop(butt_ons, None)
                        data_count_n += 1

                    with open(inline_db_path, "w") as data_file:
                        ujson.dump(view_db, data_file)

                    if str_y[0] == "btn":
                        inline_storage = list(view_db)
                    else:
                        rnd_id = (str_y[0].split("_", 1))[1]
                        inline_storage = [rnd_id]

                    if len(inline_storage) == 0:
                        return

                    for inline_content in inline_storage:
                        inline_db = view_db.get(inline_content)
                        if inline_db:
                            if (inline_db["media_valid"]
                                    and int(inline_db["media_id"]) != 0):
                                saved_msg = await userge.bot.get_messages(
                                    Config.LOG_CHANNEL_ID,
                                    int(inline_db["media_id"]))
                                media_data = get_file_id(saved_msg)

                            textx, buttonsx = pb(inline_db["msg_content"])

                            if inline_db["media_valid"]:
                                if saved_msg.photo:
                                    results.append(
                                        InlineQueryResultCachedPhoto(
                                            file_id=media_data,
                                            caption=textx,
                                            reply_markup=buttonsx,
                                        ))
                                else:
                                    results.append(
                                        InlineQueryResultCachedDocument(
                                            title=textx,
                                            file_id=media_data,
                                            caption=textx,
                                            description="Inline Button",
                                            reply_markup=buttonsx,
                                        ))
                            else:
                                results.append(
                                    InlineQueryResultArticle(
                                        title=textx,
                                        input_message_content=
                                        InputTextMessageContent(textx),
                                        reply_markup=buttonsx,
                                    ))

            if str_y[0].lower() == "stylish":
                if len(str_y) == 2:
                    results = []
                    input_text = str_y[1]
                    font_names = [
                        "serif",
                        "sans",
                        "sans_i",
                        "serif_i",
                        "medi_b",
                        "medi",
                        "double",
                        "cursive_b",
                        "cursive",
                        "bigsmall",
                        "reverse",
                        "circle",
                        "circle_b",
                        "mono",
                        "square_b",
                        "square",
                        "smoth",
                        "goth",
                        "wide",
                        "web",
                        "weeb",
                        "weeeb",
                    ]
                    for f_name in font_names:
                        styled_str = await font_gen(f_name, input_text)
                        results.append(
                            InlineQueryResultArticle(
                                title=f_name.upper(),
                                input_message_content=InputTextMessageContent(
                                    styled_str),
                                description=styled_str,
                            ))
                    await inline_query.answer(
                        results=results,
                        cache_time=1,
                        switch_pm_text="Available Commands",
                        switch_pm_parameter="inline",
                    )
                    return

            if str_x[0].lower() == "secret" and len(str_x) == 3:
                user_name = str_x[1]
                msg = str_x[2]
                try:
                    a = await userge.get_users(user_name)
                    user_id = a.id
                except BaseException:
                    return
                secret = os.path.join(PATH, "secret.txt")
                if os.path.exists(secret):
                    with open(secret) as outfile:
                        view_data = ujson.load(outfile)
                    # Uniquely identifies an inline message
                    new_id = {
                        str(inline_query.id): {
                            "user_id": user_id,
                            "msg": msg
                        }
                    }
                    view_data.update(new_id)
                else:
                    view_data = {
                        str(inline_query.id): {
                            "user_id": user_id,
                            "msg": msg
                        }
                    }
                # Save
                with open(secret, "w") as r:
                    ujson.dump(view_data, r)

                buttons = [[
                    InlineKeyboardButton(
                        "🔐  SHOW", callback_data=f"secret_{inline_query.id}")
                ]]
                results.append(
                    InlineQueryResultArticle(
                        title="Send A Secret Message",
                        input_message_content=InputTextMessageContent(
                            f"📩 <b>Secret Msg</b> for {user_name}. Only he/she can open it."
                        ),
                        description=f"Send Secret Message to: {user_name}",
                        thumb_url="https://i.imgur.com/c5pZebC.png",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    ))

            if str_y[0].lower() == "ytdl" and len(str_y) == 2:
                link = get_yt_video_id(str_y[1])
                found_ = True
                if link is None:
                    search = VideosSearch(str_y[1], limit=15)
                    resp = (search.result()).get("result")
                    if len(resp) == 0:
                        found_ = False
                    else:
                        outdata = await result_formatter(resp)
                        key_ = rand_key()
                        ytsearch_data.store_(key_, outdata)
                        buttons = InlineKeyboardMarkup([
                            [
                                InlineKeyboardButton(
                                    text=f"1 / {len(outdata)}",
                                    callback_data=f"ytdl_next_{key_}_1",
                                )
                            ],
                            [
                                InlineKeyboardButton(
                                    text="📜  List all",
                                    callback_data=f"ytdl_listall_{key_}_1",
                                ),
                                InlineKeyboardButton(
                                    text="⬇️  Download",
                                    callback_data=
                                    f'ytdl_download_{outdata[1]["video_id"]}_0',
                                ),
                            ],
                        ])
                        caption = outdata[1]["message"]
                        photo = outdata[1]["thumb"]
                else:
                    caption, buttons = await download_button(link, body=True)
                    photo = await get_ytthumb(link)

                if found_:
                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=photo,
                            title=link,
                            description="⬇️ Click to Download",
                            caption=caption,
                            reply_markup=buttons,
                        ))
                else:
                    results.append(
                        InlineQueryResultArticle(
                            title="not Found",
                            input_message_content=InputTextMessageContent(
                                f"No Results found for `{str_y[1]}`"),
                            description="INVALID",
                        ))

            MAIN_MENU = InlineQueryResultArticle(
                title="Main Menu",
                input_message_content=InputTextMessageContent(
                    " 𝐔𝐒𝐄𝐑𝐆𝐄-𝐗  𝗠𝗔𝗜𝗡 𝗠𝗘𝗡𝗨 "),
                url="https://github.com/code-rgb/USERGE-X",
                description="Userge-X Main Menu",
                thumb_url="https://i.imgur.com/1xsOo9o.png",
                reply_markup=InlineKeyboardMarkup(main_menu_buttons()),
            )
            results.append(MAIN_MENU)
            if len(results) != 0:
                await inline_query.answer(
                    results=results,
                    cache_time=1,
                    switch_pm_text="Available Commands",
                    switch_pm_parameter="inline",
                )
        else:
            results.append(REPO_X)
            owner_name = (await userge.get_me()).first_name
            await inline_query.answer(
                results=results,
                cache_time=1,
                switch_pm_text=f"This bot is only for {owner_name}",
                switch_pm_parameter="start",
            )
コード例 #27
0
async def inline_handler(event):  # sourcery no-metrics
    builder = event.builder
    result = None
    query = event.text
    string = query.lower()
    query.split(" ", 2)
    str_y = query.split(" ", 1)
    string.split()
    query_user_id = event.query.user_id
    if query_user_id == Config.OWNER_ID or query_user_id in Config.SUDO_USERS:
        hmm = re.compile("secret (.*) (.*)")
        match = re.findall(hmm, query)
        if query.startswith("**Catuserbot"):
            buttons = [(
                Button.inline("Stats", data="stats"),
                Button.url("Repo", "https://github.com/sandy1709/catuserbot"),
            )]
            ALIVE_PIC = gvarstatus("ALIVE_PIC")
            IALIVE_PIC = gvarstatus("IALIVE_PIC")
            if IALIVE_PIC:
                CAT = [x for x in IALIVE_PIC.split()]
                PIC = list(CAT)
                I_IMG = random.choice(PIC)
            if not IALIVE_PIC and ALIVE_PIC:
                CAT = [x for x in ALIVE_PIC.split()]
                PIC = list(CAT)
                I_IMG = random.choice(PIC)
            elif not IALIVE_PIC:
                I_IMG = None
            if I_IMG and I_IMG.endswith((".jpg", ".png")):
                result = builder.photo(
                    I_IMG,
                    text=query,
                    buttons=buttons,
                )
            elif I_IMG:
                result = builder.document(
                    I_IMG,
                    title="Alive cat",
                    text=query,
                    buttons=buttons,
                )
            else:
                result = builder.article(
                    title="Alive cat",
                    text=query,
                    buttons=buttons,
                )
            await event.answer([result] if result else None)
        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 = ibuild_keyboard(buttons)
            result = builder.article(
                title="Inline creator",
                text=message_text,
                buttons=tl_ib_buttons,
                link_preview=False,
            )
            await event.answer([result] if result else None)
        elif match:
            query = query[7:]
            user, txct = query.split(" ", 1)
            builder = event.builder
            secret = os.path.join("./userbot", "secrets.txt")
            try:
                jsondata = json.load(open(secret))
            except Exception:
                jsondata = False
            try:
                # if u is user id
                u = int(user)
                try:
                    u = await event.client.get_entity(u)
                    if u.username:
                        sandy = f"@{u.username}"
                    else:
                        sandy = f"[{u.first_name}](tg://user?id={u.id})"
                except ValueError:
                    # ValueError: Could not find the input entity
                    sandy = f"[user](tg://user?id={u})"
            except ValueError:
                # if u is username
                try:
                    u = await event.client.get_entity(user)
                except ValueError:
                    return
                if u.username:
                    sandy = f"@{u.username}"
                else:
                    sandy = f"[{u.first_name}](tg://user?id={u.id})"
                u = int(u.id)
            except Exception:
                return
            timestamp = int(time.time() * 2)
            newsecret = {str(timestamp): {"userid": u, "text": txct}}

            buttons = [
                Button.inline("show message 🔐", data=f"secret_{timestamp}")
            ]
            result = builder.article(
                title="secret message",
                text=
                f"🔒 A whisper message to {sandy}, Only he/she can open it.",
                buttons=buttons,
            )
            await event.answer([result] if result else None)
            if jsondata:
                jsondata.update(newsecret)
                json.dump(jsondata, open(secret, "w"))
            else:
                json.dump(newsecret, open(secret, "w"))
        elif string == "help":
            _result = main_menu()
            result = builder.article(
                title="© CatUserbot Help",
                description="Help menu for CatUserbot",
                text=_result[0],
                buttons=_result[1],
                link_preview=False,
            )
            await event.answer([result] if result else None)
        elif str_y[0].lower() == "ytdl" and len(str_y) == 2:
            link = get_yt_video_id(str_y[1].strip())
            found_ = True
            if link is None:
                search = VideosSearch(str_y[1].strip(), limit=15)
                resp = (search.result()).get("result")
                if len(resp) == 0:
                    found_ = False
                else:
                    outdata = await result_formatter(resp)
                    key_ = rand_key()
                    ytsearch_data.store_(key_, outdata)
                    buttons = [
                        Button.inline(
                            f"1 / {len(outdata)}",
                            data=f"ytdl_next_{key_}_1",
                        ),
                        Button.inline(
                            "📜  List all",
                            data=f"ytdl_listall_{key_}_1",
                        ),
                        Button.inline(
                            "⬇️  Download",
                            data=f'ytdl_download_{outdata[1]["video_id"]}_0',
                        ),
                    ]
                    caption = outdata[1]["message"]
                    photo = await get_ytthumb(outdata[1]["video_id"])
            else:
                caption, buttons = await download_button(link, body=True)
                photo = await get_ytthumb(link)
            if found_:
                markup = event.client.build_reply_markup(buttons)
                photo = types.InputWebDocument(url=photo,
                                               size=0,
                                               mime_type="image/jpeg",
                                               attributes=[])
                text, msg_entities = await event.client._parse_message_text(
                    caption, "html")
                result = types.InputBotInlineResult(
                    id=str(uuid4()),
                    type="photo",
                    title=link,
                    description="⬇️ Click to Download",
                    thumb=photo,
                    content=photo,
                    send_message=types.InputBotInlineMessageMediaAuto(
                        reply_markup=markup,
                        message=text,
                        entities=msg_entities),
                )
            else:
                result = builder.article(
                    title="Not Found",
                    text=f"No Results found for `{str_y[1]}`",
                    description="INVALID",
                )
            try:
                await event.answer([result] if result else None)
            except QueryIdInvalidError:
                await event.answer([
                    builder.article(
                        title="Not Found",
                        text=f"No Results found for `{str_y[1]}`",
                        description="INVALID",
                    )
                ])
        elif string == "age_verification_alert":
            buttons = [
                Button.inline(text="Yes I'm 18+",
                              data="age_verification_true"),
                Button.inline(text="No I'm Not",
                              data="age_verification_false"),
            ]
            markup = event.client.build_reply_markup(buttons)
            photo = types.InputWebDocument(
                url="https://i.imgur.com/Zg58iXc.jpg",
                size=0,
                mime_type="image/jpeg",
                attributes=[],
            )
            text, msg_entities = await event.client._parse_message_text(
                "<b>ARE YOU OLD ENOUGH FOR THIS ?</b>", "html")
            result = types.InputBotInlineResult(
                id=str(uuid4()),
                type="photo",
                title="Age verification",
                thumb=photo,
                content=photo,
                send_message=types.InputBotInlineMessageMediaAuto(
                    reply_markup=markup, message=text, entities=msg_entities),
            )
            await event.answer([result] if result else None)
        elif string == "pmpermit":
            buttons = [
                Button.inline(text="Show Options.",
                              data="show_pmpermit_options"),
            ]
            PM_PIC = gvarstatus("pmpermit_pic")
            if PM_PIC:
                CAT = [x for x in PM_PIC.split()]
                PIC = list(CAT)
                CAT_IMG = random.choice(PIC)
            else:
                CAT_IMG = None
            query = gvarstatus("pmpermit_text")
            if CAT_IMG and CAT_IMG.endswith((".jpg", ".jpeg", ".png")):
                result = builder.photo(
                    CAT_IMG,
                    # title="Alive cat",
                    text=query,
                    buttons=buttons,
                )
            elif CAT_IMG:
                result = builder.document(
                    CAT_IMG,
                    title="Alive cat",
                    text=query,
                    buttons=buttons,
                )
            else:
                result = builder.article(
                    title="Alive cat",
                    text=query,
                    buttons=buttons,
                )
            await event.answer([result] if result else None)
    else:
        buttons = [(
            Button.url("Source code",
                       "https://github.com/sandy1709/catuserbot"),
            Button.url(
                "Deploy",
                "https://dashboard.heroku.com/new?button-url=https%3A%2F%2Fgithub.com%2FMr-confused%2Fcatpack&template=https%3A%2F%2Fgithub.com%2FMr-confused%2Fcatpack",
            ),
        )]
        markup = event.client.build_reply_markup(buttons)
        photo = types.InputWebDocument(url=CATLOGO,
                                       size=0,
                                       mime_type="image/jpeg",
                                       attributes=[])
        text, msg_entities = await event.client._parse_message_text(
            "𝗗𝗲𝗽𝗹𝗼𝘆 𝘆𝗼𝘂𝗿 𝗼𝘄𝗻 𝗖𝗮𝘁𝗨𝘀𝗲𝗿𝗯𝗼𝘁.", "md")
        result = types.InputBotInlineResult(
            id=str(uuid4()),
            type="photo",
            title="𝘾𝙖𝙩𝙐𝙨𝙚𝙧𝙗𝙤𝙩",
            description="Deploy yourself",
            url="https://github.com/sandy1709/catuserbot",
            thumb=photo,
            content=photo,
            send_message=types.InputBotInlineMessageMediaAuto(
                reply_markup=markup, message=text, entities=msg_entities),
        )
        await event.answer([result] if result else None)
コード例 #28
0
ファイル: inlinebot.py プロジェクト: AlphaTp/DaisyX
async def inline_query_handler(client, query):
    try:
        text = query.query.lower()
        answers = []
        if text.strip() == "":
            answerss = await inline_help_func(__HELP__)
            await client.answer_inline_query(query.id, results=answerss, cache_time=10)
            return
        elif text.split()[0] == "alive":
            answerss = await alive_function(answers)
            await client.answer_inline_query(query.id, results=answerss, cache_time=10)
        elif text.split()[0] == "tr":
            lang = text.split()[1]
            tex = text.split(None, 2)[2]
            answerss = await translate_func(answers, lang, tex)
            await client.answer_inline_query(query.id, results=answerss, cache_time=10)
        elif text.split()[0] == "ud":
            tex = text.split(None, 1)[1]
            answerss = await urban_func(answers, tex)
            await client.answer_inline_query(query.id, results=answerss, cache_time=10)
        elif text.split()[0] == "google":
            tex = text.split(None, 1)[1]
            answerss = await google_search_func(answers, tex)
            await client.answer_inline_query(query.id, results=answerss, cache_time=10)
        elif text.split()[0] == "webss":
            tex = text.split(None, 1)[1]
            answerss = await webss(tex)
            await client.answer_inline_query(query.id, results=answerss, cache_time=2)
        elif text.split()[0] == "bitly":
            tex = text.split(None, 1)[1]
            answerss = await shortify(tex)
            await client.answer_inline_query(query.id, results=answerss, cache_time=2)
        elif text.split()[0] == "wiki":
            if len(text.split()) < 2:
                await client.answer_inline_query(
                    query.id,
                    results=answers,
                    switch_pm_text="Wikipedia | wiki [QUERY]",
                    switch_pm_parameter="inline",
                )
                return
            tex = text.split(None, 1)[1].strip()
            answerss = await wiki_func(answers, tex)
            await client.answer_inline_query(query.id, results=answerss, cache_time=2)

        elif text.split()[0] == "ping":
            answerss = await ping_func(answers)
            await client.answer_inline_query(query.id, results=answerss, cache_time=2)
            return

        elif text.split()[0] == "yt":
            answers = []
            search_query = text.split(None, 1)[1]
            search_query = query.query.lower().strip().rstrip()

            if search_query == "":
                await client.answer_inline_query(
                    query.id,
                    results=answers,
                    switch_pm_text="Type a YouTube video name...",
                    switch_pm_parameter="help",
                    cache_time=0,
                )
            else:
                search = VideosSearch(search_query, limit=50)

                for result in search.result()["result"]:
                    answers.append(
                        InlineQueryResultArticle(
                            title=result["title"],
                            description="{}, {} views.".format(
                                result["duration"], result["viewCount"]["short"]
                            ),
                            input_message_content=InputTextMessageContent(
                                "https://www.youtube.com/watch?v={}".format(
                                    result["id"]
                                )
                            ),
                            thumb_url=result["thumbnails"][0]["url"],
                        )
                    )

                try:
                    await query.answer(results=answers, cache_time=0)
                except errors.QueryIdInvalid:
                    await query.answer(
                        results=answers,
                        cache_time=0,
                        switch_pm_text="Error: Search timed out",
                        switch_pm_parameter="",
                    )

        elif text.split()[0] == "wall":
            tex = text.split(None, 1)[1]
            answerss = await wall_func(answers, tex)
            await client.answer_inline_query(query.id, results=answerss)

        elif text.split()[0] == "pic":
            tex = text.split(None, 1)[1]
            answerss = await wall_func(answers, tex)
            await client.answer_inline_query(query.id, results=answerss)

        elif text.split()[0] == "saavn":
            tex = text.split(None, 1)[1]
            answerss = await saavn_func(answers, tex)
            await client.answer_inline_query(query.id, results=answerss)

        elif text.split()[0] == "deezer":
            tex = text.split(None, 1)[1]
            answerss = await deezer_func(answers, tex)
            await client.answer_inline_query(query.id, results=answerss)

        elif text.split()[0] == "torrent":
            tex = text.split(None, 1)[1]
            answerss = await torrent_func(answers, tex)
            await client.answer_inline_query(query.id, results=answerss, cache_time=10)
        elif text.split()[0] == "modapk":
            sgname = text.split(None, 1)[1]
            PabloEscobar = (
                f"https://an1.com/tags/MOD/?story={sgname}&do=search&subaction=search"
            )
            r = requests.get(PabloEscobar)
            results = []
            soup = BeautifulSoup(r.content, "html5lib")
            mydivs = soup.find_all("div", {"class": "search-results"})
            Pop = soup.find_all("div", {"class": "title"})
            cnte = len(mydivs)
            for cnt in range(cnte):
                sucker = mydivs[cnt]
                pH9 = sucker.find("a").contents[0]
                file_name = pH9
                pH = sucker.findAll("img")
                imme = pH[0]["src"]
                Pablo = Pop[0].a["href"]
                ro = requests.get(Pablo)
                soupe = BeautifulSoup(ro.content, "html5lib")
                myopo = soupe.find_all("div", {"class": "item"})
                capt = f"**{file_name}** \n** {myopo[0].text}**\n**{myopo[1].text}**\n**{myopo[2].text}**\n**{myopo[3].text}**"
                mydis0 = soupe.find_all("a", {"class": "get-product"})
                Lol9 = mydis0[0]
                lemk = "https://an1.com" + Lol9["href"]
                rr = requests.get(lemk)
                soup = BeautifulSoup(rr.content, "html5lib")
                script = soup.find("script", type="text/javascript")
                leek = re.search(r'href=[\'"]?([^\'" >]+)', script.text).group()
                dl_link = leek[5:]

                results.append(
                    InlineQueryResultPhoto(
                        photo_url=imme,
                        title=file_name,
                        caption=capt,
                        reply_markup=InlineKeyboardMarkup(
                            [
                                [InlineKeyboardButton("Download Link", url=lemk)],
                                [
                                    InlineKeyboardButton(
                                        "Direct Download Link", url=dl_link
                                    )
                                ],
                            ]
                        ),
                    )
                )

            await client.answer_inline_query(query.id, cache_time=0, results=results)
        elif text.split()[0] == "reddit":
            subreddit = text.split(None, 1)[1]
            results = []
            reddit = await arq.reddit(subreddit)
            sreddit = reddit.subreddit
            title = reddit.title
            image = reddit.url
            link = reddit.postLink
            caption = f"""**Title:** `{title}`
            Subreddit: `{sreddit}`"""
            results.append(
                InlineQueryResultPhoto(
                    photo_url=image,
                    title="Meme Search",
                    caption=caption,
                    reply_markup=InlineKeyboardMarkup(
                        [
                            [InlineKeyboardButton("PostLink", url=link)],
                        ]
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)

        elif text.split()[0] == "imdb":
            movie_name = text.split(None, 1)[1]
            results = []
            remove_space = movie_name.split(" ")
            final_name = "+".join(remove_space)
            page = requests.get(
                "https://www.imdb.com/find?ref_=nv_sr_fn&q=" + final_name + "&s=all"
            )
            str(page.status_code)
            soup = BeautifulSoup(page.content, "lxml")
            odds = soup.findAll("tr", "odd")
            mov_title = odds[0].findNext("td").findNext("td").text
            mov_link = (
                "http://www.imdb.com/" + odds[0].findNext("td").findNext("td").a["href"]
            )
            page1 = requests.get(mov_link)
            soup = BeautifulSoup(page1.content, "lxml")
            if soup.find("div", "poster"):
                poster = soup.find("div", "poster").img["src"]
            else:
                poster = ""
            if soup.find("div", "title_wrapper"):
                pg = soup.find("div", "title_wrapper").findNext("div").text
                mov_details = re.sub(r"\s+", " ", pg)
            else:
                mov_details = ""
            credits = soup.findAll("div", "credit_summary_item")
            if len(credits) == 1:
                director = credits[0].a.text
                writer = "Not available"
                stars = "Not available"
            elif len(credits) > 2:
                director = credits[0].a.text
                writer = credits[1].a.text
                actors = []
                for x in credits[2].findAll("a"):
                    actors.append(x.text)
                actors.pop()
                stars = actors[0] + "," + actors[1] + "," + actors[2]
            else:
                director = credits[0].a.text
                writer = "Not available"
                actors = []
                for x in credits[1].findAll("a"):
                    actors.append(x.text)
                actors.pop()
                stars = actors[0] + "," + actors[1] + "," + actors[2]
            if soup.find("div", "inline canwrap"):
                story_line = soup.find("div", "inline canwrap").findAll("p")[0].text
            else:
                story_line = "Not available"
            info = soup.findAll("div", "txt-block")
            if info:
                mov_country = []
                mov_language = []
                for node in info:
                    a = node.findAll("a")
                    for i in a:
                        if "country_of_origin" in i["href"]:
                            mov_country.append(i.text)
                        elif "primary_language" in i["href"]:
                            mov_language.append(i.text)
            if soup.findAll("div", "ratingValue"):
                for r in soup.findAll("div", "ratingValue"):
                    mov_rating = r.strong["title"]
            else:
                mov_rating = "Not available"
            lol = f"Movie - {mov_title}\n Click to see more"
            msg = (
                "<a href=" + poster + ">&#8203;</a>"
                "<b>Title : </b><code>"
                + mov_title
                + "</code>\n<code>"
                + mov_details
                + "</code>\n<b>Rating : </b><code>"
                + mov_rating
                + "</code>\n<b>Country : </b><code>"
                + mov_country[0]
                + "</code>\n<b>Language : </b><code>"
                + mov_language[0]
                + "</code>\n<b>Director : </b><code>"
                + director
                + "</code>\n<b>Writer : </b><code>"
                + writer
                + "</code>\n<b>Stars : </b><code>"
                + stars
                + "</code>\n<b>IMDB Url : </b>"
                + mov_link
                + "\n<b>Story Line : </b>"
                + story_line
            )
            results.append(
                InlineQueryResultArticle(
                    title="Imdb Search",
                    description=lol,
                    input_message_content=InputTextMessageContent(
                        msg, disable_web_page_preview=False, parse_mode="HTML"
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)
        elif text.split()[0] == "spaminfo":
            cmd = text.split(None, 1)[1]
            results = []
            url = f"https://api.intellivoid.net/spamprotection/v1/lookup?query={cmd}"
            a = await AioHttp().get_json(url)
            response = a["success"]
            if response is True:
                date = a["results"]["last_updated"]
                stats = f"**◢ Intellivoid• SpamProtection Info**:\n"
                stats += f' • **Updated on**: `{datetime.fromtimestamp(date).strftime("%Y-%m-%d %I:%M:%S %p")}`\n'
                stats += f" • **Chat Info**: [Link](t.me/SpamProtectionBot/?start=00_{cmd})\n"

                if a["results"]["attributes"]["is_potential_spammer"] is True:
                    stats += f" • **User**: `USERxSPAM`\n"
                elif a["results"]["attributes"]["is_operator"] is True:
                    stats += f" • **User**: `USERxOPERATOR`\n"
                elif a["results"]["attributes"]["is_agent"] is True:
                    stats += f" • **User**: `USERxAGENT`\n"
                elif a["results"]["attributes"]["is_whitelisted"] is True:
                    stats += f" • **User**: `USERxWHITELISTED`\n"

                stats += f' • **Type**: `{a["results"]["entity_type"]}`\n'
                stats += f' • **Language**: `{a["results"]["language_prediction"]["language"]}`\n'
                stats += f' • **Language Probability**: `{a["results"]["language_prediction"]["probability"]}`\n'
                stats += f"**Spam Prediction**:\n"
                stats += f' • **Ham Prediction**: `{a["results"]["spam_prediction"]["ham_prediction"]}`\n'
                stats += f' • **Spam Prediction**: `{a["results"]["spam_prediction"]["spam_prediction"]}`\n'
                stats += f'**Blacklisted**: `{a["results"]["attributes"]["is_blacklisted"]}`\n'
                if a["results"]["attributes"]["is_blacklisted"] is True:
                    stats += f' • **Reason**: `{a["results"]["attributes"]["blacklist_reason"]}`\n'
                    stats += f' • **Flag**: `{a["results"]["attributes"]["blacklist_flag"]}`\n'
                stats += f'**PTID**:\n`{a["results"]["private_telegram_id"]}`\n'
                results.append(
                    InlineQueryResultArticle(
                        title="Spam Info",
                        description="Search Users spam info",
                        input_message_content=InputTextMessageContent(
                            stats, disable_web_page_preview=True
                        ),
                    )
                )
                await client.answer_inline_query(
                    query.id, cache_time=0, results=results
                )
        elif text.split()[0] == "lyrics":
            cmd = text.split(None, 1)[1]
            results = []

            song = ""
            song = Song.find_song(cmd)
            if song:
                if song.lyrics:
                    reply = song.format()
                else:
                    reply = "Couldn't find any lyrics for that song! try with artist name along with song if still doesnt work try `.glyrics`"
            else:
                reply = "lyrics not found! try with artist name along with song if still doesnt work try `.glyrics`"

            if len(reply) > 4095:
                reply = "lyrics too big, Try using /lyrics"

            results.append(
                InlineQueryResultArticle(
                    title="Song Lyrics",
                    description="Click here to see lyrics",
                    input_message_content=InputTextMessageContent(
                        reply, disable_web_page_preview=False
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)
        elif text.split()[0] == "pokedex":
            if len(text.split()) < 2:
                await client.answer_inline_query(
                    query.id,
                    results=answers,
                    switch_pm_text="Pokemon [text]",
                    switch_pm_parameter="pokedex",
                )
                return
            pokedex = text.split(None, 1)[1].strip()
            Pokedex = await pokedexinfo(answers, pokedex)
            await client.answer_inline_query(query.id, results=Pokedex, cache_time=2)
        elif text.split()[0] == "paste":
            tex = text.split(None, 1)[1]
            answerss = await paste_func(answers, tex)
            await client.answer_inline_query(query.id, results=answerss, cache_time=2)

        elif text.split()[0] == "covid":
            lel = text.split(None, 1)[1]
            results = []
            country = lel.replace(" ", "")
            data = await fetch(f"https://corona.lmao.ninja/v2/countries/{country}")
            data = await json_prettify(data)
            results.append(
                InlineQueryResultArticle(
                    title="Covid Info Gathered succesfully",
                    description=data,
                    input_message_content=InputTextMessageContent(
                        data, disable_web_page_preview=False
                    ),
                )
            )
            await client.answer_inline_query(query.id, results=results, cache_time=2)
        elif text.split()[0] == "country":
            lel = text.split(None, 1)[1]
            results = []
            country = CountryInfo(lel)
            try:
                a = country.info()
            except:
                a = "Country Not Avaiable Currently"
            name = a.get("name")
            bb = a.get("altSpellings")
            hu = ""
            for p in bb:
                hu += p + ",  "

            area = a.get("area")
            borders = ""
            hell = a.get("borders")
            for fk in hell:
                borders += fk + ",  "

            call = ""
            WhAt = a.get("callingCodes")
            for what in WhAt:
                call += what + "  "

            capital = a.get("capital")
            currencies = ""
            fker = a.get("currencies")
            for FKer in fker:
                currencies += FKer + ",  "

            HmM = a.get("demonym")
            geo = a.get("geoJSON")
            pablo = geo.get("features")
            Pablo = pablo[0]
            PAblo = Pablo.get("geometry")
            EsCoBaR = PAblo.get("type")
            iso = ""
            iSo = a.get("ISO")
            for hitler in iSo:
                po = iSo.get(hitler)
                iso += po + ",  "
            fla = iSo.get("alpha2")
            fla.upper()

            languages = a.get("languages")
            lMAO = ""
            for lmao in languages:
                lMAO += lmao + ",  "

            nonive = a.get("nativeName")
            waste = a.get("population")
            reg = a.get("region")
            sub = a.get("subregion")
            tik = a.get("timezones")
            tom = ""
            for jerry in tik:
                tom += jerry + ",   "

            GOT = a.get("tld")
            lanester = ""
            for targaryen in GOT:
                lanester += targaryen + ",   "

            wiki = a.get("wiki")

            caption = f"""<b><u>Information Gathered Successfully</b></u>
        <b>
        Country Name:- {name}
        Alternative Spellings:- {hu}
        Country Area:- {area} square kilometers
        Borders:- {borders}
        Calling Codes:- {call}
        Country's Capital:- {capital}
        Country's currency:- {currencies}
        Demonym:- {HmM}
        Country Type:- {EsCoBaR}
        ISO Names:- {iso}
        Languages:- {lMAO}
        Native Name:- {nonive}
        population:- {waste}
        Region:- {reg}
        Sub Region:- {sub}
        Time Zones:- {tom}
        Top Level Domain:- {lanester}
        wikipedia:- {wiki}</b>
        Gathered By Daisy X.</b>
        """
            results.append(
                InlineQueryResultArticle(
                    title=f"Infomation of {name}",
                    description=f"""
        Country Name:- {name}
        Alternative Spellings:- {hu}
        Country Area:- {area} square kilometers
        Borders:- {borders}
        Calling Codes:- {call}
        Country's Capital:- {capital}
        
        Touch for more info
        """,
                    input_message_content=InputTextMessageContent(
                        caption, parse_mode="HTML", disable_web_page_preview=True
                    ),
                )
            )
            await client.answer_inline_query(query.id, results=results, cache_time=2)

        elif text.split()[0] == "fakegen":
            results = []
            fake = Faker()
            name = str(fake.name())
            fake.add_provider(internet)
            address = str(fake.address())
            ip = fake.ipv4_private()
            cc = fake.credit_card_full()
            email = fake.ascii_free_email()
            job = fake.job()
            android = fake.android_platform_token()
            pc = fake.chrome()
            res = f"<b><u> Fake Information Generated</b></u>\n<b>Name :-</b><code>{name}</code>\n\n<b>Address:-</b><code>{address}</code>\n\n<b>IP ADDRESS:-</b><code>{ip}</code>\n\n<b>credit card:-</b><code>{cc}</code>\n\n<b>Email Id:-</b><code>{email}</code>\n\n<b>Job:-</b><code>{job}</code>\n\n<b>android user agent:-</b><code>{android}</code>\n\n<b>Pc user agent:-</b><code>{pc}</code>"
            results.append(
                InlineQueryResultArticle(
                    title="Fake infomation gathered",
                    description="Click here to see them",
                    input_message_content=InputTextMessageContent(
                        res, parse_mode="HTML", disable_web_page_preview=True
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)

        elif text.split()[0] == "cs":
            results = []
            score_page = "http://static.cricinfo.com/rss/livescores.xml"
            page = urllib.request.urlopen(score_page)
            soup = BeautifulSoup(page, "html.parser")
            result = soup.find_all("description")
            Sed = ""
            for match in result:
                Sed += match.get_text() + "\n\n"
            res = f"<b><u>Match information gathered successful</b></u>\n\n\n<code>{Sed}</code>"
            results.append(
                InlineQueryResultArticle(
                    title="Match information gathered",
                    description="Click here to see them",
                    input_message_content=InputTextMessageContent(
                        res, parse_mode="HTML", disable_web_page_preview=False
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)

        elif text.split()[0] == "antonyms":
            results = []
            lel = text.split(None, 1)[1]
            word = f"{lel}"
            let = dictionary.antonym(word)
            set = str(let)
            jet = set.replace("{", "")
            net = jet.replace("}", "")
            got = net.replace("'", "")
            results.append(
                InlineQueryResultArticle(
                    title=f"antonyms for {lel}",
                    description=got,
                    input_message_content=InputTextMessageContent(
                        got, disable_web_page_preview=False
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)

        elif text.split()[0] == "synonyms":
            results = []
            lel = text.split(None, 1)[1]
            word = f"{lel}"
            let = dictionary.synonym(word)
            set = str(let)
            jet = set.replace("{", "")
            net = jet.replace("}", "")
            got = net.replace("'", "")
            results.append(
                InlineQueryResultArticle(
                    title=f"antonyms for {lel}",
                    description=got,
                    input_message_content=InputTextMessageContent(
                        got, disable_web_page_preview=False
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)

        elif text.split()[0] == "define":
            results = []
            lel = text.split(None, 1)[1]
            word = f"{lel}"
            let = dictionary.meaning(word)
            set = str(let)
            jet = set.replace("{", "")
            net = jet.replace("}", "")
            got = net.replace("'", "")
            results.append(
                InlineQueryResultArticle(
                    title=f"Definition for {lel}",
                    description=got,
                    input_message_content=InputTextMessageContent(
                        got, disable_web_page_preview=False
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)

        elif text.split()[0] == "weather":
            results = []
            sample_url = "https://api.openweathermap.org/data/2.5/weather?q={}&APPID={}&units=metric"
            input_str = text.split(None, 1)[1]
            async with aiohttp.ClientSession() as session:
                response_api_zero = await session.get(
                    sample_url.format(input_str, OPENWEATHERMAP_ID)
                )
            response_api = await response_api_zero.json()
            if response_api["cod"] == 200:
                country_code = response_api["sys"]["country"]
                country_time_zone = int(response_api["timezone"])
                sun_rise_time = int(response_api["sys"]["sunrise"]) + country_time_zone
                sun_set_time = int(response_api["sys"]["sunset"]) + country_time_zone
                lol = """ 
        WEATHER INFO GATHERED
        Location: {}
        Temperature ☀️: {}°С
            minimium: {}°С
            maximum : {}°С
        Humidity 🌤**: {}%
        Wind 💨: {}m/s
        Clouds ☁️: {}hpa
        Sunrise 🌤: {} {}
        Sunset 🌝: {} {}""".format(
                    input_str,
                    response_api["main"]["temp"],
                    response_api["main"]["temp_min"],
                    response_api["main"]["temp_max"],
                    response_api["main"]["humidity"],
                    response_api["wind"]["speed"],
                    response_api["clouds"]["all"],
                    # response_api["main"]["pressure"],
                    time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(sun_rise_time)),
                    country_code,
                    time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(sun_set_time)),
                    country_code,
                )
                results.append(
                    InlineQueryResultArticle(
                        title=f"Weather Information",
                        description=lol,
                        input_message_content=InputTextMessageContent(
                            lol, disable_web_page_preview=True
                        ),
                    )
                )
                await client.answer_inline_query(
                    query.id, cache_time=0, results=results
                )

        elif text.split()[0] == "datetime":
            results = []
            gay = text.split(None, 1)[1]
            lel = gay
            query_timezone = lel.lower()
            if len(query_timezone) == 2:
                result = generate_time(query_timezone, ["countryCode"])
            else:
                result = generate_time(query_timezone, ["zoneName", "countryName"])

            if not result:
                result = f"Timezone info not available for <b>{lel}</b>"

            results.append(
                InlineQueryResultArticle(
                    title=f"Date & Time info of {lel}",
                    description=result,
                    input_message_content=InputTextMessageContent(
                        result, disable_web_page_preview=False, parse_mode="html"
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)

        elif text.split()[0] == "app":
            rip = []
            app_name = text.split(None, 1)[1]
            remove_space = app_name.split(" ")
            final_name = "+".join(remove_space)
            page = requests.get(
                "https://play.google.com/store/search?q=" + final_name + "&c=apps"
            )
            str(page.status_code)
            soup = BeautifulSoup(page.content, "lxml", from_encoding="utf-8")
            results = soup.findAll("div", "ZmHEEd")
            app_name = (
                results[0]
                .findNext("div", "Vpfmgd")
                .findNext("div", "WsMG1c nnK0zc")
                .text
            )
            app_dev = (
                results[0].findNext("div", "Vpfmgd").findNext("div", "KoLSrc").text
            )
            app_dev_link = (
                "https://play.google.com"
                + results[0].findNext("div", "Vpfmgd").findNext("a", "mnKHRc")["href"]
            )
            app_rating = (
                results[0]
                .findNext("div", "Vpfmgd")
                .findNext("div", "pf5lIe")
                .find("div")["aria-label"]
            )
            app_link = (
                "https://play.google.com"
                + results[0]
                .findNext("div", "Vpfmgd")
                .findNext("div", "vU6FJ p63iDd")
                .a["href"]
            )
            app_icon = (
                results[0]
                .findNext("div", "Vpfmgd")
                .findNext("div", "uzcko")
                .img["data-src"]
            )
            app_details = "<a href='" + app_icon + "'>📲&#8203;</a>"
            app_details += " <b>" + app_name + "</b>"
            app_details += (
                "\n\n<code>Developer :</code> <a href='"
                + app_dev_link
                + "'>"
                + app_dev
                + "</a>"
            )
            app_details += "\n<code>Rating :</code> " + app_rating.replace(
                "Rated ", "⭐ "
            ).replace(" out of ", "/").replace(" stars", "", 1).replace(
                " stars", "⭐ "
            ).replace(
                "five", "5"
            )
            app_details += (
                "\n<code>Features :</code> <a href='"
                + app_link
                + "'>View in Play Store</a>"
            )
            app_details += "\n\n===> @DaisySupport_Official <==="
            rip.append(
                InlineQueryResultArticle(
                    title=f"Datails of {app_name}",
                    description=app_details,
                    input_message_content=InputTextMessageContent(
                        app_details, disable_web_page_preview=True, parse_mode="html"
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=rip)

        elif text.split()[0] == "gh":
            results = []
            gett = text.split(None, 1)[1]
            text = gett + ' "site:github.com"'
            gresults = await GoogleSearch().async_search(text, 1)
            result = ""
            for i in range(4):
                try:
                    title = gresults["titles"][i].replace("\n", " ")
                    source = gresults["links"][i]
                    description = gresults["descriptions"][i]
                    result += f"[{title}]({source})\n"
                    result += f"`{description}`\n\n"
                except IndexError:
                    pass
            results.append(
                InlineQueryResultArticle(
                    title=f"Results for {gett}",
                    description=f" Github info of {title}\n  Touch to read",
                    input_message_content=InputTextMessageContent(
                        result, disable_web_page_preview=True
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)

        elif text.split()[0] == "so":
            results = []
            gett = text.split(None, 1)[1]
            text = gett + ' "site:stackoverflow.com"'
            gresults = await GoogleSearch().async_search(text, 1)
            result = ""
            for i in range(4):
                try:
                    title = gresults["titles"][i].replace("\n", " ")
                    source = gresults["links"][i]
                    description = gresults["descriptions"][i]
                    result += f"[{title}]({source})\n"
                    result += f"`{description}`\n\n"
                except IndexError:
                    pass
            results.append(
                InlineQueryResultArticle(
                    title=f"Stack overflow saerch - {title}",
                    description=f" Touch to view search results on {title}",
                    input_message_content=InputTextMessageContent(
                        result, disable_web_page_preview=True
                    ),
                )
            )
            await client.answer_inline_query(query.id, cache_time=0, results=results)

    except (IndexError, TypeError, KeyError, ValueError):
        return
コード例 #29
0
    async def inline_answer(_, inline_query: InlineQuery):
        results = []
        i_q = inline_query.query
        string = i_q.lower()  # All lower
        str_x = i_q.split(" ", 2)  # trigger @username Text
        str_y = i_q.split(" ", 1)  # trigger and Text
        string_split = string.split()  # All lower and Split each word
        iq_user_id = inline_query.from_user.id
        if (
            (iq_user_id in Config.OWNER_ID)
            or (iq_user_id in Config.SUDO_USERS)
            and Config.SUDO_ENABLED
        ):

            if string == "syntax":
                owner = [
                    [
                        InlineKeyboardButton(
                            text="Contact", url="https://t.me/deleteduser420"
                        )
                    ]
                ]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url="https://coverfiles.alphacoders.com/123/123388.png",
                        caption="Hey I solved **𝚂𝚢𝚗𝚝𝚊𝚡's ░ Σrr♢r**",
                        reply_markup=InlineKeyboardMarkup(owner),
                    )
                )

            if string == "age_verification_alert":
                buttons = [
                    [
                        InlineKeyboardButton(
                            text="Yes I'm 18+", callback_data="age_verification_true"
                        ),
                        InlineKeyboardButton(
                            text="No I'm Not", callback_data="age_verification_false"
                        ),
                    ]
                ]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url="https://i.imgur.com/Zg58iXc.jpg",
                        caption="**ARE YOU OLD ENOUGH FOR THIS ?**",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    )
                )

            if str_y[0] == "reddit":
                reddit_api = "https://meme-api.herokuapp.com/gimme/"
                if len(str_y) == 2:
                    subreddit_regex = r"^([a-zA-Z]+)\.$"
                    match = re.search(subreddit_regex, str_y[1])
                    if match:
                        subreddit_name = match.group(1)
                        reddit_api += f"{subreddit_name}/30"
                    else:
                        return
                else:
                    reddit_api += "30"
                try:
                    r = await get_response.json(reddit_api)
                except ValueError:
                    results.append(
                        InlineQueryResultArticle(
                            title="Reddit Api is Down !",
                            input_message_content=InputTextMessageContent(
                                "**Error Code: Status != 200**"
                            ),
                            thumb_url="https://i.imgur.com/7a7aPVa.png",
                        )
                    )
                else:
                    if "code" in r:
                        bool_is_gallery = False
                        code = r["code"]
                        code_message = r["message"]
                        results.append(
                            InlineQueryResultArticle(
                                title=str(code),
                                input_message_content=InputTextMessageContent(
                                    f"**Error Code: {code}**\n`{code_message}`"
                                ),
                                description="Enter A Valid Subreddit Name !",
                                thumb_url="https://i.imgur.com/7a7aPVa.png",
                            )
                        )
                    else:
                        bool_is_gallery = True
                        for post in r["memes"]:
                            if "url" in post:
                                postlink = post["postLink"]
                                subreddit = post["subreddit"]
                                title = post["title"]
                                media_url = post["url"]
                                author = post["author"]
                                upvote = post["ups"]
                                captionx = f"<b>{title}</b>\n"
                                captionx += f"`Posted by u/{author}`\n"
                                captionx += f"↕️ <code>{upvote}</code>\n"
                                thumbnail = reddit_thumb_link(post["preview"])
                                if post["spoiler"]:
                                    captionx += "⚠️ Post marked as SPOILER\n"
                                if post["nsfw"]:
                                    captionx += "🔞 Post marked Adult \n"
                                buttons = [
                                    [
                                        InlineKeyboardButton(
                                            f"Source: r/{subreddit}", url=postlink
                                        )
                                    ]
                                ]
                                if media_url.endswith(".gif"):
                                    results.append(
                                        InlineQueryResultAnimation(
                                            animation_url=media_url,
                                            thumb_url=thumbnail,
                                            caption=captionx,
                                            reply_markup=InlineKeyboardMarkup(buttons),
                                        )
                                    )
                                else:
                                    results.append(
                                        InlineQueryResultPhoto(
                                            photo_url=media_url,
                                            thumb_url=thumbnail,
                                            caption=captionx,
                                            reply_markup=InlineKeyboardMarkup(buttons),
                                        )
                                    )
                    await inline_query.answer(
                        results=results,
                        cache_time=1,
                        is_gallery=bool_is_gallery,
                        switch_pm_text="Available Commands",
                        switch_pm_parameter="inline",
                    )
                    return

            if string == "alive":
                me = await userge.get_me()
                alive_info = Bot_Alive.alive_info(me)
                buttons = Bot_Alive.alive_buttons()
                if not Config.ALIVE_MEDIA:
                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=Bot_Alive.alive_default_imgs(),
                            caption=alive_info,
                            reply_markup=buttons,
                        )
                    )
                else:
                    if Config.ALIVE_MEDIA.lower().strip() == "false":
                        results.append(
                            InlineQueryResultArticle(
                                title="USERGE-X",
                                input_message_content=InputTextMessageContent(
                                    alive_info, disable_web_page_preview=True
                                ),
                                description="ALIVE",
                                reply_markup=buttons,
                            )
                        )
                    else:
                        _media_type, _media_url = await Bot_Alive.check_media_link(
                            Config.ALIVE_MEDIA
                        )
                        if _media_type == "url_gif":
                            results.append(
                                InlineQueryResultAnimation(
                                    animation_url=_media_url,
                                    caption=alive_info,
                                    reply_markup=buttons,
                                )
                            )
                        elif _media_type == "url_image":
                            results.append(
                                InlineQueryResultPhoto(
                                    photo_url=_media_url,
                                    caption=alive_info,
                                    reply_markup=buttons,
                                )
                            )
                        elif _media_type == "tg_media":
                            c_file_id = Bot_Alive.get_bot_cached_fid()
                            if c_file_id is None:
                                try:
                                    c_file_id = get_file_id(
                                        await userge.bot.get_messages(
                                            _media_url[0], _media_url[1]
                                        )
                                    )
                                except Exception as b_rr:
                                    await CHANNEL.log(str(b_rr))
                            if Bot_Alive.is_photo(c_file_id):
                                results.append(
                                    InlineQueryResultCachedPhoto(
                                        file_id=c_file_id,
                                        caption=alive_info,
                                        reply_markup=buttons,
                                    )
                                )
                            else:
                                results.append(
                                    InlineQueryResultCachedDocument(
                                        title="USERGE-X",
                                        file_id=c_file_id,
                                        caption=alive_info,
                                        description="ALIVE",
                                        reply_markup=buttons,
                                    )
                                )

            if string == "geass":
                results.append(
                    InlineQueryResultAnimation(
                        animation_url="https://i.imgur.com/DeZHcRK.gif",
                        caption="To defeat evil, I must become a greater evil",
                    )
                )

            if str_y[0] == "inotes" and len(str_y) == 2:
                note_data = str_y[1].split("_", 2)
                note_data = [int(x) for x in note_data]
                if len(note_data) == 3:
                    cnote = await get_inote(
                        note_id=note_data[0], chat_id=note_data[1], user_id=note_data[2]
                    )
                    type_ = cnote.get("type")
                    if type_ == "image":
                        results.append(
                            InlineQueryResultCachedPhoto(
                                file_id=cnote.get("file_id"),
                                caption=cnote.get("caption"),
                                reply_markup=cnote.get("buttons"),
                            )
                        )
                    elif type_ == "media":
                        results.append(
                            InlineQueryResultCachedDocument(
                                title="Inline Note",
                                file_id=cnote.get("file_id"),
                                caption=cnote.get("caption"),
                                description=f"#{note_data[0]}",
                                reply_markup=cnote.get("buttons"),
                            )
                        )
                    else:
                        results.append(
                            InlineQueryResultArticle(
                                title="Inline Note",
                                input_message_content=InputTextMessageContent(
                                    cnote.get("caption"), disable_web_page_preview=True
                                ),
                                description=f"#{note_data[0]}",
                                reply_markup=cnote.get("buttons"),
                            )
                        )

            if string == "gapps":
                buttons = [
                    [
                        InlineKeyboardButton("Open GApps", callback_data="open_gapps"),
                        InlineKeyboardButton(
                            "Flame GApps", callback_data="flame_gapps"
                        ),
                    ],
                    [InlineKeyboardButton("Nik GApps", callback_data="nik_gapps")],
                ]
                results.append(
                    InlineQueryResultArticle(
                        title="GApps",
                        input_message_content=InputTextMessageContent(
                            "[\u200c](https://i.imgur.com/BZBMrfn.jpg) **LATEST Android 10 arm64 GApps**"
                        ),
                        description="Get Latest GApps Download Links Directly from SF",
                        thumb_url="https://i.imgur.com/Npzw8Ph.png",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    )
                )

            if len(string_split) == 2 and (string_split[0] == "ofox"):
                codename = string_split[1]
                t = TelegraphPoster(use_api=True)
                t.create_api_token("Userge-X")
                photo = "https://i.imgur.com/582uaSk.png"
                api_host = "https://api.orangefox.download/v2/device/"
                try:
                    async with get_response.get_session() as session:
                        r = await get_response.json(
                            f"{api_host}{codename}", session=session
                        )
                        s = await get_response.json(
                            f"{api_host}{codename}/releases/stable/last",
                            session=session,
                        )
                except ValueError:
                    return
                info = f"📱 **Device**: {r['fullname']}\n"
                info += f"👤 **Maintainer**: {r['maintainer']['name']}\n\n"
                recovery = f"🦊 <code>{s['file_name']}</code>\n"
                recovery += f"📅 {s['date']}\n"
                recovery += f"ℹ️ **Version:** {s['version']}\n"
                recovery += f"📌 **Build Type:** {s['build_type']}\n"
                recovery += f"🔰 **Size:** {s['size_human']}\n\n"
                recovery += "📍 **Changelog:**\n"
                recovery += f"<code>{s['changelog']}</code>\n\n"
                msg = info
                msg += recovery
                notes_ = s.get("notes")
                if notes_:
                    notes = t.post(title="READ Notes", author="", text=notes_)
                    buttons = [
                        [
                            InlineKeyboardButton("🗒️ NOTES", url=notes["url"]),
                            InlineKeyboardButton("⬇️ DOWNLOAD", url=s["url"]),
                        ]
                    ]
                else:
                    buttons = [[InlineKeyboardButton(text="⬇️ DOWNLOAD", url=s["url"])]]
                results.append(
                    InlineQueryResultPhoto(
                        photo_url=photo,
                        thumb_url="https://i.imgur.com/o0onLYB.jpg",
                        title="Latest OFOX RECOVERY",
                        description=f"For device : {codename}",
                        caption=msg,
                        reply_markup=InlineKeyboardMarkup(buttons),
                    )
                )

            if string == "repo":
                results.append(REPO_X)

            if len(str_y) == 2 and str_y[0] == "anime":
                for i in await Anime.search(str_y[1]):
                    results.append(
                        InlineQueryResultArticle(
                            title=i.get("title"),
                            input_message_content=InputTextMessageContent(
                                f'[\u200c]({i.get("image")})**{i.get("title")}**\n{i.get("release")}'
                            ),
                            description=i.get("release"),
                            thumb_url=i.get("image"),
                            reply_markup=InlineKeyboardMarkup(
                                [
                                    [
                                        InlineKeyboardButton(
                                            text="⬇️  Download",
                                            callback_data=f'get_eps{i.get("key")}',
                                        )
                                    ]
                                ]
                            ),
                        )
                    )
                if len(results) != 0:
                    await inline_query.answer(
                        results=results[:50],
                        cache_time=1,
                        switch_pm_text="Available Commands",
                        switch_pm_parameter="inline",
                    )
                    return

            if str_y[0] == "spoiler":
                if not os.path.exists(f"{Config.CACHE_PATH}/spoiler_db.json"):
                    results.append(
                        InlineQueryResultArticle(
                            title="No Spoiler Found",
                            input_message_content=InputTextMessageContent(
                                "No Spoiler Found !\nLet's Add Some 😈"
                            ),
                            description="See .help spoiler for more info",
                        )
                    )
                else:
                    bot_name = (await userge.bot.get_me()).username
                    if len(str_y) == 2:
                        link = f"https://t.me/{bot_name}?start=spoiler_{str_y[1]}"
                        buttons = [
                            [InlineKeyboardButton(text="View Spoiler", url=link)]
                        ]
                        results.append(
                            InlineQueryResultArticle(
                                title="Spoiler",
                                input_message_content=InputTextMessageContent(
                                    "<b>Click To View The Spoiler !</b>"
                                ),
                                description="Click To Send",
                                thumb_url="https://telegra.ph/file/ee3a6439494463acd1a3a.jpg",
                                reply_markup=InlineKeyboardMarkup(buttons),
                            )
                        )
                    else:
                        fo = open(f"{Config.CACHE_PATH}/spoiler_db.json")
                        view_db = ujson.load(fo)
                        fo.close()
                        if len(view_db) != 0:
                            for numm, spoilerr in enumerate(view_db, start=1):
                                buttons = [
                                    [
                                        InlineKeyboardButton(
                                            text="View Spoiler",
                                            url=f"https://t.me/{bot_name}?start=spoiler_{spoilerr}",
                                        )
                                    ]
                                ]
                                saved_at = view_db.get(spoilerr, None)
                                savetime = (
                                    saved_at.get("savetime", None) if saved_at else None
                                )
                                results.append(
                                    InlineQueryResultArticle(
                                        title=f"#{numm}  Spoiler",
                                        input_message_content=InputTextMessageContent(
                                            "<b>Click To View The Spoiler !</b>"
                                        ),
                                        description=f"Created At: {savetime}",
                                        thumb_url="https://telegra.ph/file/ee3a6439494463acd1a3a.jpg",
                                        reply_markup=InlineKeyboardMarkup(buttons),
                                    )
                                )

            if str_x[0].lower() == "op" and len(str_x) > 1:
                txt = i_q[3:]
                opinion = os.path.join(Config.CACHE_PATH, "emoji_data.txt")
                if os.path.exists(opinion):
                    with open(opinion) as fo:
                        view_data = ujson.load(fo)
                    # Uniquely identifies an inline message
                    new_id = {int(inline_query.id): [{}]}
                    view_data.update(new_id)
                else:
                    view_data = {int(inline_query.id): [{}]}
                with open(opinion, "w") as outfile:
                    ujson.dump(view_data, outfile)
                buttons = [
                    [
                        InlineKeyboardButton(
                            "👍", callback_data=f"op_y_{inline_query.id}"
                        ),
                        InlineKeyboardButton(
                            "👎", callback_data=f"op_n_{inline_query.id}"
                        ),
                    ]
                ]
                results.append(
                    InlineQueryResultArticle(
                        title="Ask For Opinion",
                        input_message_content=InputTextMessageContent(txt),
                        description=f"Q. {txt}",
                        thumb_url="https://i.imgur.com/Zlc98qS.jpg",
                        reply_markup=InlineKeyboardMarkup(buttons),
                    )
                )

            if "btn_" in str_y[0] or str_y[0] == "btn":
                inline_db_path = f"{Config.CACHE_PATH}/inline_db.json"
                if os.path.exists(inline_db_path):
                    with open(inline_db_path, "r") as data_file:
                        view_db = ujson.load(data_file)
                    data_count_n = 1
                    reverse_list = list(view_db)
                    reverse_list.reverse()
                    for butt_ons in reverse_list:
                        if data_count_n > 30:
                            view_db.pop(butt_ons, None)
                        data_count_n += 1
                    with open(inline_db_path, "w") as data_file:
                        ujson.dump(view_db, data_file)
                    if str_y[0] == "btn":
                        inline_storage = list(view_db)
                    else:
                        rnd_id = (str_y[0].split("_", 1))[1]
                        inline_storage = [rnd_id]
                    if len(inline_storage) == 0:
                        return
                    for inline_content in inline_storage:
                        inline_db = view_db.get(inline_content)
                        if inline_db:
                            if (
                                inline_db["media_valid"]
                                and int(inline_db["media_id"]) != 0
                            ):
                                saved_msg = await userge.bot.get_messages(
                                    Config.LOG_CHANNEL_ID, int(inline_db["media_id"])
                                )
                                media_data = get_file_id(saved_msg)
                            textx, buttonsx = pb(inline_db["msg_content"])
                            if inline_db["media_valid"]:
                                if saved_msg.photo:
                                    results.append(
                                        InlineQueryResultCachedPhoto(
                                            file_id=media_data,
                                            caption=textx,
                                            reply_markup=buttonsx,
                                        )
                                    )
                                else:
                                    results.append(
                                        InlineQueryResultCachedDocument(
                                            title=textx,
                                            file_id=media_data,
                                            caption=textx,
                                            description="Inline Button",
                                            reply_markup=buttonsx,
                                        )
                                    )
                            else:
                                results.append(
                                    InlineQueryResultArticle(
                                        title=textx,
                                        input_message_content=InputTextMessageContent(
                                            textx
                                        ),
                                        reply_markup=buttonsx,
                                    )
                                )

            if str_y[0].lower() == "stylish" and len(str_y) == 2:
                results = []
                for f_name in Styled.font_choice:
                    styled_str = font_gen(f_name, str_y[1])
                    results.append(
                        InlineQueryResultArticle(
                            title=f_name.upper(),
                            input_message_content=InputTextMessageContent(
                                f"`{styled_str}`"
                            ),
                            description=styled_str,
                        )
                    )
                await inline_query.answer(
                    results=results,
                    cache_time=1,
                    switch_pm_text="Available Commands",
                    switch_pm_parameter="inline",
                )
                return

            if str_x[0].lower() in ["secret", "troll"] and len(str_x) == 3:
                user_name = str_x[1]
                msg = str_x[2]
                try:
                    receiver = await userge.get_users(user_name)
                except (BadRequest, IndexError):
                    return
                secret = os.path.join(Config.CACHE_PATH, "secret.json")
                key_ = rand_key()
                r_name = (
                    ("@" + receiver.username)
                    if receiver.username
                    else f"{receiver.first_name} {receiver.last_name or ''}"
                )
                secret_data = {
                    key_: {
                        "sender": iq_user_id,
                        "receiver": {"id": receiver.id, "name": r_name},
                        "msg": msg,
                        "views": [],
                    }
                }
                if os.path.exists(secret):
                    with open(secret) as outfile:
                        view_data = ujson.load(outfile)
                    view_data.update(secret_data)
                else:
                    view_data = secret_data
                # Save
                with open(secret, "w") as r:
                    ujson.dump(view_data, r, indent=4)
                if str_x[0].lower() == "secret":
                    c_data = f"secret_{key_}"
                    i_m_content = f"📩 <b>Secret Msg</b> for <b>{r_name}</b>. Only he/she can open it."
                    i_l_des = f"Send Secret Message to: {r_name}"
                    title = "Send A Secret Message"
                    thumb_img = "https://i.imgur.com/c5pZebC.png"
                else:
                    c_data = f"troll_{key_}"
                    i_m_content = f"😈 Only <b>{r_name}</b> can't view this message. UwU"
                    i_l_des = f"Message Hidden from {r_name}"
                    title = "😈 Troll"
                    thumb_img = "https://i.imgur.com/0vg5B0A.png"
                buttons = [[InlineKeyboardButton("🔐  SHOW", callback_data=c_data)]]
                results.append(
                    InlineQueryResultArticle(
                        title=title,
                        input_message_content=InputTextMessageContent(i_m_content),
                        description=i_l_des,
                        thumb_url=thumb_img,
                        reply_markup=InlineKeyboardMarkup(buttons),
                    )
                )

            if str_y[0].lower() == "ytdl" and len(str_y) == 2:
                link = get_yt_video_id(str_y[1].strip())
                found_ = True
                if link is None:
                    search = VideosSearch(str_y[1].strip(), limit=15)
                    resp = (search.result()).get("result")
                    if len(resp) == 0:
                        found_ = False
                    else:
                        outdata = await result_formatter(resp)
                        key_ = rand_key()
                        ytsearch_data.store_(key_, outdata)
                        buttons = InlineKeyboardMarkup(
                            [
                                [
                                    InlineKeyboardButton(
                                        text=f"1 / {len(outdata)}",
                                        callback_data=f"ytdl_next_{key_}_1",
                                    )
                                ],
                                [
                                    InlineKeyboardButton(
                                        text="📜  List all",
                                        callback_data=f"ytdl_listall_{key_}_1",
                                    ),
                                    InlineKeyboardButton(
                                        text="⬇️  Download",
                                        callback_data=f'ytdl_download_{outdata[1]["video_id"]}_0',
                                    ),
                                ],
                            ]
                        )
                        caption = outdata[1]["message"]
                        photo = outdata[1]["thumb"]
                else:
                    caption, buttons = await download_button(link, body=True)
                    photo = await get_ytthumb(link)

                if found_:
                    results.append(
                        InlineQueryResultPhoto(
                            photo_url=photo,
                            title=link,
                            description="⬇️ Click to Download",
                            caption=caption,
                            reply_markup=buttons,
                        )
                    )
                else:
                    results.append(
                        InlineQueryResultArticle(
                            title="not Found",
                            input_message_content=InputTextMessageContent(
                                f"No Results found for `{str_y[1]}`"
                            ),
                            description="INVALID",
                        )
                    )

            MAIN_MENU = InlineQueryResultArticle(
                title="Main Menu",
                input_message_content=InputTextMessageContent(" 𝐒𝐇𝐀𝐑𝐈𝐍𝐆𝐀𝐍 MAIN MENU "),
                url="https://github.com/code-rgb/USERGE-X",
                description="Sharingan Main Menu",
                thumb_url="https://telegra.ph/file/8fa91f9c7f6f4f6b8fa6c.jpg",
                reply_markup=InlineKeyboardMarkup(main_menu_buttons()),
            )
            results.append(MAIN_MENU)
            if len(results) != 0:
                await inline_query.answer(
                    results=results,
                    cache_time=1,
                    switch_pm_text="Available Commands",
                    switch_pm_parameter="inline",
                )
        else:
            results.append(REPO_X)
            owner_name = (await userge.get_me()).first_name
            await inline_query.answer(
                results=results,
                cache_time=1,
                switch_pm_text=f"This bot is only for {owner_name}",
                switch_pm_parameter="start",
            )
コード例 #30
0
    def compile(self, ctx, time, number, term):

        actual_time = int(time.content)

        video = VideosSearch(term.content, limit=int(number.content))

        filename_list = []
        youtube_list = []
        clip_list = []

        for i in range(int(number.content)):

            ydl_opts = {
                'format': '136',
                'outtmpl':
                f"/root/vc/video/{str(video.result()['result'][i]['id'])}.mp4",
                'ignoreerrors': True
            }

            video_link = video.result()['result'][i]['link']

            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([video_link])
            try:
                length = video.result()['result'][i]['duration']

                calculated_length = sum(
                    int(x) * 60**i
                    for i, x in enumerate(reversed(length.split(":"))))
                if calculated_length < 1800:
                    stripped_length = calculated_length / 2 - actual_time

                    clip = VideoFileClip(
                        f"/root/vc/video/{str(video.result()['result'][i]['id'])}.mp4"
                    )
                    clip = clip.subclip(stripped_length, calculated_length / 2)
                    clip = clip.crossfadein(1.0)
                    clip = clip.crossfadeout(1.0)
                    clip.write_videofile(
                        filename=f"video/{ctx.author.name}{[i]}.mp4",
                        threads=64,
                        fps=30)

                    filename_list.append(clip)
                    clip_list.append(f"video/{ctx.author.name}{[i]}.mp4")
                    youtube_list.append(
                        f"{str(video.result()['result'][i]['id'])}.mp4")
                else:
                    int(number.content) + 1
                    pass
            except Exception as e:
                print(e)
                pass

        else:
            final_clip = concatenate_videoclips(filename_list,
                                                method="compose")
            final_clip.write_videofile(f"video/{ctx.author.id}.mp4",
                                       threads=64,
                                       fps=30)

            client = storage.Client.from_service_account_json(
                json_credentials_path="/root/vc/config.json")

            bucket = client.get_bucket('compiledvideos')

            send_name = bucket.blob(f"videos/{ctx.message.id}.mp4")
            send_name.upload_from_filename(f"video/{ctx.author.id}.mp4")

            mypath = "/root/vc/video"
            for root, dirs, files in os.walk(mypath):
                for file in files:
                    if file in youtube_list:
                        os.remove(os.path.join(root, file))
                    elif file in clip_list:
                        os.remove(os.path.join(root, file))