Example #1
0
async def play(_, message: Message):

    lel = await message.reply(f"**{bn} :-** 🔎 Şarkı buluyorum...")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    print(query)
    await lel.edit(f"**{bn} :-** 🎵 işleme alındı {query}")
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        url = f"https://youtube.com{results[0]['url_suffix']}"
        #print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f'thumb{title}.jpg'
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, 'wb').write(thumb.content)

        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        lel.edit(
            f"**{bn} :-** ❌ Şarkı bulunamadı.\nTry başka bir şarkı veya belki düzgün hecelemeye çalışın."
        )
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup(
        [[InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")]])

    keyboard2 = InlineKeyboardMarkup(
        [[InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")]])

    audio = (message.reply_to_message.audio or message.reply_to_message.voice
             ) if message.reply_to_message else None

    if audio:
        await lel.edit_text(f"**{bn} :-** Hehe 🥴")

    elif url:
        file_path = await converter.convert(youtube.download(url))
    else:
        return await lel.edit_text(
            f"**{bn} :-** ❗ Bana oynayacak bir şey vermedin!")

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        await message.reply_photo(
            photo=thumb_name,
            caption=
            f"**{bn} :-** İstediğiniz şarkı **sıraya** alındı #{position} !",
            reply_markup=keyboard2)
        return await lel.delete()
    else:
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo=thumb_name,
            reply_markup=keyboard,
            caption="▶️ **Oynatılıyor** burada istenen şarkı {}".format(
                message.from_user.mention()),
        )
        return await lel.delete()
Example #2
0
async def play(_, message: Message):

    lel = await message.reply("🔄 **Processing** Sounds...")
    sender_id = message.from_user.id
    sender_name = message.from_user.first_name

    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton(text="Channel", url="https://t.me/Infinity_BOTs")
    ]])

    audio = (message.reply_to_message.audio or message.reply_to_message.voice
             ) if message.reply_to_message else None
    url = get_url(message)

    if audio:
        if round(audio.duration / 60) > DURATION_LIMIT:
            raise DurationLimitError(
                f"❌ Videos longer than {DURATION_LIMIT} minute(s) aren't allowed to play!"
            )

        file_name = get_file_name(audio)
        title = file_name
        thumb_name = "https://telegra.ph/file/638c20c44ca418c8b2178.jpg"
        thumbnail = thumb_name
        duration = round(audio.duration / 60)
        views = "Locally added"
        keyboard = InlineKeyboardMarkup([[
            InlineKeyboardButton(text="Channel",
                                 url=f"https://t.me/Infinity_Bots")
        ]])
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await converter.convert((
            await message.reply_to_message.download(file_name)
        ) if not path.isfile(path.join("downloads", file_name)) else file_name)
    elif url:
        try:
            results = YoutubeSearch(url, max_results=1).to_dict()
            # url = f"https://youtube.com{results[0]['url_suffix']}"
            #print(results)
            title = results[0]["title"][:40]
            thumbnail = results[0]["thumbnails"][0]
            thumb_name = f'thumb{title}.jpg'
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, 'wb').write(thumb.content)
            duration = results[0]["duration"]
            url_suffix = results[0]["url_suffix"]
            views = results[0]["views"]
            keyboard = InlineKeyboardMarkup(
                [[InlineKeyboardButton(text="Watch On YouTube",
                                       url=f"{url}")]])
        except Exception as e:
            title = "NaN"
            thumb_name = "https://telegra.ph/file/638c20c44ca418c8b2178.jpg"
            duration = "NaN"
            views = "NaN"
            keyboard = InlineKeyboardMarkup([[
                InlineKeyboardButton(text="Watch On YouTube",
                                     url=f"https://youtube.com")
            ]])
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await converter.convert(youtube.download(url))
    else:
        await lel.edit("🔎 **Finding** the song...")
        sender_id = message.from_user.id
        user_id = message.from_user.id
        sender_name = message.from_user.first_name
        user_name = message.from_user.first_name
        rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

        query = ''
        for i in message.command[1:]:
            query += ' ' + str(i)
        print(query)
        await lel.edit("🎵 **Processing** sounds...")
        ydl_opts = {"format": "bestaudio[ext=m4a]"}
        try:
            results = YoutubeSearch(query, max_results=1).to_dict()
            url = f"https://youtube.com{results[0]['url_suffix']}"
            #print(results)
            title = results[0]["title"][:40]
            thumbnail = results[0]["thumbnails"][0]
            thumb_name = f'thumb{title}.jpg'
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, 'wb').write(thumb.content)
            duration = results[0]["duration"]
            url_suffix = results[0]["url_suffix"]
            views = results[0]["views"]

        except Exception as e:
            lel.edit(
                "❌ Song not found.\n\nTry another song or maybe spell it properly."
            )
            print(str(e))
            return

        keyboard = InlineKeyboardMarkup(
            [[InlineKeyboardButton(text="Watch On YouTube", url=f"{url}")]])
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await converter.convert(youtube.download(url))

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        await message.reply_photo(
            photo="final.png",
            caption=
            f"#⃣ Your requested song **queued** at position {position}!",
            reply_markup=keyboard)
        os.remove("final.png")
        return await lel.delete()
    else:
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption="▶️ **Playing** here the song requested by {} via YouTube 🎵"
            .format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
def launch_serve():
    print("Getting information..")
    name = ""
    description = ""
    video_results = []
    exercise_images = []
    relative_limit = randint(0, 10)
    relative_offset = randint(0, 100)
    count = 0
    image = None
    flag = True
    while flag:
        flag = True
        equipement = randomizer(EQUIPEMENT)
        print("offset:", relative_offset, "limit:", relative_limit, "total:",
              count, "equipement:", EQUIPEMENT[equipement]["name"])
        equipement_id = EQUIPEMENT[equipement]["id"]
        exercises = Exercise().get_filtered({
            "language": 2,
            "equipment": equipement_id,
            "limit": relative_limit,
            "offset": relative_offset
        })
        relative_limit, relative_offset = random_limiter(exercises.total)
        count = exercises.total
        exercises = exercises.results
        if len(exercises) == 0:
            continue
        if IMAGES:
            for exercise in exercises:
                print(".")
                exercise_images = ExerciseImage().get_filtered({
                    "exercise":
                    exercise["id"]
                }).results
                if len(exercise_images) > 0:
                    description = exercise["description"]
                    name = exercise["name"]
                    image = exercise_images[0]["image"]
                    flag = False
                    break
        else:
            exercise = exercises[randomizer(exercises)]
            description = exercise["description"]
            name = exercise["name"]
            break
        print("...")

    video_results = YoutubeSearch(name + " {} workout".format(SEX),
                                  max_results=9).to_dict()
    data = {
        "title": name,
        "description": description,
        "image": image,
        "videos": video_results
    }

    with open('src/data.js', 'w') as text_file:
        data = json.dumps(data)
        data = "const data=" + data
        text_file.write(data)

    handler = HttpRequestHandler
    host = "http://localhost:{}".format(PORT)
    print("Open at", host)
    server = HTTPServer(server_address=('', PORT), RequestHandlerClass=handler)
    webbrowser.open(host, new=2)
    server.serve_forever()
Example #4
0
async def play(_, message: Message):
    global que
    lel = await message.reply("🔄 **Processing**")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id

    try:
        user = await USER.get_me()
    except:
        user.first_name = "helper"
    usar = user
    wew = usar.id
    try:
        #chatdetails = await USER.get_chat(chid)
        lmoa = await _.get_chat_member(chid, wew)
    except:
        for administrator in administrators:
            if administrator == message.from_user.id:
                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>Add me as admin of yor group first</b>", )
                    return

                try:
                    await USER.join_chat(invitelink)
                    await USER.send_message(
                        message.chat.id,
                        "I joined this group for playing music in VC")
                    await lel.edit("<b>helper userbot joined your chat</b>", )

                except UserAlreadyParticipant:
                    pass
                except Exception as e:
                    #print(e)
                    await lel.edit(
                        f"<b>🔴 Flood Wait Error 🔴 \nUser {user.first_name} couldn't join your group due to heavy requests for userbot! Make sure user is not banned in group."
                        "\n\nOr manually add @YUI_VC_ASSISTANT to your Group and try again</b>",
                    )
                    pass
    try:
        chatdetails = await USER.get_chat(chid)
        #lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i> {user.first_name} Userbot not in this chat, Ask admin to send /play command for first time or add {user.first_name} manually</i>"
        )
        return
    sender_id = message.from_user.id
    sender_name = message.from_user.first_name
    await lel.edit("🔎 **Finding**")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    print(query)
    await lel.edit("🎶 **Processing**")
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        url = f"https://youtube.com{results[0]['url_suffix']}"
        #print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f'thumb{title}.jpg'
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, 'wb').write(thumb.content)
        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        await lel.edit(
            "Song not found.Try another song or maybe spell it properly.")
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton('📖 Playlist', callback_data='playlist'),
        InlineKeyboardButton('Menu ⏯ ', callback_data='menu')
    ], [InlineKeyboardButton(text="Watch On YouTube 🎥", url=f"{url}")
        ], [InlineKeyboardButton(text="❌ Close", callback_data='cls')]])
    requested_by = message.from_user.first_name
    await generate_cover(requested_by, title, views, duration, thumbnail)
    file_path = await converter.convert(youtube.download(url))

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await message.reply_photo(
            photo="final.png",
            caption=
            f"#⃣ Your requested song **queued** at position {position}!",
            reply_markup=keyboard)
        os.remove("final.png")
        return await lel.delete()
    else:
        chat_id = message.chat.id
        que[chat_id] = []
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption=
            "▶️ **Playing** here the song requested by {} via @Emcee_Assistant_VC ꧂"
            .format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
Example #5
0
async def sonf_REG(client, message):
    chat_id = message.chat.id
    user_id = message.from_user.id
    user_name = message.from_user.first_name
    mention = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"
    
    if not message.reply_to_message:
        await message.reply_text("Reply to a short video to recognize song.")
        return
    if not message.reply_to_message.video:
        await message.reply_text("Reply to a short video to recognize song.")
        return
    m = await message.reply_text("Listening 🎶")
    
    target = message.reply_to_message.video.file_id
    print(target) #-------------------test
    await app.download_media(target, file_name=f"res/blackmusic-{message.message_id}.mp4")
    
    
    shazam = Shazam()
    out = await shazam.recognize_song(f'res/blackmusic-{message.message_id}.mp4')
    try:
        await m.edit("Analysing 🔎")
        item = out.get("track")
        title = item.get("title")
        artist = item.get("subtitle")
        query = (f"{title} - {artist}")
    except Exception: 
        await m.edit("Sorry, failed to find your song ☹️")
        return
    
    #------------------------------------------------------+ new func
    await m.edit('Trying to download 😎')
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = []
        count = 0
        while len(results) == 0 and count < 6:
            if count>0:
                time.sleep(1)
            results = YoutubeSearch(query, max_results=1).to_dict()
            count += 1
        try:
            duration = results[0]["duration"]
            if time_to_seconds(duration) >= 900:  
                await m.edit("**Sorry!**\n\nMax Duration is 15min")
                return           
            
            link = f"https://youtube.com{results[0]['url_suffix']}"
            title = results[0]["title"][:35]
            thumbnail = results[0]["thumbnails"][0]
            thumb_name = f'thumb{message.message_id}.jpg'
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, 'wb').write(thumb.content)
            
            title_turple = (str(chat_id),title)
            user_turple = (str(user_id), title)

   
       
        except Exception as e:
            print(e)
            await m.edit(
                f"**No results Error 🐞**"
                f"\n\nSorry {message.from_user.first_name} i did't find anything with your keyword: `{query}`"
                )
            return
    except Exception as e:
        await m.edit(
            ""
        )
        print(str(e))
        return



    await m.edit("⏬ Downloading.")
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(link, download=False)
            audio_file = ydl.prepare_filename(info_dict)
            ydl.process_info(info_dict)
        secmul, dur, dur_arr = 1, 0, duration.split(':')
        for i in range(len(dur_arr)-1, -1, -1):
            dur += (int(dur_arr[i]) * secmul)
            secmul *= 60
        song = await message.reply_audio(audio_file, parse_mode='md',quote=False,thumb=thumb_name,
                                   reply_to_message_id=message.message_id, 
                                   title=title, duration=dur,
                                   caption=f"☈ Title**: {title}"
                                                        f"\n**☈ Duration**: `{duration}`"
                                                        f"\n**☈ Link**: [Click here]({link})"
                                                        f"\n**☈ Requested by**: {mention}")
        await m.delete()

        
    except Exception as e:
        print(e)
    try:
        os.remove(audio_file)
        os.remove(thumb_name)
        os.remove(f'res/blackmusic-{message.message_id}.mp4')
    except Exception as e:
        print(e)
Example #6
0
async def ytplay(_, message: Message):
    global que
    if message.chat.id in DISABLED_GROUPS:
        return
    lel = await message.reply("🔄 <b>Processing</b>")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id

    try:
        user = await USER.get_me()
    except:
        user.first_name = "helper"
    usar = user
    wew = usar.id
    try:
        # chatdetails = await USER.get_chat(chid)
        await _.get_chat_member(chid, wew)
    except:
        for administrator in administrators:
            if administrator == message.from_user.id:
                if message.chat.title.startswith("Channel Music: "):
                    await lel.edit(
                        "<b>Remember to add helper to your channel</b>", )
                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>Add me as admin of yor group first</b>", )
                    return

                try:
                    await USER.join_chat(invitelink)
                    await USER.send_message(
                        message.chat.id,
                        "I joined this group for playing music in VC")
                    await lel.edit("<b>helper userbot joined your chat</b>", )

                except UserAlreadyParticipant:
                    pass
                except Exception:
                    # print(e)
                    await lel.edit(
                        f"<b>🔴 Flood Wait Error 🔴 \nUser {user.first_name} couldn't join your group due to heavy requests for userbot! Make sure user is not banned in group."
                        "\n\nOr manually add assistant to your Group and try again</b>",
                    )
    try:
        await USER.get_chat(chid)
        # lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i> {user.first_name} Userbot not in this chat, Ask admin to send /play command for first time or add {user.first_name} manually</i>"
        )
        return
    await lel.edit("🔎 <b>Finding</b>")
    message.from_user.id
    message.from_user.first_name

    query = ""
    for i in message.command[1:]:
        query += " " + str(i)
    print(query)
    await lel.edit("🎵 <b>Processing</b>")
    ydl_opts = {"format": "bestaudio/best"}
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        url = f"https://youtube.com{results[0]['url_suffix']}"
        # print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f"thumb{title}.jpg"
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, "wb").write(thumb.content)
        duration = results[0]["duration"]
        results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        await lel.edit(
            "Song not found.Try another song or maybe spell it properly.")
        print(str(e))
        return
    try:
        secmul, dur, dur_arr = 1, 0, duration.split(":")
        for i in range(len(dur_arr) - 1, -1, -1):
            dur += int(dur_arr[i]) * secmul
            secmul *= 60
        if (dur / 60) > DURATION_LIMIT:
            await lel.edit(
                f"❌ Videos longer than {DURATION_LIMIT} minutes aren't allowed to play!"
            )
            return
    except:
        pass
    dlurl = url
    dlurl = dlurl.replace("youtube", "youtubepp")
    keyboard = InlineKeyboardMarkup([
        [
            InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
            InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
        ],
        [
            InlineKeyboardButton(text="🎬 YouTube", url=f"{url}"),
            InlineKeyboardButton(text="Download 📥", url=f"{dlurl}"),
        ],
        [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
    ])
    requested_by = message.from_user.first_name
    await generate_cover(requested_by, title, views, duration, thumbnail)
    file = await convert(youtube.download(url))
    chat_id = get_chat_id(message.chat)
    if chat_id in callsmusic.active_chats:
        position = await queues.put(chat_id, file=file)
        qeue = que.get(chat_id)
        s_name = title
        r_by = message.from_user
        loc = file
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await message.reply_photo(
            photo="final.png",
            caption=
            f"#⃣ Your requested song <b>queued</b> at position {position}!",
            reply_markup=keyboard,
        )
        os.remove("final.png")
        return await lel.delete()
    else:
        chat_id = get_chat_id(message.chat)
        que[chat_id] = []
        qeue = que.get(chat_id)
        s_name = title
        r_by = message.from_user
        loc = file
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        try:
            await callsmusic.set_stream(chat_id, file)
        except:
            message.reply("Group Call is not connected or I can't join it")
            return
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption=
            "▶️ <b>Playing</b> here the song requested by {} via Youtube Music 😎"
            .format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
Example #7
0
def _play():    
    btn2['state'] = 'disabled'    
    btn1.configure(bg = 'orange')         
          
        # btn1.configure(bg = 'orange')
    text = takeCommand().lower()

    get_location(text)
    get_day(text)
    get_time(text)

    if 'kết thúc' in text:
        goodbye()
        window.destroy()
        # break    
    elif 'xin chào' in text:
        hello()

    elif 'gọi tôi là' in text:
        id_end = text.find("gọi tôi là") + len("gọi tôi là ")
        show_name(text[id_end:])
    elif 'thời tiết' in text:            
        weather_description = get_weather()
        var.set(weather_description)    
        window.update()        
        speak(weather_description, 'weather.mp3')

        #open browser
    elif 'mở trình duyệt' in text:
        url='google.com'
        webbrowser.open(url, autoraise=False)
        var.set('mở trình duyệt')
        window.update()
        speak('mở trình duyệt', 'browser.mp3')

    #search: mở link đầu tiên trên tab mới
    elif 'tìm' in text:
        #get query string
        pos = text.find('tìm')
        query = text[pos+len('tìm'):].strip()

        #mở link đầu tiên trên trình duyệt
        url = next(search(query, tld='com', lang='en', num=1, domains= ['com', 'org', 'vn'], start=0, stop=None, pause=2))
        # print(url)
        webbrowser.open(url, autoraise=False)
        end_speech = 'tìm kiếm ' + query
        var.set(end_speech)
        window.update()
        speak(end_speech, 'search.mp3')

    #open music on youtube
    elif 'bật' in text:
        # subprocess.call(r'C:\Users\Acer\AppData\Roaming\Spotify/Spotify.exe')
        #get query string
        pos = text.find('bật')
        query = text[pos+len('bật'):].strip()
        if query == 'nhạc' or query == 'nhạc đi':
            webbrowser.open(DEFAULT_MUSIC, autoraise=False)
            var.set('bật nhạc')    
            window.update()
            speak('bật nhạc', 'music.mp3')
        else:
            ytsearch = YoutubeSearch(query, max_results=1).to_dict()
            if len(ytsearch) > 0:
                results = ytsearch[0]
                url = 'youtube.com' + results.get('link')
                print(url)
                webbrowser.open(url, autoraise=False)    #autoraise=false không hoạt động ở windows
                end_speech = 'mở bài ' + query
                var.set(end_speech)
                window.update()
                speak(end_speech, 'music.mp3')
            else:
                var.set('Jarvis không tìm thấy bài ' + query)
                window.update()
                speak('Jarvis không tìm thấy bài ' + query, 'sorry.mp3')

    else:
        var.set('Jarvis không hiểu bạn')
        window.update()
        speak('Javis không hiểu bạn nói gì')
Example #8
0
async def a(client, message: Message):
    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    okvai = query.capitalize()
    print(query.capitalize())
    m = await message.reply(f"`{okvai}` __adlı parça aranıyor...__")
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = []
        count = 0
        while len(results) == 0 and count < 6:
            if count > 0:
                time.sleep(1)
            results = YoutubeSearch(query, max_results=1).to_dict()
            count += 1
        # results = YoutubeSearch(query, max_results=1).to_dict()
        try:
            link = f"https://youtube.com{results[0]['url_suffix']}"
            # print(results)
            title = results[0]["title"]
            thumbnail = results[0]["thumbnails"][0]
            duration = results[0]["duration"]

            ## UNCOMMENT THIS IF YOU WANT A LIMIT ON DURATION. CHANGE 1800 TO YOUR OWN PREFFERED DURATION AND EDIT THE MESSAGE (30 minutes cap) LIMIT IN SECONDS
            # if time_to_seconds(duration) >= 1800:  # duration limit
            #     m.edit("Exceeded 30mins cap")
            #     return

            views = results[0]["views"]
            thumb_name = f'thumb{message.message_id}.jpg'
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, 'wb').write(thumb.content)

        except Exception as e:
            m.edit(f"`Aradığınız şarkı bulunamadı.\n\n{e}`")
            return
    except Exception as e:
        m.edit(
            f"`Aradığınız şarkı bulunamadı. \n\nYazıyı değiştirerek tekrar deneyin.`"
        )
        print(str(e))
        return
    await m.edit(f"`{query}` __adlı parça yükleniyor...__")
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(link, download=False)
            audio_file = ydl.prepare_filename(info_dict)
            ydl.process_info(info_dict)
        rep = f'🎶 **İsim:** [{title[:35]}]({link})\n⏳ **Süre:** {duration}\n👀 **İzlenme:** {views}'
        secmul, dur, dur_arr = 1, 0, duration.split(':')
        for i in range(len(dur_arr) - 1, -1, -1):
            dur += (int(dur_arr[i]) * secmul)
            secmul *= 60
        await message.reply_audio(audio_file,
                                  caption=rep,
                                  parse_mode='md',
                                  quote=False,
                                  title=title,
                                  duration=dur,
                                  thumb=thumb_name)
        await m.delete()
    except Exception as e:
        m.edit(f"Hata! \n\n{e}")
    try:
        os.remove(audio_file)
        os.remove(thumb_name)
    except Exception as e:
        print(e)
Example #9
0
async def song(client, message):

    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    print(query)
    shed = message.reply("🔎 Finding the song...")
    ydl_opts = {
        "format": "bestaudio[ext=m4a]",
        "geo-bypass": True,
        "nocheckcertificate": True,
        "outtmpl": "downloads/%(id)s.%(ext)s",
    }
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        link = f"https://youtube.com{results[0]['url_suffix']}"
        #print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f'thumb{title}.jpg'
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, 'wb').write(thumb.content)

        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]
        channel = results[0]["channel"]
    except Exception as e:
        shed.edit(
            "❌ Found Nothing.\n\nTry another keywork or maybe spell it properly."
        )
        print(str(e))
        return
    shed.edit("📥 Downloading...")
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(link, download=False)
            audio_file = ydl.prepare_filename(info_dict)
            ydl.process_info(info_dict)
        rep = '@JEBotZ'
        secmul, dur, dur_arr = 1, 0, duration.split(':')
        for i in range(len(dur_arr) - 1, -1, -1):
            dur += (int(dur_arr[i]) * secmul)
            secmul *= 60
        shed.edit("📤 Uploading...")
        s = message.reply_audio(audio_file,
                                caption=rep,
                                thumb=thumb_name,
                                parse_mode='md',
                                title=title,
                                duration=dur,
                                performer=channel)
        shed.delete()
    except Exception as e:
        shed.edit("❌ Error")
        print(e)

    try:
        os.remove(audio_file)
        os.remove(thumb_name)
    except Exception as e:
        print(e)
Example #10
0
import requests
from io import BytesIO
import numpy as np
from matplotlib.pyplot import imshow
from pytube import YouTube
from youtube_search import YoutubeSearch
import warnings
warnings.filterwarnings("ignore")
from docsim import YTCompare

pd.set_option('display.max_columns', None)

search_term = 'learn python programming'
max_results = 30

results = YoutubeSearch(search_term, max_results=max_results).to_json()
res = json.loads(results)['videos']

links = [res[i]['link'] for i in range(max_results)]

ytdatalist = []
for i in range(max_results):
    yt = YouTube('http://youtube.com/{}'.format(links[i]))
    ytdata = {
        'title': yt.title,
        'thurl': yt.thumbnail_url,
        'length': yt.length,
        'views': yt.views,
        'author': yt.author
    }
    ytdatalist.append(ytdata)
Example #11
0
async def add_to_playlist(_, message: Message):
    with suppress(MessageIdInvalid, MessageNotModified):
        admins = await get_admins(Config.CHAT)
        if Config.ADMIN_ONLY:
            if not (message.from_user is None and message.sender_chat
                    or message.from_user.id in admins):
                k = await message.reply_sticker(
                    "CAADBQADsQIAAtILIVYld1n74e3JuQI")
                await delete_messages([message, k])
                return
        type = ""
        yturl = ""
        ysearch = ""
        url = ""
        if message.command[0] == "fplay":
            if not (message.from_user is None and message.sender_chat
                    or message.from_user.id in admins):
                k = await message.reply("This command is only for admins.")
                await delete_messages([message, k])
                return
        msg = await message.reply_text("⚡️ **Checking recived input..**")
        if message.reply_to_message and message.reply_to_message.video:
            await msg.edit("⚡️ **Checking Telegram Media...**")
            type = 'video'
            m_video = message.reply_to_message.video
        elif message.reply_to_message and message.reply_to_message.document:
            await msg.edit("⚡️ **Checking Telegram Media...**")
            m_video = message.reply_to_message.document
            type = 'video'
            if not "video" in m_video.mime_type:
                return await msg.edit("The given file is invalid")
        elif message.reply_to_message and message.reply_to_message.audio:
            #if not Config.IS_VIDEO:
            #return await message.reply("Play from audio file is available only if Video Mode if turned off.\nUse /settings to configure ypur player.")
            await msg.edit("⚡️ **Checking Telegram Media...**")
            type = 'audio'
            m_video = message.reply_to_message.audio
        else:
            if message.reply_to_message and message.reply_to_message.text:
                query = message.reply_to_message.text
            elif " " in message.text:
                text = message.text.split(" ", 1)
                query = text[1]
            else:
                await msg.edit(
                    "You Didn't gave me anything to play.Reply to a video or a youtube link or a direct link."
                )
                await delete_messages([message, msg])
                return
            regex = r"^(?:https?:\/\/)?(?:www\.)?youtu\.?be(?:\.com)?\/?.*(?:watch|embed)?(?:.*v=|v\/|\/)([\w\-_]+)\&?"
            match = re.match(regex, query)
            if match:
                type = "youtube"
                yturl = query
            elif query.startswith("http"):
                try:
                    has_audio_ = await is_audio(query)
                except:
                    has_audio_ = False
                    LOGGER.error("Unable to get Audio properties within time.")
                if has_audio_:
                    try:
                        dur = await get_duration(query)
                    except:
                        dur = 0
                    if dur == 0:
                        await msg.edit(
                            "This is a live stream, Use /stream command.")
                        await delete_messages([message, msg])
                        return
                    type = "direct"
                    url = query
                else:
                    if is_ytdl_supported(query):
                        type = "ytdl_s"
                        url = query
                    else:
                        await msg.edit(
                            "This is an invalid link, provide me a direct link or a youtube link."
                        )
                        await delete_messages([message, msg])
                        return
            else:
                type = "query"
                ysearch = query
        if not message.from_user is None:
            user = f"[{message.from_user.first_name}](tg://user?id={message.from_user.id})"
            user_id = message.from_user.id
        else:
            user = "******"
            user_id = "anonymous_admin"
        now = datetime.now()
        nyav = now.strftime("%d-%m-%Y-%H:%M:%S")
        if type in ["video", "audio"]:
            if type == "audio":
                if m_video.title is None:
                    if m_video.file_name is None:
                        title_ = "Music"
                    else:
                        title_ = m_video.file_name
                else:
                    title_ = m_video.title
                if m_video.performer is not None:
                    title = f"{m_video.performer} - {title_}"
                else:
                    title = title_
                unique = f"{nyav}_{m_video.file_size}_audio"
            else:
                title = m_video.file_name
                unique = f"{nyav}_{m_video.file_size}_video"
                if Config.PTN:
                    ny = parse(title)
                    title_ = ny.get("title")
                    if title_:
                        title = title_
            file_id = m_video.file_id
            if title is None:
                title = 'Music'
            data = {1: title, 2: file_id, 3: "telegram", 4: user, 5: unique}
            if message.command[0] == "fplay":
                pla = [data] + Config.playlist
                Config.playlist = pla
            else:
                Config.playlist.append(data)
            await add_to_db_playlist(data)
            await msg.edit("Media added to playlist")
        elif type in ["youtube", "query", "ytdl_s"]:
            if type == "youtube":
                await msg.edit("⚡️ **Fetching Video From YouTube...**")
                url = yturl
            elif type == "query":
                try:
                    await msg.edit("⚡️ **Fetching Video From YouTube...**")
                    ytquery = ysearch
                    results = YoutubeSearch(ytquery, max_results=1).to_dict()
                    url = f"https://youtube.com{results[0]['url_suffix']}"
                    title = results[0]["title"][:40]
                except Exception as e:
                    await msg.edit("Song not found.\nTry inline mode..")
                    LOGGER.error(str(e), exc_info=True)
                    await delete_messages([message, msg])
                    return
            elif type == "ytdl_s":
                url = url
            else:
                return
            ydl_opts = {
                "quite": True,
                "geo-bypass": True,
                "nocheckcertificate": True
            }
            ydl = YoutubeDL(ydl_opts)
            try:
                info = ydl.extract_info(url, False)
            except Exception as e:
                LOGGER.error(e, exc_info=True)
                await msg.edit(f"YouTube Download Error ❌\nError:- {e}")
                LOGGER.error(str(e))
                await delete_messages([message, msg])
                return
            if type == "ytdl_s":
                title = "Music"
                try:
                    title = info['title']
                except:
                    pass
            else:
                title = info["title"]
                if info['duration'] is None:
                    await msg.edit(
                        "This is a live stream, Use /stream command.")
                    await delete_messages([message, msg])
                    return
            data = {
                1: title,
                2: url,
                3: "youtube",
                4: user,
                5: f"{nyav}_{user_id}"
            }
            if message.command[0] == "fplay":
                pla = [data] + Config.playlist
                Config.playlist = pla
            else:
                Config.playlist.append(data)
            await add_to_db_playlist(data)
            await msg.edit(f"[{title}]({url}) added to playist",
                           disable_web_page_preview=True)
        elif type == "direct":
            data = {
                1: "Music",
                2: url,
                3: "url",
                4: user,
                5: f"{nyav}_{user_id}"
            }
            if message.command[0] == "fplay":
                pla = [data] + Config.playlist
                Config.playlist = pla
            else:
                Config.playlist.append(data)
            await add_to_db_playlist(data)
            await msg.edit("Link added to playlist")
        if not Config.CALL_STATUS \
            and len(Config.playlist) >= 1:
            await msg.edit("Downloading and Processing...")
            await download(Config.playlist[0], msg)
            await play()
        elif (len(Config.playlist) == 1 and Config.CALL_STATUS):
            await msg.edit("Downloading and Processing...")
            await download(Config.playlist[0], msg)
            await play()
        elif message.command[0] == "fplay":
            await msg.edit("Downloading and Processing...")
            await download(Config.playlist[0], msg)
            await play()
        else:
            await send_playlist()
        await msg.delete()
        pl = await get_playlist_str()
        if message.chat.type == "private":
            await message.reply(pl,
                                reply_markup=await get_buttons(),
                                disable_web_page_preview=True)
        elif not Config.LOG_GROUP and message.chat.type == "supergroup":
            if Config.msg.get('playlist') is not None:
                await Config.msg['playlist'].delete()
            Config.msg['playlist'] = await message.reply(
                pl,
                disable_web_page_preview=True,
                reply_markup=await get_buttons())
            await delete_messages([message])
        for track in Config.playlist[:2]:
            await download(track)
Example #12
0
def search(text):
    # Search on youtube and pick first result
    result = YoutubeSearch(text, max_results=1).to_dict()

    #Return the link
    return 'https://www.youtube.com' + result[0].get('url_suffix')
Example #13
0
def summarizing_video(chemical_compound):
    confirmation_video = ""
    summary = ''
    formatted_article_text = ''
    max_elements = 1
    #results=YoutubeSearch('Benzene',max_results=5).to_json()
    results = YoutubeSearch(chemical_compound,
                            max_results=max_elements).to_dict()

    #print(results)

    def validate_reply(confirmation_video):

        confirmation_verified = ''
        if confirmation_video == 'YES' or confirmation_video == 'NO':
            confirmation_verified = confirmation_video
            return confirmation_verified
        else:
            print('Please confirm that you want me to transcribe it?')
            confirmation_video = input('(yes/no):').upper()
            return validate_reply(confirmation_video)

    for i in range(max_elements):

        url = "https://www.youtube.com/watch?v=" + results[i]['id']
        title_video = results[i]['title']
        duration = results[i]['duration']
        views = results[i]['views']
        print('I found this video, do you want me to transcribe it?\n')
        print('****************')
        print("Title: ", title_video)
        print('Duration', duration)
        print("Url", url)
        print("Views", views)
        print("***************")
        confirmation_video = input('Transcribing video? (yes/no):').upper()
        confirmation_verified = validate_reply(confirmation_video)
        print('out', confirmation_verified)
        if confirmation_verified == 'YES':
            print('in', confirmation_verified)
            ydl_opts = {
                'format':
                'bestaudio/best',
                'postprocessors': [{
                    'key': 'FFmpegExtractAudio',
                    'preferredcodec': 'wav',
                    'preferredquality': '192',
                }],
            }
            with youtube_dl.YoutubeDL(ydl_opts) as ydl:
                ydl.download([url])
                info_dict = ydl.extract_info(url)
                fn = ydl.prepare_filename(info_dict)
                path = fn[:-4] + "wav"

            r = sr.Recognizer()
            print("started..")

            def get_large_audio_transcription(path):
                sound = AudioSegment.from_wav(path)
                chunks = split_on_silence(
                    sound,
                    min_silence_len=500,
                    silence_thresh=sound.dBFS - 14,
                    keep_silence=500,
                )
                folder_name = "audio-chunks"
                if not os.path.isdir(folder_name):
                    os.mkdir(folder_name)
                whole_text = ""
                for i, audio_chunk in enumerate(chunks, start=1):
                    chunk_filename = os.path.join(folder_name, f"chunk{i}.wav")
                    audio_chunk.export(chunk_filename, format="wav")
                    with sr.AudioFile(chunk_filename) as source:
                        audio_listened = r.record(source)

                        try:
                            text = r.recognize_google(audio_listened,
                                                      language="en-US")
                        except sr.UnknownValueError as e:
                            pass
                            #print("Error:",str(e))
                        else:
                            text = f"{text.capitalize()}. "
                            #print(chunk_filename,":",text)
                            whole_text += text

                return whole_text

            # (starting here:)#path="Audacity FFMpeg codec install for Windows-v2J6fT65Ydc.wav"
            #print("\nFull text:",get_large_audio_transcription(path))
            article_text = get_large_audio_transcription(path)

            article_text = re.sub(r'\[[0-9]*\]', ' ', article_text)
            article_text = re.sub(r'\s+', ' ', article_text)

            formatted_article_text = re.sub('^a-zA-Z', ' ', article_text)
            formatted_article_text = re.sub(r'\s+', ' ',
                                            formatted_article_text)

            #print(formatted_article_text)  #final text from audio

            print('*********************')
            print("Summaryzing..")
            #tokenization
            sentence_list = nltk.sent_tokenize(article_text)

            stopwords = nltk.corpus.stopwords.words('english')
            word_frequencies = {}
            for word in nltk.word_tokenize(formatted_article_text):
                if word not in stopwords:
                    if word not in word_frequencies.keys():
                        word_frequencies[word] = 1
                    else:
                        word_frequencies[word] += 1

            #print(list(map(str,word_frequencies)))

            #word frequency
            maximum_frequency = max(word_frequencies.values())
            for word in word_frequencies.keys():
                word_frequencies[word] = (word_frequencies[word] /
                                          maximum_frequency)

            #print(word_frequencies)

            #sentence score
            sentence_scores = {}
            for sent in sentence_list:
                for word in nltk.word_tokenize(sent.lower()):
                    if word in word_frequencies.keys():
                        if len(sent.split(' ')) < 50:
                            if sent not in sentence_scores.keys():
                                sentence_scores[sent] = word_frequencies[word]
                            else:
                                sentence_scores[sent] += word_frequencies[word]

            #top 7 most frequent sentences
            summary_sentences = heapq.nlargest(10,
                                               sentence_scores,
                                               key=sentence_scores.get)
            summary = ' '.join(summary_sentences)

    return (summary, formatted_article_text)
Example #14
0
def get_id(r):
    return (json.loads(YoutubeSearch(
        r, max_results=1).to_json())['videos'][0]['id'])
Example #15
0
async def lol_cb(b, cb):
    global que

    cbd = cb.data.strip()
    chat_id = cb.message.chat.id
    typed_ = cbd.split(None, 1)[1]
    # useer_id = cb.message.reply_to_message.from_user.id
    try:
        x, query, useer_id = typed_.split("|")
    except:
        await cb.message.edit("Song Not Found")
        return
    useer_id = int(useer_id)
    if cb.from_user.id != useer_id:
        await cb.answer("You ain't the person who requested to play the song!",
                        show_alert=True)
        return
    await cb.message.edit("Hang On... Player Starting")
    x = int(x)
    try:
        useer_name = cb.message.reply_to_message.from_user.first_name
    except:
        useer_name = cb.message.from_user.first_name

    results = YoutubeSearch(query, max_results=5).to_dict()
    resultss = results[x]["url_suffix"]
    title = results[x]["title"][:40]
    thumbnail = results[x]["thumbnails"][0]
    duration = results[x]["duration"]
    views = results[x]["views"]
    url = f"https://youtube.com{resultss}"

    try:
        secmul, dur, dur_arr = 1, 0, duration.split(":")
        for i in range(len(dur_arr) - 1, -1, -1):
            dur += int(dur_arr[i]) * secmul
            secmul *= 60
        if (dur / 60) > DURATION_LIMIT:
            await cb.message.edit(
                f"Music longer than {DURATION_LIMIT}min are not allowed to play"
            )
            return
    except:
        pass
    try:
        thumb_name = f"thumb{title}.jpg"
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, "wb").write(thumb.content)
    except Exception as e:
        print(e)
        return
    dlurl = url
    dlurl = dlurl.replace("youtube", "youtubepp")
    keyboard = InlineKeyboardMarkup([
        [
            InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
            InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
        ],
        [
            InlineKeyboardButton(text="🎬 YouTube", url=f"{url}"),
            InlineKeyboardButton(text="Download 📥", url=f"{dlurl}"),
        ],
        [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
    ])
    requested_by = useer_name
    await generate_cover(requested_by, title, views, duration, thumbnail)
    file = await convert(youtube.download(url))
    if chat_id in callsmusic.active_chats:
        position = await queues.put(chat_id, file=file)
        qeue = que.get(chat_id)
        s_name = title
        try:
            r_by = cb.message.reply_to_message.from_user
        except:
            r_by = cb.message.from_user
        loc = file
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await cb.message.delete()
        await b.send_photo(
            chat_id,
            photo="final.png",
            caption=
            f"#⃣  Song requested by {r_by.mention()} <b>queued</b> at position {position}!",
            reply_markup=keyboard,
        )
        os.remove("final.png")

    else:
        que[chat_id] = []
        qeue = que.get(chat_id)
        s_name = title
        try:
            r_by = cb.message.reply_to_message.from_user
        except:
            r_by = cb.message.from_user
        loc = file
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)

        await callsmusic.set_stream(chat_id, file)
        await cb.message.delete()
        await b.send_photo(
            chat_id,
            photo="final.png",
            reply_markup=keyboard,
            caption=
            f"▶️ <b>Playing</b> here the song requested by {r_by.mention()} via Youtube Music 😎",
        )
        os.remove("final.png")
Example #16
0
def ytb_search(term):
    res = YoutubeSearch(term, max_results=10).to_json()
    return (res)
Example #17
0
async def play(_, message: Message):
    global que
    global useer
    if message.chat.id in DISABLED_GROUPS:
        return
    lel = await message.reply("🔄 <b>Processing</b>")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id

    try:
        user = await USER.get_me()
    except:
        user.first_name = "helper"
    usar = user
    wew = usar.id
    try:
        # chatdetails = await USER.get_chat(chid)
        await _.get_chat_member(chid, wew)
    except:
        for administrator in administrators:
            if administrator == message.from_user.id:
                if message.chat.title.startswith("Channel Music: "):
                    await lel.edit(
                        "<b>Remember to add helper to your channel</b>", )
                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>Add me as admin of yor group first</b>", )
                    return

                try:
                    await USER.join_chat(invitelink)
                    await USER.send_message(
                        message.chat.id,
                        "I joined this group for playing music in VC")
                    await lel.edit("<b>helper userbot joined your chat</b>", )

                except UserAlreadyParticipant:
                    pass
                except Exception:
                    # print(e)
                    await lel.edit(
                        f"<b>🔴 Flood Wait Error 🔴 \nUser {user.first_name} couldn't join your group due to heavy requests for userbot! Make sure user is not banned in group."
                        "\n\nOr manually add assistant to your Group and try again</b>",
                    )
    try:
        await USER.get_chat(chid)
        # lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i> {user.first_name} Userbot not in this chat, Ask admin to send /play command for first time or add {user.first_name} manually</i>"
        )
        return
    text_links = None
    await lel.edit("🔎 <b>Finding</b>")
    if message.reply_to_message:
        if message.reply_to_message.audio:
            pass
        entities = []
        if message.entities:
            entities += entities
        elif message.caption_entities:
            entities += message.caption_entities
        if message.reply_to_message:
            text = message.reply_to_message.text \
                or message.reply_to_message.caption
            if message.reply_to_message.entities:
                entities = message.reply_to_message.entities + entities
            elif message.reply_to_message.caption_entities:
                entities = message.reply_to_message.entities + entities
        else:
            text = message.text or message.caption

        urls = [entity for entity in entities if entity.type == 'url']
        text_links = [
            entity for entity in entities if entity.type == 'text_link'
        ]
    else:
        urls = None
    if text_links:
        urls = True
    user_id = message.from_user.id
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"
    audio = ((message.reply_to_message.audio or message.reply_to_message.voice)
             if message.reply_to_message else None)
    if audio:
        if round(audio.duration / 60) > DURATION_LIMIT:
            await lel.edit(
                f"❌ Videos longer than {DURATION_LIMIT} minute(s) aren't allowed to play!"
            )
            return
        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
            ],
            [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
        ])
        file_name = get_file_name(audio)
        title = file_name
        thumb_name = "https://telegra.ph/file/f6086f8909fbfeb0844f2.png"
        thumbnail = thumb_name
        duration = round(audio.duration / 60)
        views = "Locally added"
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file = await convert((
            await message.reply_to_message.download(file_name)
        ) if not path.isfile(path.join("downloads", file_name)) else file_name)
    elif urls:
        query = toxt
        await lel.edit("🎵 <b>Processing</b>")
        ydl_opts = {"format": "bestaudio/best"}
        try:
            results = YoutubeSearch(query, max_results=1).to_dict()
            url = f"https://youtube.com{results[0]['url_suffix']}"
            # print(results)
            title = results[0]["title"][:40]
            thumbnail = results[0]["thumbnails"][0]
            thumb_name = f"thumb{title}.jpg"
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, "wb").write(thumb.content)
            duration = results[0]["duration"]
            results[0]["url_suffix"]
            views = results[0]["views"]

        except Exception as e:
            await lel.edit(
                "Song not found.Try another song or maybe spell it properly.")
            print(str(e))
            return
        try:
            secmul, dur, dur_arr = 1, 0, duration.split(":")
            for i in range(len(dur_arr) - 1, -1, -1):
                dur += int(dur_arr[i]) * secmul
                secmul *= 60
            if (dur / 60) > DURATION_LIMIT:
                await lel.edit(
                    f"❌ Videos longer than {DURATION_LIMIT} minutes aren't allowed to play!"
                )
                return
        except:
            pass
        dlurl = url
        dlurl = dlurl.replace("youtube", "youtubepp")
        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
            ],
            [
                InlineKeyboardButton(text="🎬 YouTube", url=f"{url}"),
                InlineKeyboardButton(text="Download 📥", url=f"{dlurl}"),
            ],
            [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
        ])
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file = await convert(youtube.download(url))
    else:
        query = ""
        for i in message.command[1:]:
            query += " " + str(i)
        print(query)
        await lel.edit("🎵 **Processing**")
        ydl_opts = {"format": "bestaudio/best"}

        try:
            results = YoutubeSearch(query, max_results=5).to_dict()
        except:
            await lel.edit("Give me something to play")
        # Looks like hell. Aren't it?? F**K OFF
        try:
            toxxt = "**Select the song you want to play**\n\n"
            j = 0
            useer = user_name
            emojilist = [
                "1️⃣",
                "2️⃣",
                "3️⃣",
                "4️⃣",
                "5️⃣",
            ]

            while j < 5:
                toxxt += f"{emojilist[j]} <b>Title - [{results[j]['title']}](https://youtube.com{results[j]['url_suffix']})</b>\n"
                toxxt += f" ╚ <b>Duration</b> - {results[j]['duration']}\n"
                toxxt += f" ╚ <b>Views</b> - {results[j]['views']}\n"
                toxxt += f" ╚ <b>Channel</b> - {results[j]['channel']}\n\n"

                j += 1
            koyboard = InlineKeyboardMarkup([
                [
                    InlineKeyboardButton(
                        "1️⃣", callback_data=f"plll 0|{query}|{user_id}"),
                    InlineKeyboardButton(
                        "2️⃣", callback_data=f"plll 1|{query}|{user_id}"),
                    InlineKeyboardButton(
                        "3️⃣", callback_data=f"plll 2|{query}|{user_id}"),
                ],
                [
                    InlineKeyboardButton(
                        "4️⃣", callback_data=f"plll 3|{query}|{user_id}"),
                    InlineKeyboardButton(
                        "5️⃣", callback_data=f"plll 4|{query}|{user_id}"),
                ],
                [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
            ])
            await lel.edit(toxxt,
                           reply_markup=koyboard,
                           disable_web_page_preview=True)
            # WHY PEOPLE ALWAYS LOVE P**N ?? (A point to think)
            return
            # Returning to pornhub
        except:
            await lel.edit(
                "No Enough results to choose.. Starting direct play..")

            # print(results)
            try:
                url = f"https://youtube.com{results[0]['url_suffix']}"
                title = results[0]["title"][:40]
                thumbnail = results[0]["thumbnails"][0]
                thumb_name = f"thumb{title}.jpg"
                thumb = requests.get(thumbnail, allow_redirects=True)
                open(thumb_name, "wb").write(thumb.content)
                duration = results[0]["duration"]
                results[0]["url_suffix"]
                views = results[0]["views"]

            except Exception as e:
                await lel.edit(
                    "Song not found.Try another song or maybe spell it properly."
                )
                print(str(e))
                return
            try:
                secmul, dur, dur_arr = 1, 0, duration.split(":")
                for i in range(len(dur_arr) - 1, -1, -1):
                    dur += int(dur_arr[i]) * secmul
                    secmul *= 60
                if (dur / 60) > DURATION_LIMIT:
                    await lel.edit(
                        f"❌ Videos longer than {DURATION_LIMIT} minutes aren't allowed to play!"
                    )
                    return
            except:
                pass
            dlurl = url
            dlurl = dlurl.replace("youtube", "youtubepp")
            keyboard = InlineKeyboardMarkup([
                [
                    InlineKeyboardButton("📖 Playlist",
                                         callback_data="playlist"),
                    InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
                ],
                [
                    InlineKeyboardButton(text="🎬 YouTube", url=f"{url}"),
                    InlineKeyboardButton(text="Download 📥", url=f"{dlurl}"),
                ],
                [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
            ])
            requested_by = message.from_user.first_name
            await generate_cover(requested_by, title, views, duration,
                                 thumbnail)
            file = await convert(youtube.download(url))
    chat_id = get_chat_id(message.chat)
    if chat_id in callsmusic.active_chats:
        position = await queues.put(chat_id, file=file)
        qeue = que.get(chat_id)
        s_name = title
        r_by = message.from_user
        loc = file
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await message.reply_photo(
            photo="final.png",
            caption=
            f"#⃣ Your requested song <b>queued</b> at position {position}!",
            reply_markup=keyboard,
        )
        os.remove("final.png")
        return await lel.delete()
    else:
        chat_id = get_chat_id(message.chat)
        que[chat_id] = []
        qeue = que.get(chat_id)
        s_name = title
        r_by = message.from_user
        loc = file
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        try:
            await callsmusic.set_stream(chat_id, file)
        except:
            message.reply("Group Call is not connected or I can't join it")
            return
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption=
            "▶️ <b>Playing</b> here the song requested by {} via Youtube Music 😎"
            .format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
Example #18
0
async def play(_, message: Message):
    global que
    lel = await message.reply("🔄 **Processing**")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id

    try:
        user = await USER.get_me()
    except:
        user.first_name = "helper"
    usar = user
    wew = usar.id
    try:
        # chatdetails = await USER.get_chat(chid)
        await _.get_chat_member(chid, wew)
    except:
        for administrator in administrators:
            if administrator == message.from_user.id:
                if message.chat.title.startswith("Channel Music: "):
                    await lel.edit(
                        "<b>Remember to add helper to your channel</b>", )
                    pass
                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>Add me as admin of yor group first</b>", )
                    return

                try:
                    await USER.join_chat(invitelink)
                    await USER.send_message(
                        message.chat.id,
                        "I joined this group for playing music in VC")
                    await lel.edit("<b>helper userbot joined your chat</b>", )

                except UserAlreadyParticipant:
                    pass
                except Exception:
                    # print(e)
                    await lel.edit(
                        f"<b>🔴 Flood Wait Error 🔴 \nUser {user.first_name} couldn't join your group due to heavy requests for userbot! Make sure user is not banned in group."
                        "\n\nOr manually add assistant to your Group and try again</b>",
                    )
    try:
        await USER.get_chat(chid)
        # lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i> {user.first_name} Userbot not in this chat, Ask admin to send /play command for first time or add {user.first_name} manually</i>"
        )
        return
    message.from_user.id
    message.from_user.first_name
    text_links = None
    await lel.edit("🔎 **Finding**")
    message.from_user.id
    if message.reply_to_message:
        entities = []
        toxt = message.reply_to_message.text or message.reply_to_message.caption
        if message.reply_to_message.entities:
            entities = message.reply_to_message.entities + entities
        elif message.reply_to_message.caption_entities:
            entities = message.reply_to_message.entities + entities
        urls = [entity for entity in entities if entity.type == 'url']
        text_links = [
            entity for entity in entities if entity.type == 'text_link'
        ]
    else:
        urls = None
    if text_links:
        urls = True
    user_id = message.from_user.id
    message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"
    audio = ((message.reply_to_message.audio or message.reply_to_message.voice)
             if message.reply_to_message else None)
    if audio:
        if round(audio.duration / 60) > DURATION_LIMIT:
            raise DurationLimitError(
                f"❌ Videos longer than {DURATION_LIMIT} minute(s) aren't allowed to play!"
            )
        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
            ],
            [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
        ])
        file_name = get_file_name(audio)
        title = file_name
        thumb_name = "https://telegra.ph/file/f6086f8909fbfeb0844f2.png"
        thumbnail = thumb_name
        duration = round(audio.duration / 60)
        views = "Locally added"
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await convert((
            await message.reply_to_message.download(file_name)
        ) if not path.isfile(path.join("downloads", file_name)) else file_name)
    elif urls:
        query = toxt
        await lel.edit("🎵 **Processing**")
        ydl_opts = {"format": "bestaudio[ext=m4a]"}
        try:
            results = YoutubeSearch(query, max_results=1).to_dict()
            url = f"https://youtube.com{results[0]['url_suffix']}"
            # print(results)
            title = results[0]["title"][:40]
            thumbnail = results[0]["thumbnails"][0]
            thumb_name = f"thumb{title}.jpg"
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, "wb").write(thumb.content)
            duration = results[0]["duration"]
            results[0]["url_suffix"]
            views = results[0]["views"]

        except Exception as e:
            await lel.edit(
                "Song not found.Try another song or maybe spell it properly.")
            print(str(e))
            return
        dlurl = url
        dlurl = dlurl.replace("youtube", "youtubepp")
        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
            ],
            [
                InlineKeyboardButton(text="🎬 YouTube", url=f"{url}"),
                InlineKeyboardButton(text="Download 📥", url=f"{dlurl}"),
            ],
            [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
        ])
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await convert(youtube.download(url))
    else:
        query = ""
        for i in message.command[1:]:
            query += " " + str(i)
        print(query)
        await lel.edit("🎵 **Processing**")
        ydl_opts = {"format": "bestaudio[ext=m4a]"}
        try:
            results = YoutubeSearch(query, max_results=1).to_dict()
            url = f"https://youtube.com{results[0]['url_suffix']}"
            # print(results)
            title = results[0]["title"][:40]
            thumbnail = results[0]["thumbnails"][0]
            thumb_name = f"thumb{title}.jpg"
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, "wb").write(thumb.content)
            duration = results[0]["duration"]
            results[0]["url_suffix"]
            views = results[0]["views"]

        except Exception as e:
            await lel.edit(
                "Song not found.Try another song or maybe spell it properly.")
            print(str(e))
            return
        dlurl = url
        dlurl = dlurl.replace("youtube", "youtubepp")
        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
            ],
            [
                InlineKeyboardButton(text="🎬 YouTube", url=f"{url}"),
                InlineKeyboardButton(text="Download 📥", url=f"{dlurl}"),
            ],
            [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
        ])
        requested_by = message.from_user.first_name
        await generate_cover(requested_by, title, views, duration, thumbnail)
        file_path = await convert(youtube.download(url))
    chat_id = get_chat_id(message.chat)
    if chat_id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(chat_id, file=file_path)
        qeue = que.get(chat_id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await message.reply_photo(
            photo="final.png",
            caption=
            f"#⃣ Your requested song **queued** at position {position}!",
            reply_markup=keyboard,
        )
        os.remove("final.png")
        return await lel.delete()
    else:
        chat_id = get_chat_id(message.chat)
        que[chat_id] = []
        qeue = que.get(chat_id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        try:
            callsmusic.pytgcalls.join_group_call(chat_id, file_path)
        except:
            message.reply("Group Call is not connected or I can't join it")
            return
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption=
            "▶️ **Playing** here the song requested by {} via Youtube Music 😜".
            format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
def open_youtube_song(song_name):
    results = YoutubeSearch(song_name, max_results=1).to_dict()
    url = "https://www.youtube.com/" + results[0]['url_suffix']
    webbrowser.open(url)
Example #20
0
async def inline_id_handler(event: events.InlineQuery.Event):
    o = await all_pro_s(Config, client1, client2, client3)
    builder = event.builder
    if event.query.user_id not in o:
        resultm = builder.article(
            title="Not Allowded",
            text=
            f"You Can't Use This Bot. \nDeploy WhiteEyeUserBot To Get Your Own Assistant, Deploy Link [Here](https://whiteeye-org.github.io/WhiteEyeUserBot/)",
        )
        await event.answer([resultm])
        return
    testinput = event.pattern_match.group(1)
    urllib.parse.quote_plus(testinput)
    results = []
    moi = YoutubeSearch(testinput, max_results=9).to_dict()
    if not moi:
        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 moon in moi:
        hmm = moon["id"]
        mo = f"https://www.youtube.com/watch?v={hmm}"
        kek = f"https://www.youtube.com/watch?v={hmm}"
        stark_name = moon["title"]
        stark_chnnl = moon["channel"]
        total_stark = moon["duration"]
        stark_views = moon["views"]
        moon["long_desc"]
        kekme = f"https://img.youtube.com/vi/{hmm}/hqdefault.jpg"
        okayz = f"**Title :** `{stark_name}` \n**Link :** `{kek}` \n**Channel :** `{stark_chnnl}` \n**Views :** `{stark_views}` \n**Duration :** `{total_stark}`"
        hmmkek = f"Video Name : {stark_name} \nChannel : {stark_chnnl} \nDuration : {total_stark} \nViews : {stark_views}"
        results.append(await event.builder.document(
            file=kekme,
            title=stark_name,
            description=hmmkek,
            text=okayz,
            include_media=True,
            buttons=[
                [
                    custom.Button.inline("Download Video - mp4",
                                         data=f"yt_vid_{mo}")
                ],
                [
                    custom.Button.inline("Download Audio - mp3",
                                         data=f"yt_dla_{mo}")
                ],
                [
                    Button.switch_inline("Search Again",
                                         query="yt ",
                                         same_peer=True)
                ],
            ],
        ))
    await event.answer(results)
Example #21
0
async def ytplay(_, message: Message):
    global blacks
    global is_playing
    global current_player
    global s
    global m
    global d

    if message.from_user.id in blacks:
        await message.reply_text("You're Blacklisted, So Stop Spamming.")
        return
    elif is_playing:
        list_of_admins = await getadmins(message.chat.id)
        if message.from_user.id in list_of_admins:
            pass
        else:
            d = await message.reply_text(
                text="stop interrupting while others playing!",
                disable_notification=True)
            await asyncio.sleep(2)  # 2 sec delay before deletion
            await d.delete()
            await message.delete()
            return

    elif len(message.command) < 2:
        await message.reply_text("/youtube requires one argument")
        return
    try:
        await message.delete()
    except:
        pass
    try:
        await m.delete()
    except:
        pass
    try:
        os.system(f"{kill} mpv")
    except:
        pass
    try:
        os.remove("audio.webm")
    except:
        pass
    ydl_opts = {"format": "bestaudio"}
    query = kwairi(message)
    current_player = message.from_user.id
    is_playing = True

    m = await message.reply_text(f"Searching for `{query}`on YouTube")
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
    except Exception as e:
        await m.edit(str(e))
        return
    link = f"https://youtube.com{results[0]['url_suffix']}"
    title = results[0]["title"]
    thumbnail = results[0]["thumbnails"][0]
    duration = results[0]["duration"]
    views = results[0]["views"]
    await m.edit("Processing Thumbnail.")
    async with aiohttp.ClientSession() as session:
        async with session.get(thumbnail) as resp:
            if resp.status == 200:
                f = await aiofiles.open("background.png", mode="wb")
                await f.write(await resp.read())
                await f.close()

    image1 = Image.open("./background.png")
    image2 = Image.open("etc/foreground.png")
    image3 = changeImageSize(1280, 720, image1)
    image4 = changeImageSize(1280, 720, image2)
    image5 = image3.convert("RGBA")
    image6 = image4.convert("RGBA")
    Image.alpha_composite(image5, image6).save("temp.png")
    img = Image.open("temp.png")
    draw = ImageDraw.Draw(img)
    font = ImageFont.truetype("etc/font.otf", 32)
    draw.text((190, 550), f"Title: {title}", (255, 255, 255), font=font)
    draw.text((190, 590), f"Duration: {duration}", (255, 255, 255), font=font)
    draw.text((190, 630), f"Views: {views}", (255, 255, 255), font=font)
    draw.text(
        (190, 670),
        f"Played By: {message.from_user.first_name}",
        (255, 255, 255),
        font=font,
    )
    img.save("final.png")
    os.remove("temp.png")
    os.remove("background.png")
    await m.edit("Downloading Music.")
    with youtube_dl.YoutubeDL(ydl_opts) as ydl:
        info_dict = ydl.extract_info(link, download=False)
        audio_file = ydl.prepare_filename(info_dict)
        ydl.process_info(info_dict)
        os.rename(audio_file, "audio.webm")
    await m.delete()
    m = await message.reply_photo(
        caption=
        f"Playing [{title}]({link}) Via YouTube #music\nRequested by {message.from_user.first_name}",
        photo="final.png",
        reply_markup=InlineKeyboardMarkup(
            [[InlineKeyboardButton("STOP", callback_data="end")]]),
        parse_mode="markdown",
    )
    os.remove("final.png")
    s = await asyncio.create_subprocess_shell(
        "mpv audio.webm --no-video",
        stdout=asyncio.subprocess.PIPE,
        stderr=asyncio.subprocess.PIPE,
    )
    await s.wait()
    await m.delete()
    is_playing = False
Example #22
0
def search(term, max=10):
    results = YoutubeSearch(search_terms=term, max_results=int(max)).to_dict()
    return results
Example #23
0
async def play(_, message: Message):
    global que
    lel = await message.reply("🔄 **Processing**")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id

    try:
        user = await USER.get_me()
    except:
        user.first_name = "helper"
    usar = user
    wew = usar.id
    try:
        #chatdetails = await USER.get_chat(chid)
        lmoa = await _.get_chat_member(chid, wew)
    except:
        for administrator in administrators:
            if administrator == message.from_user.id:
                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>Jadikan Saya Menjadi Admin Terlebih Dahulu.</b>", )
                    return

                try:
                    await USER.join_chat(invitelink)
                    await USER.send_message(
                        message.chat.id,
                        "Saya Bergabung Dengan Group ini Untuk Memainkan Musik di VCG."
                    )
                    await lel.edit(
                        "<b>Robot Telah Bergabung Kedalam Group.</b>", )

                except UserAlreadyParticipant:
                    pass
                except Exception as e:
                    #print(e)
                    await lel.edit(
                        f"<b>❌ Flood Wait Error ❌ \n {user.first_name} Tidak Dapat Bergabung Dengan Grup Anda Karena Banyaknya Permintaan Untuk Assistant Saya. Pastikan @AssistantMusicVCGRobot Tidak Dilarang Didalam Group."
                        "\n\nAtau Tambahkan @AssistantMusicVCGRobot ke Grup Anda Secara Manual dan Coba Lagi.</b>",
                    )
                    pass
    try:
        chatdetails = await USER.get_chat(chid)
        #lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i> {user.first_name} Sedang Tidak Dalam Obrolan Ini, Minta Kepada Admin Untuk Menekan » /joingroup Untuk Pertama Kalinya atau Tambahkan {user.first_name} Secara Manual.</i>"
        )
        return
    sender_id = message.from_user.id
    sender_name = message.from_user.first_name
    await lel.edit("🔎 **Finding**")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    print(query)
    await lel.edit("🎵 **Processing**")
    ydl_opts = {
        "format": "bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best"
    }
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        url = f"https://youtube.com{results[0]['url_suffix']}"
        #print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f'thumb{title}.jpg'
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, 'wb').write(thumb.content)
        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        await lel.edit(
            "Lagu Tidak Ditemukan. Coba Lagu Lain atau Coba Mengeja Judul Lagu Dengan Benar."
        )
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup(
        [[
            InlineKeyboardButton('📖 Playlist', callback_data='playlist'),
            InlineKeyboardButton('Menu ⏯ ', callback_data='menu')
        ], [InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")],
         [InlineKeyboardButton("• Info Help •", url="t.me/InfoMusicRobot/10")],
         [InlineKeyboardButton(text="❌ Close", callback_data='cls')]])
    requested_by = message.from_user.first_name
    await generate_cover(requested_by, title, views, duration, thumbnail)
    file_path = await converter.convert(youtube.download(url))

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await message.reply_photo(
            photo="final.png",
            caption=
            f"#⃣ Lagu yang Anda Minta **Sedang Antri** di Posisi **{position}**",
            reply_markup=keyboard)
        os.remove("final.png")
        return await lel.delete()
    else:
        chat_id = message.chat.id
        que[chat_id] = []
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption="▶️ **Sedang Memutar.**\n\n Lagu Permintaan Dari {}".
            format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
Example #24
0
def a(client, message):
    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    print(query)
    m = message.reply('🔎 Searching the song...')
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = []
        count = 0
        while len(results) == 0 and count < 6:
            if count > 0:
                time.sleep(1)
            results = YoutubeSearch(query, max_results=1).to_dict()
            count += 1
        # results = YoutubeSearch(query, max_results=1).to_dict()
        try:
            link = f"https://youtube.com{results[0]['url_suffix']}"
            # print(results)
            title = results[0]["title"]
            thumbnail = results[0]["thumbnails"][0]
            duration = results[0]["duration"]

            ## UNCOMMENT THIS IF YOU WANT A LIMIT ON DURATION. CHANGE 1800 TO YOUR OWN PREFFERED DURATION AND EDIT THE MESSAGE (30 minutes cap) LIMIT IN SECONDS
            # if time_to_seconds(duration) >= 1800:  # duration limit
            #     m.edit("Exceeded 30mins cap")
            #     return

            views = results[0]["views"]
            thumb_name = f'thumb{message.message_id}.jpg'
            thumb = requests.get(thumbnail, allow_redirects=True)
            open(thumb_name, 'wb').write(thumb.content)

        except Exception as e:
            print(e)
            m.edit('Found nothing. Try changing the spelling a little.')
            return
    except Exception as e:
        m.edit(
            "✖️ Found Nothing. Sorry.\n\nTry another keywork or maybe spell it properly."
        )
        print(str(e))
        return
    m.edit("⏬ Downloading.")
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(link, download=False)
            audio_file = ydl.prepare_filename(info_dict)
            ydl.process_info(info_dict)
        rep = f'🎧 **Title**: [{title[:35]}]({link})\n⏳ **Duration**: `{duration}`\n👁‍🗨 **Views**: `{views}`'
        secmul, dur, dur_arr = 1, 0, duration.split(':')
        for i in range(len(dur_arr) - 1, -1, -1):
            dur += (int(dur_arr[i]) * secmul)
            secmul *= 60
        message.reply_audio(audio_file,
                            caption=rep,
                            parse_mode='md',
                            quote=False,
                            title=title,
                            duration=dur,
                            thumb=thumb_name)
        m.delete()
    except Exception as e:
        m.edit('❌ Error')
        print(e)
    try:
        os.remove(audio_file)
        os.remove(thumb_name)
    except Exception as e:
        print(e)
Example #25
0
async def play(_, message: Message):

    lel = await message.reply(f"**{bn} :-** 🔎 Finding song...")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    print(query)
    await lel.edit(f"**{bn} :-** 🎵 Processing {query}")
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        url = f"https://youtube.com{results[0]['url_suffix']}"
        #print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f'thumb{title}.jpg'
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, 'wb').write(thumb.content)

        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        lel.edit(
            f"**{bn} :-** ❌ Song not found.\nTry another song or maybe try to spell it properly."
        )
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup(
        [[InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")]])

    keyboard2 = InlineKeyboardMarkup(
        [[InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")]])

    audio = (message.reply_to_message.audio or message.reply_to_message.voice
             ) if message.reply_to_message else None

    if audio:
        await lel.edit_text(f"**{bn} :-** Hehe 🥴")

    elif url:
        file_path = await converter.convert(youtube.download(url))
    else:
        return await lel.edit_text(
            f"**{bn} :-** ❗ You did not give me anything to play!")

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        await message.reply_photo(
            photo=thumb_name,
            caption=
            f"**{bn} :-** Your requested song is **queued** at position #{position} !",
            reply_markup=keyboard2)
        return await lel.delete()
    else:
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo=thumb_name,
            reply_markup=keyboard,
            caption="▶️ **Playing** here the song requested by {}".format(
                message.from_user.mention()),
        )
        return await lel.delete()
Example #26
0
async def play(_, message: Message):
    global que
    lel = await message.reply("🔄 **Sedang Memproses Lagu-mu!**")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id

    try:
        user = await USER.get_me()
    except:
        user.first_name = "helper"
    usar = user
    wew = usar.id
    try:
        #chatdetails = await USER.get_chat(chid)
        lmoa = await _.get_chat_member(chid, wew)
    except:
        for administrator in administrators:
            if administrator == message.from_user.id:
                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>Tambahkan saya sebagai admin grup Anda terlebih dahulu</b>",
                    )
                    return

                try:
                    await USER.join_chat(invitelink)
                    await USER.send_message(
                        message.chat.id,
                        "Saya bergabung dengan grup ini untuk memainkan musik di VCG"
                    )
                    await lel.edit(
                        "<b>Assisten bot bergabung dengan obrolan Anda</b>", )

                except UserAlreadyParticipant:
                    pass
                except Exception as e:
                    #print(e)
                    await lel.edit(
                        f"<b>🔴 Flood Wait Error \nAssistant Bot tidak dapat bergabung dengan grup Anda karena banyaknya permintaan bergabung untuk bot! Pastikan pengguna tidak dibanned/blokir dalam grup."
                        "\n\nAtau tambahkan secara manual @assistencrystal ke Grup Anda dan coba lagi</b>",
                    )
                    pass
    try:
        chatdetails = await USER.get_chat(chid)
        #lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i> Assisten Bot tidak ada dalam grup ini, Minta admin untuk tambahkan Assistant Bot secara manual</i>"
        )
        return
    sender_id = message.from_user.id
    sender_name = message.from_user.first_name
    await lel.edit("🔎 **Sedang Mencari Lagu-mu!**")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    print(query)
    await lel.edit("🎵 **Sedang Memproses Lagu-mu!**")
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        url = f"https://youtube.com{results[0]['url_suffix']}"
        #print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f'thumb{title}.jpg'
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, 'wb').write(thumb.content)
        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        await lel.edit(
            "Lagu tidak ditemukan. Coba cari dengan judul lagu yang lebih jelas!"
        )
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton('🎶 Daftar Putar', callback_data='playlist'),
        InlineKeyboardButton("🍃 Dashboard", callback_data='menu')
    ], [InlineKeyboardButton("Owner", url="https://t.me/boyfriendnice")
        ], [InlineKeyboardButton(text="❌ Tutup!", callback_data='cls')]])
    requested_by = message.from_user.first_name
    await generate_cover(requested_by, title, views, duration, thumbnail)
    file_path = await converter.convert(youtube.download(url))

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await message.reply_photo(
            photo="final.png",
            caption=
            f"⚡ Lagu yang Kamu minta **Sedang Antri** di posisi {position}!",
            reply_markup=keyboard)
        os.remove("final.png")
        return await lel.delete()
    else:
        chat_id = message.chat.id
        que[chat_id] = []
        qeue = que.get(message.chat.id)
        s_name = title
        r_by = message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
        photo="final.png",
        reply_markup=keyboard,
        caption=f"🍃 **Judul Lagu :** {title}\n**⏱ Durasi Lagu :** {duration}\n" \
                + f"🌙 **Status Lagu :** Sedang Memutar Lagu-mu!\n🦇 **Permintaan By :** {requested_by}".format(
        message.from_user.mention()
        ),
        )
        os.remove("final.png")
        return await lel.delete()
Example #27
0
async def play(_, message: Message):

    lel = await message.reply(f"**{bn} :-** 🔎 Menemukan Lagu...")
    sender_id = message.from_user.id
    user_id = message.from_user.id
    sender_name = message.from_user.first_name
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

    query = ''
    for i in message.command[1:]:
        query += ' ' + str(i)
    print(query)
    await lel.edit(f"**{bn} :-** 🎵 Memproses {query}")
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        url = f"https://youtube.com{results[0]['url_suffix']}"
        #print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f'thumb{title}.jpg'
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, 'wb').write(thumb.content)

        duration = results[0]["duration"]
        url_suffix = results[0]["url_suffix"]
        views = results[0]["views"]

    except Exception as e:
        lel.edit(
            f"**{bn} :-** ❌ Lagu Tidak Ditemukan.\nCoba lagu lain atau mungkin coba mengejanya dengan benar."
        )
        print(str(e))
        return

    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton(text="INSTAGRAM",
                             url=f"https://instagram.com/ferikunn")
    ]])

    keyboard2 = InlineKeyboardMarkup([[
        InlineKeyboardButton(text="Channel", url=f"https://t.me/hanyabotferi")
    ]])

    audio = (message.reply_to_message.audio or message.reply_to_message.voice
             ) if message.reply_to_message else None

    if audio:
        await lel.edit_text(f"**{bn} :-** Hehe 🥴")

    elif url:
        file_path = await converter.convert(youtube.download(url))
    else:
        return await lel.edit_text(
            f"**{bn} :-** ❗ Anda tidak memberi saya apa pun untuk dimainkan!")

    if message.chat.id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(message.chat.id, file=file_path)
        await message.reply_photo(
            photo=thumb_name,
            caption=
            f"**{bn} :-** Lagu yang Anda minta adalah **queued** Di posisi #{position} !",
            reply_markup=keyboard2)
        return await lel.delete()
    else:
        callsmusic.pytgcalls.join_group_call(message.chat.id, file_path)
        await message.reply_photo(
            photo=thumb_name,
            reply_markup=keyboard,
            caption="▶️ **Memainkan** di sini lagu tersebut diminta oleh {}".
            format(message.from_user.mention()),
        )
        return await lel.delete()
Example #28
0
    def onMessage(self, room, user, message):
        log(room.name, None, "<{0}> {1}".format(user.name, message.body))

        if "lmaolover" == user.name.lower():
            return

        message_body_lower = message.body.lower()

        if "lmaolover" in message_body_lower:
            log("lmaolover", None,
                "[{0}] <{1}> {2}".format(room.name, user.name, message.body))

        lil_cnn = "lil" in message_body_lower and "cnn" in message_body_lower
        cnn_cnn_cnn = message_body_lower.split().count('cnn') >= 3

        link_matches = link_re.search(message.body)
        command_matches = command_re.search(message.body)
        yt_matches = yt_re.search(message.body)
        imdb_matches = imdb_re.search(message.body)
        twitter_matches = twitter_re.search(message.body)
        insta_matches = insta_re.search(message.body)
        other_links = [
            "worldstar", "dailymotion.com", "liveleak.com", "strawpoll.me",
            "open.spotify.com"
        ]
        other_image = ["worldstar"]
        other_link_matches = link_matches and any(
            link_type in link_matches.group(0) for link_type in other_links)
        other_image_matches = other_link_matches and any(
            link_type in link_matches.group(0) for link_type in other_image)
        propaganda_links = [
            "theepochtimes.com", "ntd.com", "revolver.news", "ntdtv.com",
            "ntdca.com", "75.126.16.248", "infowars.com", "rebelnews.com",
            "skynews.com.au"
        ]
        propaganda_link_matches = link_matches and any(
            link_type in link_matches.group(0)
            for link_type in propaganda_links)

        country_match = next(
            (country
             for country in countries if country in message_body_lower), None)

        if "@lmaolover" in message_body_lower:
            user_lower = user.name.lower()
            message_without_quote = re.sub(r"@lmaolover: `.*`", "",
                                           message_body_lower)

            apologies = ["sry", "sorry", "apolog", "forgive"]
            repentant = any(apol in message_without_quote
                            for apol in apologies)
            if repentant:
                self.room_message(room, "thank you friend", delay=2)

            rude_messages = [
                "kys", "get fukt", "shit bot", "f**k you", "f**k off",
                "f**k ur", "f**k up", "stfu"
            ]
            disrespected = any(rude in message_without_quote
                               for rude in rude_messages)
            rude_response = [
                "fix the @{} problem when", "back in yer cage @{}"
            ]
            if disrespected:
                self.room_message(room,
                                  random_selection(rude_response).format(
                                      user.name),
                                  delay=2)

        elif "lmao?" in message_body_lower:
            roger_messages = [
                "sup", "hey girl", "ayyyy", "Let's get this bread",
                "What you need?", "Yo waddup"
            ]
            self.room_message(room, random_selection(roger_messages))

        elif room.name in chat['balb'] + chat['dev'] and len(
                message_body_lower) > 299:
            self.room_message(room,
                              random_selection(["tl;dr", "spam"]),
                              delay=1)

        elif yt_matches:
            try:
                search = yt_matches.group(1)
                if len(search) > 0:
                    results = YoutubeSearch('"' + search + '"',
                                            max_results=1).videos
                    if len(results) > 0 and results[0]['id'] == search:
                        result = results[0]
                        yt_img = result['thumbnails'][0]
                        title = result['title']
                        the_link = "https://youtu.be{}".format(
                            result['url_suffix'])
                        self.room_message(room,
                                          "{}<br/> {}<br/> {}".format(
                                              yt_img, title, the_link),
                                          html=True)
                    else:
                        self.room_message(
                            room,
                            random_selection([
                                'FORBIDDEN video requested',
                                'Video BANNED in Euroland',
                                'Illicit material detected',
                                "I ain't clickin that shit"
                            ]))
                else:
                    pass
            except Exception as e:
                logError(room.name, "youtube", message.body, e)

        elif len(message_body_lower
                 ) > 2 and message_body_lower[0] == '?' and message_body_lower[
                     1] == '?' and message_body_lower[2] != '?':
            try:
                results = wolfram_client.query(message_body_lower[2:].strip())
                if results['@success']:
                    first_result = next(results.results, None)
                    if first_result:
                        self.room_message(room, first_result.text)
                    else:
                        pod_results = None
                        for pod in results.pods:
                            if pod.id == 'Results':
                                pod_results = pod
                                break
                        if pod_results:
                            self.room_message(room,
                                              pod_results.subpod.plaintext)
                        else:
                            self.room_message(
                                room,
                                random_selection([
                                    "AI can not compute", "AI stumped", "wot?",
                                    "is AI dum or you?",
                                    "um well ok maybe try again"
                                ]))
                else:
                    self.room_message(
                        room,
                        random_selection([
                            "AI can not compute", "AI stumped", "wot?",
                            "is AI dum or you?", "um well ok maybe try again"
                        ]))
            except Exception as e:
                logError(room.name, "wolframalpha", message.body, e)

        elif len(message_body_lower) > 1 and message_body_lower[
                0] == '?' and message_body_lower[1] != '?':
            try:
                search = message_body_lower[1:].strip()
                if len(search) > 0:
                    results = YoutubeSearch(search, max_results=1).videos
                    if len(results) > 0:
                        result = results[0]
                        yt_img = result['thumbnails'][0]
                        title = result['title']
                        the_link = "https://youtu.be{}".format(
                            result['url_suffix'])
                        self.room_message(room,
                                          "{}<br/> {}<br/> {}".format(
                                              yt_img, title, the_link),
                                          html=True)
                    else:
                        self.room_message(
                            room,
                            random_selection([
                                'dude wtf is this', 'nah dude no',
                                "nah we don't got that", 'sorry bro, try again'
                            ]))
                else:
                    pass
            except Exception as e:
                logError(room.name, "youtube-search", message.body, e)

        elif imdb_matches:
            try:
                video_id = imdb_matches.group(1)
                imdb_api = 'http://www.omdbapi.com/?apikey=cc41196e&i=' + video_id
                imdb_resp = requests.get(imdb_api, timeout=3)
                imdb_resp.raise_for_status()

                imdb_info = imdb_resp.json()
                poster = imdb_info['Poster']
                title = imdb_info['Title']
                year = imdb_info['Year']
                rating = imdb_info['imdbRating']
                plot = imdb_info['Plot']
                self.room_message(
                    room,
                    "{0}<br/> {1} ({2}) [{3}/10]<br/> <i>{4}</i>".format(
                        poster, title, year, rating, plot),
                    html=True)
                log(
                    room.name, "imdb",
                    "<{0}> {1}::{2}::{3}::{4}".format(user.name, video_id,
                                                      title, year, rating))
            except requests.exceptions.Timeout:
                self.room_message(room, "imdb ded")
            except requests.exceptions.HTTPError:
                self.room_message(room, "imdb ded")
            except Exception as e:
                logError(room.name, "imdb", message.body, e)

        elif twitter_matches:
            try:
                status_id = twitter_matches.group(1)
                tweet = tw_api.GetStatus(status_id, trim_user=True)
                desc = tweet.full_text
                img = ''
                if tweet.media:
                    img = next(media.media_url_https for media in tweet.media)
                if "satan" in desc.lower():
                    self.praise_jesus(room)
                else:
                    self.room_message(room,
                                      "{}<br/> {}".format(desc, img),
                                      html=True)
            except Exception as e:
                # just try again for connection error
                try:
                    status_id = twitter_matches.group(1)
                    tweet = tw_api.GetStatus(status_id, trim_user=True)
                    desc = tweet.full_text
                    img = ''
                    if tweet.media:
                        img = next(media.media_url for media in tweet.media)
                    if "satan" in desc.lower():
                        self.praise_jesus(room)
                    else:
                        self.room_message(room,
                                          "{}<br/> {}".format(desc, img),
                                          html=True)
                except Exception as e:
                    logError(room.name, "twitter", message.body, e)

        elif insta_matches:
            self.room_message(room, random_selection(memes['insta']))

        elif propaganda_link_matches and room.name in chat['mod']:
            try:
                the_link = link_matches.group(0)
                fetch = lassie().fetch(the_link, favicon=False)
                desc = fetch['title']
                img = ''
                if fetch['images']:
                    urls = (img['src'] for img in fetch['images'])
                    img = next(urls, '')
                room.deleteMessage(message)
                self.room_message(room,
                                  "{}<br/> {}<br/> {}".format(
                                      img, desc, the_link),
                                  html=True)
            except Exception as e:
                logError(room.name, "propaganda", message.body, e)

        elif other_image_matches:
            try:
                fetch = lassie().fetch(link_matches.group(0))
                desc = fetch['title']
                img = ''
                if fetch['images']:
                    urls = (img['src'] for img in fetch['images']
                            if 'type' in img and img['type'] == 'og:image')
                    img = next(urls, '')
                self.room_message(room,
                                  "{}<br/> {}".format(desc, img),
                                  html=True)
            except Exception as e:
                logError(room.name, "link_image", message.body, e)

        elif other_link_matches:
            try:
                the_link = link_matches.group(0)
                fetch = lassie().fetch(the_link)
                self.room_message(room, fetch['title'])
            except Exception as e:
                logError(room.name, "link", message.body, e)

        elif re.match("ay+ lmao", message_body_lower):
            self.room_message(room, random_selection(memes['lmao']))
        elif re.match(".*(?<![@a-zA-Z])clam.*", message_body_lower):
            self.room_message(room, random_selection(memes['clam']))

        elif command_matches:
            try:
                command = command_matches.group(0)
                self.room_message(room, stash_memes[command])
            except:
                pass

        elif "alex jones" in message_body_lower or "infowars" in message_body_lower:
            self.room_message(room, "https://lmao.love/infowars")
        elif "church" in message_body_lower or "satan" in message_body_lower:
            self.praise_jesus(room)
        elif "preach" in message_body_lower or "gospel" in message_body_lower:
            self.preach_the_gospel(room)
        elif "maga" in message_body_lower and "magazine" not in message_body_lower:
            self.room_message(room, random_selection(memes['trump']))
        elif "!whatson" in message_body_lower:
            self.room_message(room, "https://guide.lmao.love/")
        elif "!stash" in message_body_lower:
            meme = random_selection(stash_tuples)
            self.room_message(room,
                              "{}<br/> {}".format(meme[0], meme[1]),
                              html=True)
        elif "stash" in message_body_lower:
            self.room_message(room, random_selection(memes['stash']))
        elif "!jameis" in message_body_lower or "!winston" in message_body_lower:
            self.room_message(room, "https://i.imgur.com/vyrNpSm.png")
        elif "!phins" in message_body_lower:
            self.room_message(
                room,
                "https://giphygifs.s3.amazonaws.com/media/Px2Zu55ofxfO0/giphy.gif"
            )
        elif "!spike" in message_body_lower:
            self.room_message(room, "https://xvsvc.net/emotes/1smoke.gif")
        elif "tyson" in message_body_lower:
            self.room_message(room, random_selection(memes['tyson']))
        elif "pika" in message_body_lower:
            self.room_message(room, "https://i.imgur.com/dZxHsel.png")
        elif "propaganda" in message_body_lower:
            self.room_message(room, random_selection(memes['korea']))
        elif "xmas" in message_body_lower or "christmas" in message_body_lower:
            self.room_message(room, random_selection(memes['santa']))
        elif "shkreli" in message_body_lower:
            self.room_message(room, random_selection(memes['shkreli']))
        elif "jumanji" in message_body_lower:
            self.room_message(room, random_selection(memes['jumanji']))
        elif "devil?" in message_body_lower:
            self.room_message(room, "https://i.imgur.com/kz3joDl.jpg")
        elif "go2bed" in message_body_lower:
            self.room_message(room, "https://i.imgur.com/hpZ64Zk.jpg")
        elif "ronaldo" in message_body_lower or "rolando" in message_body_lower or "penaldo" in message_body_lower:
            self.room_message(room, random_selection(memes['ronaldo']))
        elif "!tv" in message_body_lower:
            if country_match:
                country_code = countries[country_match]
                country_name = country_match.title()
                self.room_message(room,
                                  "{} TV<br/> https://lmao.love/{}/".format(
                                      country_name, country_code),
                                  html=True,
                                  delay=1)
            else:
                self.room_message(room, "https://lmao.love")
        elif lil_cnn or cnn_cnn_cnn:
            self.room_message(room, random_selection(memes['cnn']), delay=1)
Example #29
0
def song(client, message):

    user_id = message.from_user.id
    user_name = message.from_user.first_name
    rpk = "[" + user_name + "](tg://user?id=" + str(user_id) + ")"

    query = ""
    for i in message.command[1:]:
        query += " " + str(i)
    print(query)
    m = message.reply("🔎 Finding the song...")
    ydl_opts = {"format": "bestaudio[ext=m4a]"}
    try:
        results = YoutubeSearch(query, max_results=1).to_dict()
        link = f"https://youtube.com{results[0]['url_suffix']}"
        # print(results)
        title = results[0]["title"][:40]
        thumbnail = results[0]["thumbnails"][0]
        thumb_name = f"thumb{title}.jpg"
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, "wb").write(thumb.content)

        duration = results[0]["duration"]
        results[0]["url_suffix"]
        results[0]["views"]

    except Exception as e:
        m.edit(
            "❌ Found Nothing.\n\nTry another keywork or maybe spell it properly."
        )
        print(str(e))
        return
    m.edit("Downloading the song ")
    try:
        with youtube_dl.YoutubeDL(ydl_opts) as ydl:
            info_dict = ydl.extract_info(link, download=False)
            audio_file = ydl.prepare_filename(info_dict)
            ydl.process_info(info_dict)
        rep = "**🎵 Uploaded by [𝐑𝐈𝐒𝐇𝐈 ⚡](https://t.me/RISHI_OP)**"
        secmul, dur, dur_arr = 1, 0, duration.split(":")
        for i in range(len(dur_arr) - 1, -1, -1):
            dur += int(dur_arr[i]) * secmul
            secmul *= 60
        message.reply_audio(
            audio_file,
            caption=rep,
            thumb=thumb_name,
            parse_mode="md",
            title=title,
            duration=dur,
        )
        m.delete()
    except Exception as e:
        m.edit("❌ Error")
        print(e)

    try:
        os.remove(audio_file)
        os.remove(thumb_name)
    except Exception as e:
        print(e)
Example #30
0
async def lol_cb(b, cb):
    global que

    cbd = cb.data.strip()
    chat_id = cb.message.chat.id
    typed_=cbd.split(None, 1)[1]
    #useer_id = cb.message.reply_to_message.from_user.id
    try:
        x,query,useer_id = typed_.split("|")      
    except:
        await cb.message.edit("Song Not Found")
        return
    useer_id = int(useer_id)
    if cb.from_user.id != useer_id:
        await cb.answer("You ain't the person who requested to play the song!", show_alert=True)
        return
    await cb.message.edit("Hang On... Player Starting")
    x=int(x)
    try:
        useer_name = cb.message.reply_to_message.from_user.first_name
    except:
        useer_name = cb.message.from_user.first_name
    
    results = YoutubeSearch(query, max_results=5).to_dict()
    resultss=results[x]["url_suffix"]
    title=results[x]["title"][:40]
    thumbnail=results[x]["thumbnails"][0]
    duration=results[x]["duration"]
    views=results[x]["views"]
    url = f"https://youtube.com{resultss}"
    
    try:    
        duuration= round(duration / 60)
        if duuration > DURATION_LIMIT:
            await cb.message.edit(f"Music longer than {DURATION_LIMIT}min are not allowed to play")
            return
    except:
        pass
    try:
        thumb_name = f"thumb{title}.jpg"
        thumb = requests.get(thumbnail, allow_redirects=True)
        open(thumb_name, "wb").write(thumb.content)
    except Exception as e:
        print(e)
        return
    dlurl=url
    dlurl=dlurl.replace("youtube","youtubepp")
    keyboard = InlineKeyboardMarkup(
        [
            [
                InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
            ],
            [
                InlineKeyboardButton(text="🎬 YouTube", url=f"{url}"),
                InlineKeyboardButton(text="Download 📥", url=f"{dlurl}"),
            ],
            [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
        ]
    )
    requested_by = useer_name
    await generate_cover(requested_by, title, views, duration, thumbnail)
    file_path = await convert(youtube.download(url))  
    if chat_id in callsmusic.pytgcalls.active_calls:
        position = await queues.put(chat_id, file=file_path)
        qeue = que.get(chat_id)
        s_name = title
        try:
            r_by = cb.message.reply_to_message.from_user
        except:
            r_by = cb.message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        await cb.message.delete()
        await b.send_photo(chat_id,
            photo="final.png",
            caption=f"**🏷️Song: [{title}]({url})**\n⏱️Duration: {duration}\n💡Status: `queued`\nRequested By {message.from_user.mention}\n\n**At Position #{position}!",
            reply_markup=keyboard,
        )
        os.remove("final.png")
        
    else:
        que[chat_id] = []
        qeue = que.get(chat_id)
        s_name = title
        try:
            r_by = cb.message.reply_to_message.from_user
        except:
            r_by = cb.message.from_user
        loc = file_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)

        callsmusic.pytgcalls.join_group_call(chat_id, file_path)
        await cb.message.delete()
        await b.send_photo(chat_id,
            photo="final.png",
            reply_markup=keyboard,
            caption=f"**🏷️Song: [{title}]({url})**\n⏱️Duration: {duration}\n💡Status: `Playing🎵`\nRequested By {message.from_user.mention}",
        )
        os.remove("final.png")
        ######wkkqkqkq