Beispiel #1
0
def help(_: Client, m: Message):
    u = get_user(m.from_user)
    m.reply(('🙋 Добро пожаловать в ваш Фатум!\n\n'
             'Дистанция генерации: %d м.\n\n'
             'Отправьте местоположение '
             'для генерации новой точки '
             'или отправьте желаемую дистанцию в метрах.') % (u.distance))
Beispiel #2
0
def werewolf_message_call(cli: Client, msg: Message):
    print("werewolf_message_call")
    if not msg.text:
        return

    if nolynch_mode.get(msg.chat.id, False):
        if msg.text.startswith(voting_message):
            msg.reply("/EQ" + tasksystem_username)
            return

    if msg.text.startswith("#players"):
        msg.reply("New game...")
        msg.pin(False)
        return

    elif player_list_header in msg.text:
        player_count = msg.text.splitlines()[0].replace(player_list_header, "", 1).strip().split('/')
        if final_list_footer in msg.text:
            msg.reply("/CONFIRM" + tasksystem_username)
            time.sleep(2)
            cli.send_message(msg.chat.id, "/CLEAR" + tasksystem_username)
        elif player_count[0] == player_count[1]:
            msg.reply("/NEW" + tasksystem_username)
        else:
            msg.reply("/STSUP" + tasksystem_username)
Beispiel #3
0
def start_command(bot, message: Message):
    Subscriber().register(message.from_user.id)
    message.reply(f"Assalam Alaikum {message.from_user.first_name}!")
    message.reply("To personalize the experience, you may subscribe to your own subjects "
                  "and get notifications accordingly. I hope this bot will be useful to you.\n\n"
                  "If you would like to request for a feature. Enter command /feedback and "
                  "explain what you want in detail.")
async def _filter_blacklist(msg: Message):
    chat_id = str(msg.chat.id)
    BLACK_LIST = await bot.load_data(bot.BLACKLIST_DATA_ID)
    BLACKLIST_MODE = await bot.load_data(bot.BLACKLIST_MODE_ID)
    if BLACKLIST_MODE.get(chat_id) is None:
        BLACKLIST_MODE.update({chat_id: "warn"})
        await bot.save_data(bot.BLACKLIST_MODE_ID, json.dumps(BLACKLIST_MODE))
    if BLACK_LIST.get(chat_id) is None:
        return
    if not user_dict.get(msg.from_user.id):
        bio = (await bot.get_chat(msg.from_user.id)).bio
        if not bio:
            bio = "No Bio"
        user_dict[msg.from_user.id] = bio
    if await _is_spammer(int(chat_id), msg.from_user.id,
                         user_dict[msg.from_user.id]):
        return
    text = None
    if msg.text:
        text = msg.text.lower()
    elif msg.caption:
        text = msg.caption.lower()
    if text and BLACK_LIST.get(chat_id) is not None:
        for trigger in BLACK_LIST.get(chat_id):
            pattern = r"( |^|[^\w])" + re.escape(trigger) + r"( |$|[^\w])"
            if re.search(pattern, text, re.IGNORECASE):
                reason = f"Due to match on {trigger} Blacklisted word."
                try:
                    if await check_bot_rights(msg.chat.id,
                                              "can_delete_messages"):
                        await msg.delete()
                    if BLACKLIST_MODE.get(chat_id) == "del":
                        if await check_bot_rights(msg.chat.id,
                                                  "can_delete_messages"):
                            await msg.reply(f"#DELETED\n\n{reason}")
                    elif BLACKLIST_MODE.get(chat_id) == "warn":
                        await warn_user(msg, msg.chat.id, msg.from_user.id,
                                        reason)
                    elif BLACKLIST_MODE.get(chat_id) == "ban":
                        await asyncio.gather(
                            bot.kick_chat_member(msg.chat.id,
                                                 msg.from_user.id),
                            msg.reply(f"#BANNED\n\n{reason}"))
                    elif BLACKLIST_MODE.get(chat_id) == "kick":
                        await asyncio.gather(
                            bot.kick_chat_member(msg.chat.id, msg.from_user.id,
                                                 time.time() + 45),
                            msg.reply(f"#KICKED\n\n{reason}"))
                    elif BLACKLIST_MODE.get(chat_id) == "mute":
                        await asyncio.gather(
                            bot.restrict_chat_member(msg.chat.id,
                                                     msg.from_user.id,
                                                     ChatPermissions()),
                            msg.reply(f"#MUTED\n\n{reason}"))
                except Exception:
                    pass
                break
Beispiel #5
0
def sudo_command_call(cli: Client, msg: Message):
    print("sudo_command_call")
    sudos = get_sudos()
    if not any([x for x in sudos if x == msg.from_user.id]):
        msg.reply("sudo only")
        return

    if any([x for x in ct["eqmode"] if f"/{x}" == msg.text.lower()]):
        nolynch_mode[msg.chat.id] = not nolynch_mode.get(msg.chat.id, False)
        msg.reply(f'eqmode: **{nolynch_mode[msg.chat.id]}**')
Beispiel #6
0
def neko(client: Client, message: Message):
    reply = message.reply_to_message

    if reply.text is None:
        return

    message.delete()

    result = requests.post(
        "{}/api/documents".format(BASE),
        data=dict(content=reply.text.encode("UTF-8"))).json()

    message.reply(
        "{}/{}.py".format(BASE, result["result"]["key"]),
        reply_to_message_id=reply.message_id,
    )
Beispiel #7
0
def loc(c: Client, m: Message):
    m.reply_chat_action('find_location')
    user = m.from_user
    u = get_user(user)

    loc: Location = m.location
    p = Point(loc.latitude, loc.longitude)
    try:
        d = qr.randint(500, u.distance) / 1000
        angle = qr.randint(0, 360)
        np = distance.distance(d).destination(p, angle)
        m.reply_location(np.latitude, np.longitude)
        c.send_message(m.from_user.id, 'В добрый путь!')
        update_points_count(user)
    except Exception as e:
        m.reply('Error =(\n%s' % e)
Beispiel #8
0
def werewolf_forworded_call(cli: Client, msg: Message):
    print("werewolf_forworded_call")
    if not msg.text:
        return
    
    if any([x for x in new_achiv_header if msg.text.startswith(x)]):
        msg.reply("مبارکههه 🥳")
        return

    else:
        for x in roles_texts:
            for t in x.text:
                if msg.text.startswith(t):
                    rs = msg.reply("/ts " + x.roles)
                    time.sleep(1)
                    rs.delete()
                    return
Beispiel #9
0
async def reply_and_delete(message: Message, text: str):
    await asyncio.gather(
        message.delete(),
        message.reply(text,
                      quote=False,
                      reply_to_message_id=getattr(message.reply_to_message,
                                                  "message_id", None),
                      disable_web_page_preview=True))
 async def delete_user_manual(self, client: Client, msg: Message) -> None:
     if len(msg.command) != 2:
         user_id = int(msg.command[1])
         if await self.query_authorized_user(user_id):
             await asyncio.gather(
                 client.send_message(user_id, "Access revoked"),
                 self.delete_authorized_user(user_id), msg.reply('Success'))
         else:
             await msg.reply('User not in authorized list')
Beispiel #11
0
def direct_rolling_call(cli: Client, msg: Message):
    print("direct_rolling_call")
    if msg.reply_to_message.text:
        if any([x for x in task_list_update if msg.reply_to_message.text.startswith(x)]):
            for x in roles:
                for k in x.kinders:
                    if msg.text == k:
                        rs = msg.reply("/ts " + x.kinders[0])
                        time.sleep(1)
                        rs.delete()
                        return
Beispiel #12
0
async def _filter_blacklist(_, msg: Message):
    if not BLACK_LIST.get(msg.chat.id):
        return
    text = None
    if msg.text:
        text = msg.text.lower()
    elif msg.caption:
        text = msg.caption.lower()
    if text:
        for trigger in BLACK_LIST.get(msg.chat.id):
            pattern = r"( |^|[^\w])" + re.escape(trigger) + r"( |$|[^\w])"
            if re.search(pattern, text, re.IGNORECASE):
                reason = f"Due to match on {trigger} Blacklisted word."
                try:
                    if await check_bot_rights(msg.chat.id,
                                              "can_delete_messages"):
                        await msg.delete()
                    if BLACKLIST_MODE == "none":
                        await msg.reply(f"#DELETED\n\n{reason}")
                    elif BLACKLIST_MODE == "warn":
                        await warn_user(msg, msg.chat.id, msg.from_user.id,
                                        reason)
                    elif BLACKLIST_MODE == "ban":
                        await asyncio.gather(
                            bot.kick_chat_member(msg.chat.id,
                                                 msg.from_user.id),
                            msg.reply(f"#BANNED\n\n{reason}"))
                    elif BLACKLIST_MODE == "kick":
                        await asyncio.gather(
                            bot.kick_chat_member(msg.chat.id, msg.from_user.id,
                                                 time.time() + 45),
                            msg.reply(f"#KICKED\n\n{reason}"))
                    elif BLACKLIST_MODE == "mute":
                        await asyncio.gather(
                            bot.restrict_chat_member(msg.chat.id,
                                                     msg.from_user.id,
                                                     ChatPermissions()),
                            msg.reply(f"#MUTED\n\n{reason}"))
                except Exception:
                    pass
                break
Beispiel #13
0
async def fmt(_, message: Message):
    """Tell to format code"""
    await asyncio.gather(
        message.delete(),
        message.reply(
            FMT,
            quote=False,
            parse_mode="html",
            disable_web_page_preview=True,
            reply_to_message_id=getattr(message.reply_to_message, "message_id",
                                        None),
        ))
Beispiel #14
0
async def help(bot: Assistant, message: Message):
    """Show this message"""
    await asyncio.gather(
        message.delete(),
        message.reply(
            HELP,
            quote=False,
            reply_to_message_id=getattr(
                message.reply_to_message,
                "message_id", None
            ),
            )
    )
Beispiel #15
0
async def help(bot: Assistant, message: Message):
    """Show this message"""
    await asyncio.gather(
        message.delete(),
        message.reply(
            HELP,
            quote=False,
            reply_to_message_id=getattr(message.reply_to_message, "message_id",
                                        None),
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("Remove Help",
                                     f"remove.{message.from_user.id}")
            ]]),
        ))
Beispiel #16
0
def on_user_join(client: Client, msg: Message) -> None:
    for user in msg.new_chat_members:

        if client.get_chat_member(msg.chat.id,
                                  user.id).can_send_messages == False:
            client.kick_chat_member(msg.chat.id,
                                    user.id,
                                    until_date=int(time.time()) +
                                    36000)  # 60*60*10 == 36000 == 10 hours
            msg.reply(f"Banned user {user.first_name} because they rejoined.")
            return

        client.restrict_chat_member(
            msg.chat.id,
            user.id,
            ChatPermissions(
                can_send_messages=False,
                can_change_info=False,
                can_invite_users=False,
                can_pin_messages=False,
            ),
        )
        client.send_chat_action(msg.chat.id, "upload_photo")

        captchaSolution, captchaBytesIO = get_captcha()
        captchaBytesIO.name = "captcha.jpeg"
        correctEmoji = getattr(emoji, captchaSolution)
        msg.reply_photo(
            captchaBytesIO,
            caption=
            f"Welcome {user.first_name}\nYou must complete a captcha to chat.\nChoose the correct emoji.",
            reply_markup=get_keyboard(
                correctEmoji,
                user.id,
            ),
        )
Beispiel #17
0
def get_id(message: Message) -> Union[int, None]:
    """
    function to cathe the use ID from the given message.
    :return the user ID or None in case of filer.
    """
    if message.reply_to_message.forward_from:
        uid = message.reply_to_message.forward_from.id
    else:
        uid = message.reply_to_message.text.split("\n")[0]
    if isinstance(uid, str) and uid.isdigit():
        uid = int(uid)
    if not isinstance(uid, int):
        asyncio.get_event_loop().run_until_complete(
            message.reply(
                MSG('user_not_found',
                    add_user(tg_user=message.from_user).language)))
        return
    return uid
Beispiel #18
0
 def my_handler(client, message: types.Message):
     message_data = message.text.split(' ')
     command = message_data[0]
     if message.chat.id == self.my_id:
         if command == "!help":
             message.reply(
                 "In chat with yourself you can change settings of your addon:\n\n"
                 "<code>!ping_all_from_non_me</code> - toggle using !ping_all command "
                 f"by all members of chat\n<b>({self.ping_all_from_non_me})</b>\n\n",
                 parse_mode="html")
         elif command == "!ping_all_from_non_me":
             self.ping_all_from_non_me = not self.ping_all_from_non_me
             message.reply(
                 f"ping_all_from_non_me = <b>{self.ping_all_from_non_me}</b> ",
                 parse_mode="html")
     else:
         if command == '!ping_all':
             if self.ping_all_from_non_me or (self.my_id
                                              == message.from_user.id):
                 logging.warning(f"Pinging all in {message.chat.title}")
                 list_mentions = []
                 for member in message.chat.iter_members():
                     if not member.user.is_bot:
                         try:
                             list_mentions.append(member.user.mention)
                         except AttributeError:
                             pass
                 conclusion = ''
                 if self.my_id != message.from_user.id:
                     conclusion = '\n\n<b>Requested by:</b>\n'
                     try:
                         conclusion += message.from_user.mention
                     except AttributeError:
                         pass
                 message.reply('\n'.join(list_mentions) + conclusion)
                 logging.warning(
                     f"Done pinging all in {message.chat.title}")
         elif command == "!get_all":
             message.delete()
             list_mentions = []
             for member in message.chat.iter_members():
                 if not member.user.is_bot:
                     try:
                         list_mentions.append(member.user.mention)
                     except AttributeError:
                         pass
             app.send_message(
                 "me", "\n".join(list_mentions) +
                 f"\n\nfrom {message.chat.title}")
Beispiel #19
0
async def ytplay(_, message: Message):
    global que
    if message.chat.id in DISABLED_GROUPS:
        return
    lel = await message.reply("🔄 **Sedang Memproses Lagu**")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id

    try:
        user = await USER.get_me()
    except:
        user.first_name = "MusicMan"
    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(
                        f"<b>Ingatlah untuk menambahkan {user.first_name} ke Channel Anda</b>",
                    )
                    pass
                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 lel.edit(
                        f"<b>{user.first_name} berhasil bergabung dengan Group anda</b>",
                    )

                except UserAlreadyParticipant:
                    pass
                except Exception:
                    # print(e)
                    await lel.edit(
                        f"<b>⛑ Flood Wait Error ⛑\n{user.first_name} tidak dapat bergabung dengan grup Anda karena banyaknya permintaan bergabung untuk userbot! Pastikan pengguna tidak dibanned dalam grup."
                        f"\n\nAtau tambahkan @{ASSISTANT_NAME} secara manual ke Grup Anda dan coba lagi</b>",
                    )
    try:
        await USER.get_chat(chid)
        # lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i>{user.first_name} terkena banned dari Grup ini, Minta admin untuk mengirim perintah `/play` untuk pertama kalinya atau tambahkan @{ASSISTANT_NAME} secara manual</i>"
        )
        return
    await lel.edit("🔎 **Sedang Mencari Lagu**")
    user_id = message.from_user.id
    user_name = message.from_user.first_name

    query = ""
    for i in message.command[1:]:
        query += " " + str(i)
    print(query)
    await lel.edit("🎵 **Sedang Memproses Lagu**")
    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(
            "**Lagu tidak ditemukan.** Coba cari dengan judul lagu yang lebih jelas, Ketik `/help` bila butuh bantuan"
        )
        print(str(e))
        return
    dlurl = url
    dlurl = dlurl.replace("youtube", "youtubepp")
    keyboard = InlineKeyboardMarkup([
        [
            InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
            InlineKeyboardButton("⛑ Channel", url="https://t.me/Lunatic0de"),
        ],
        [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"🏷 **Judul:** [{title[:60]}]({url})\n⏱ **Durasi:** {duration}\n💡 **Status:** Antrian Ke `{position}`\n" \
                    + f"🎼 **Request Dari:** {message.from_user.mention}",
                   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(
                "**Voice Chat Group tidak aktif, Saya tidak dapat bergabung**")
            return
        await message.reply_photo(
            photo="final.png",
            caption = f"🏷 **Judul:** [{title[:60]}]({url})\n⏱ **Durasi:** {duration}\n💡 **Status:** Sedang Memutar\n" \
                    + f"🎼 **Request Dari:** {message.from_user.mention}",
                   reply_markup=keyboard,)
        os.remove("final.png")
        return await lel.delete()
Beispiel #20
0
def superadmin_command_call(cli: Client, msg: Message):
    print("superadmin_command_call")
    if msg.from_user.id != super_admin:
        msg.reply("super only!")
        return

    if msg.text == "/test":
        msg.reply("tested!")

    elif msg.text.startswith('/addsudo'):
        if msg.reply_to_message:
            add_sudo(msg.reply_to_message.from_user.id)
            msg.reply(f"added **{msg.reply_to_message.from_user.first_name}**")
        
        elif msg.text.split(' ').__len__() > 1:
            try:
                add_sudo(int(msg.text.split(' ')[1]))
                msg.reply("added!")
            except:
                msg.reply('failed')
        else:
            msg.reply('unknown!')
Beispiel #21
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>",
                    )
                    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
    await lel.edit("🔎 <b>Finding</b>")
    user_id = message.from_user.id
    user_name = 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_path = 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_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 <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_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        try:
           await callsmusic.set_stream(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="▶️ <b>Playing</b> here the song requested by {} via Youtube Music 😎".format(
                message.from_user.mention()
            ),
        )
        os.remove("final.png")
        return await lel.delete()
Beispiel #22
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>",
                    )
                    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
    text_links=None
    await lel.edit("🔎 <b>Finding</b>")
    if message.reply_to_message:
        if message.reply_to_message.audio:
            pass
        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
    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_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("🎵 <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_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/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="❌", 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_path = 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_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 <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_path
        appendable = [s_name, r_by, loc]
        qeue.append(appendable)
        try:
            await callsmusic.set_stream(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="▶️ <b>Playing</b> here the song requested by {} via Youtube Music 😎".format(
                message.from_user.mention()
            ),
        )
        os.remove("final.png")
        return await lel.delete()
Beispiel #23
0
async def play(_, message: Message):
    global que
    lel = await message.reply("🔄 **işlemde**")
    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>Kanalda sesli açma yetkisi vermeyi unutma babuş</b>",
                    )
                    pass
                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>Beni grubunuzda sesli sohbet ve davetle bağlantı yetkisi verin yoksa çalışamam...</b>",
                    )
                    return

                try:
                    await USER.join_chat(invitelink)
                    await USER.send_message(message.chat.id,
                                            "Helloğ ben geldimke")
                    await lel.edit("<b>Tamam artık burda ses botuğ</b>", )

                except UserAlreadyParticipant:
                    pass
                except Exception:
                    # print(e)
                    await lel.edit(
                        f"<b>🔴 Sel bekleme hatası 🔴 \Sayın {user.first_name} userbot için yoğun isteklerden dolayı grubunuza katılamadı! Kullanıcının grupta yasaklanmadığından emin olun."
                        "\n\nYa da @zevzekcalarasistan manuel olarak ekleyin</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 bu sohbette değil, Yöneticiden ilk kez komut göndermesini /play isteyin veya ekleyin {user.first_name} kendiniz ekleyin</i>"
        )
        return
    message.from_user.id
    message.from_user.first_name
    await lel.edit("🔎 **Finding**")
    message.from_user.id
    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"❌ {DURATION_LIMIT} dakikadan uzun videoların oynatılmasına izin verilmez!"
            )
        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 converter.convert((
            await message.reply_to_message.download(file_name)
        ) if not path.isfile(path.join("downloads", file_name)) else file_name)
    else:
        query = ""
        for i in message.command[1:]:
            query += " " + str(i)
        print(query)
        await lel.edit("🎵 **İşlemde**")
        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(
                "Şarkı bulunamadı Başka bir şarkı deneyin veya belki doğru şekilde yazın."
            )
            print(str(e))
            return

        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
            ],
            [InlineKeyboardButton(text="YouTube'da İzle 🎬", 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 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"#⃣ İstediğiniz şarkı pozisyonda ** sıraya girdi ** {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(
                "Dostum sesli sohbet açık değil nasıl müzik çalmamı bekliyorsun..."
            )
            return
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption=
            "Youtube Music aracılığıyla {} tarafından istenen şarkı ▶ ️ ** burada çalınıyor **"
            .format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
Beispiel #24
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
    await lel.edit("🔎 **Finding**")
    message.from_user.id
    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="Support Channel",
                                     url="https://t.me/yudmusic")
            ],
            [InlineKeyboardButton(text="Close", callback_data="cls")],
        ])
        file_name = get_file_name(audio)
        title = file_name
        thumb_name = "https://telegra.ph/file/3db70390937823dbdcbd8.jpg"
        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 converter.convert((
            await message.reply_to_message.download(file_name)
        ) if not path.isfile(path.join("downloads", file_name)) else file_name)
    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

        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("📖 Playlist", callback_data="playlist"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="menu"),
            ],
            [
                InlineKeyboardButton(text="Support Channel",
                                     url="https://t.me/Vckyouuu")
            ],
            [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()
Beispiel #25
0
def subscribe_to_subjects(bot, message: Message):
    message.reply("shit",
                  reply_markup=InlineKeyboardMarkup([[
                      InlineKeyboardButton("✅ AI", 'subject_ai'),
                      InlineKeyboardButton("Robotics", 'subject_robotics'),
                  ]]))
Beispiel #26
0
def dist_cmd(_: Client, m: Message):
    """old variant with distance set"""
    d = change_distance(m.from_user, m.text[len('/distance'):])
    m.reply('Дистанция: %d м' % d)
Beispiel #27
0
def dist(_: Client, m: Message):
    d = change_distance(m.from_user, m.text)
    m.reply('Дистанция: %d м' % d)
Beispiel #28
0
async def play(_, message: Message):
    global que
    lel = await message.reply("🔄 **ρяσ¢єѕѕιηg**")
    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>яємємвєя тσ α∂∂ нєℓρєя тσ уσυя ¢нαηηєℓ</b>", )
                    pass
                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>α∂∂ мє αѕ α∂мιη σƒ уσя gяσυρ ƒιяѕт</b>", )
                    return

                try:
                    await USER.join_chat(invitelink)
                    await USER.send_message(
                        message.chat.id,
                        "ι נσιηє∂ тнιѕ gяσυρ ƒσя ρℓαуιηg мυѕι¢ ιη ν¢")
                    await lel.edit("<b>нєℓρєя υѕєявσт נσιηє∂ уσυя ¢нαт</b>", )

                except UserAlreadyParticipant:
                    pass
                except Exception:
                    # print(e)
                    await lel.edit(
                        f"<b>🔴 ƒℓσσ∂ ωαιт єяяσя 🔴 \ηυѕєя [Userbot](https://t.me/lightningmujik) ¢συℓ∂η'т נσιη уσυя gяσυρ ∂υє тσ нєανу яєqυєѕтѕ ƒσя υѕєявσт! мαкє ѕυяє υѕєя ιѕ ησт вαηηє∂ ιη gяσυρ."
                        "\η\ησя мαηυαℓℓу α∂∂ αѕѕιѕтαηт тσ уσυя gяσυρ αη∂ тяу αgαιη</b>",
                    )
    try:
        await USER.get_chat(chid)
        # lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i> {user.first_name} υѕєявσт ησт ιη тнιѕ ¢нαт, αѕк α∂мιη тσ ѕєη∂ /υѕєявσтנσιη ¢σммαη∂ ƒσя ƒιяѕт тιмє σя α∂∂ [𝕌𝕤𝕖𝕣𝕓𝕠𝕥](https://t.me/lightningmujik) мαηυαℓℓу</i>"
        )
        return
    message.from_user.id
    message.from_user.first_name
    await lel.edit("🔎 **ƒιη∂ιηg**")
    message.from_user.id
    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"❌ νι∂єσѕ ℓσηgєя тнαη {DURATION_LIMIT} мιηυтє(ѕ) αяєη'т αℓℓσωє∂ тσ ρℓαу!"
            )
        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("📖 ρℓαуℓιѕт", callback_data="ρℓαуℓιѕт"),
                InlineKeyboardButton("Menu ⏯ ", callback_data="мєηυ"),
            ],
            [InlineKeyboardButton(text="❌ ¢ℓσѕє", callback_data="cls")],
        ])
        file_name = get_file_name(audio)
        title = file_name
        thumb_name = "https://telegra.ph/file/b0c914fae86cb425793c3.jpg"
        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 converter.convert((
            await message.reply_to_message.download(file_name)
        ) if not path.isfile(path.join("downloads", file_name)) else file_name)
    else:
        query = ""
        for i in message.command[1:]:
            query += " " + str(i)
        print(query)
        await lel.edit("🎵 **ρяσ¢єѕѕιηg**")
        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(
                "ѕσηg ησт ƒσυη∂.тяу αησтнєя ѕσηg σя мαувє ѕρєℓℓ ιт ρяσρєяℓу.")
            print(str(e))
            return

        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton("📖 ρℓαуℓιѕт", callback_data="ρℓαуℓιѕт"),
                InlineKeyboardButton("мєηυ ⏯ ", callback_data="menu"),
            ],
            [InlineKeyboardButton(text="Watch On YouTube 🎬", url=f"{url}")],
            [InlineKeyboardButton(text="❌ ¢ℓσѕє", 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"#⃣ уσυя яєqυєѕтє∂ ѕσηg **qυєυє∂** αт ρσѕιтιση {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("gяσυρ ¢αℓℓ ιѕ ησт ¢σηηє¢тє∂ σя ι ¢αη'т נσιη ιт")
            return
        await message.reply_photo(
            photo="final.png",
            reply_markup=keyboard,
            caption=
            "▶️ **ρℓαуιηg** нєяє тнє ѕσηg яєqυєѕтє∂ ву {} νια уσυтυвє мυѕι¢ 😜".
            format(message.from_user.mention()),
        )
        os.remove("final.png")
        return await lel.delete()
Beispiel #29
0
async def play(_, message: Message):
    global que
    global useer
    if message.chat.id in DISABLED_GROUPS:
        return
    lel = await message.reply("🔄 **Tunggu**...")
    administrators = await get_administrators(message.chat)
    chid = message.chat.id

    try:
        user = await USER.get_me()
    except:
        user.first_name = "RobotMusic"
    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(
                        f"<b>Jangan Lupa Menambahkan {user.first_name} ke Channel Anda</b>",
                    )
                    pass
                try:
                    invitelink = await _.export_chat_invite_link(chid)
                except:
                    await lel.edit(
                        "<b>⚠️ Jadikan Bot sebagai Admin dulu!</b>", )
                    return

                try:
                    await USER.join_chat(invitelink)
                    await lel.edit(
                        f"<b>🆗 **Assisten Music** Berhasil Join di Voice Chat Grup!</b>",
                    )

                except UserAlreadyParticipant:
                    pass
                except Exception:
                    # print(e)
                    await lel.edit(
                        f"<b>⛑ Flood Wait Error ⛑\n{user.first_name} Tidak Dapat Bergabung Di Grub Anda. Terlalu Banyak Permintaan Dari Grub Laon."
                        f"\n\nCoba Masukkan @robotassisten secara manual dan coba lagi</b>",
                    )
    try:
        await USER.get_chat(chid)
        # lmoa = await client.get_chat_member(chid,wew)
    except:
        await lel.edit(
            f"<i>{user.first_name} tidak ada didalam Grup, Minta admin untuk /play command atau tambahkan {user.first_name} manual.</i>"
        )
        return
    text_links = None
    await lel.edit("🔄 **Mencari**...")
    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
    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"❌ **Video terlalu panjang lebih dari** `{DURATION_LIMIT}` menit. Tidak diizinkan!"
            )
        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton(text="☕ ᴜᴘᴅᴀᴛᴇ",
                                     url='https://t.me/robotmusicupdate'),
                InlineKeyboardButton(text="ᴏᴡɴᴇʀ ☕",
                                     url='https://t.me/justthetech'),
            ],
            [InlineKeyboardButton(text="❌ Close", callback_data="cls")],
        ])
        file_name = get_file_name(audio)
        title = file_name
        thumb_name = "https://telegra.ph/file/ab13882bb05849b6ba170.jpg"
        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("🎵 **Music** ditemukan")
        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(
                "❁ **Music** tidak ditemukan.\n❁ Ketik /play (judul lagu).\n❁ Ketik /search (judul lagu)."
            )
            print(str(e))
            return
        dlurl = url
        dlurl = dlurl.replace("youtube", "youtubepp")
        keyboard = InlineKeyboardMarkup([
            [
                InlineKeyboardButton(text="☕ ᴜᴘᴅᴀᴛᴇ",
                                     url='https://t.me/robotmusicupdate'),
                InlineKeyboardButton(text="ᴏᴡɴᴇʀ ☕",
                                     url='https://t.me/justthetech'),
            ],
            [
                InlineKeyboardButton(text="❌", 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("🎵 **Music ditemukan**")
        ydl_opts = {"format": "bestaudio[ext=m4a]"}

        try:
            results = YoutubeSearch(query, max_results=5).to_dict()
        except:
            await lel.edit(
                "❁ **Music tidak ditemukan**.\n❁ Ketik /play (judul lagu).\n❁ Ketik /search (judul lagu)."
            )
        # Looks like hell. Aren't it?? F**K OFF
        try:
            toxxt = "**Pilih Lagu yang kamu Inginkan :**\n\n"
            j = 0
            useer = user_name
            emojilist = [
                "1️⃣",
                "2️⃣",
                "3️⃣",
                "4️⃣",
                "5️⃣",
                "6️⃣",
            ]

            while j < 6:
                toxxt += f"{emojilist[j]} [{results[j]['title']}](https://youtube.com{results[j]['url_suffix']})\n"
                toxxt += f" ├ **Durasi** : {results[j]['duration']}\n"
                toxxt += f" ├ **Views** : {results[j]['views']}\n"
                toxxt += f" └ **Channel** : {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(
                        "6️⃣", callback_data=f'plll 5|{query}|{user_id}'),
                ],
                [InlineKeyboardButton(text="❌", 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(
                "❁ **Music tidak ditemukan.**\n❁ Ketik /play (judul lagu).\n❁ Ketik /search (judul lagu)."
            )

            # 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(
                    "❁ **Music tidak ditemukan.**\n❁ Ketik /play (judul lagu).\n❁ Ketik /search (judul lagu)."
                )
                print(str(e))
                return
            dlurl = url
            dlurl = dlurl.replace("youtube", "youtubepp")
            keyboard = InlineKeyboardMarkup([
                [
                    InlineKeyboardButton(text="☕ ᴜᴘᴅᴀᴛᴇ",
                                         url='https://t.me/robotmusicupdate'),
                    InlineKeyboardButton(text="ᴏᴡɴᴇʀ ☕",
                                         url='https://t.me/justthetech'),
                ],
                [
                    InlineKeyboardButton(text="❌", 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"☕ **Judul** Music : [{title}]({url}) \n#️⃣ **Antrian** : {position}",
            reply_markup=keyboard)
    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("❌ **Voice Chat Group tidak aktif, Hidupkan Dulu!**")
            return
        await message.reply_photo(
            photo="final.png",
            caption=
            f"📋 **Judul** Music : [{title}]({url}) \n⏱️ **Durasi** Music : {dur} \n👤 **Request** Dari : {useer}",
            reply_markup=keyboard)

    os.remove("final.png")
    return await lel.delete()