Exemple #1
0
 async def bot_pm_ban_cb(c_q: CallbackQuery):
     user_id = int(c_q.matches[0].group(1))
     await asyncio.gather(
         c_q.answer(f"Banning UserID -> {user_id} ...", show_alert=False),
         ban_from_bot_pm(user_id, "Spamming Bot", log=__name__),
         c_q.edit_message_text(f"✅ **Successfully Banned**  User ID: {user_id}"),
     )
Exemple #2
0
 async def back_btn(_, c_q: CallbackQuery):
     await gather(
         c_q.answer(),
         c_q.edit_message_text(
             text=inline_help_txt, reply_markup=(await help_btn())
         ),
     )
Exemple #3
0
def change_lang_keyboard(_, query: CallbackQuery):
    """
    refreshing the the user help keyboard by change the language or the
    settings.
    :param _: pyrogram Client, unused argument.
    :param query: when the user press the keyboard the query returns to this
                  function.
    :type query: pyrogram.types.CallbackQuery
    """
    if query.data == 'help_lang':
        keyboard = [[InlineKeyboardButton(text=MSG(lang), callback_data=lang)]
                    for lang in MSG.locales.keys()]
        return query.message.edit(MSG('chang_lang',
                                      get_user(query.from_user.id).language),
                                  reply_markup=InlineKeyboardMarkup(keyboard))
    elif query.data in MSG.locales.keys():
        with db_session:
            get_user(query.from_user.id).language = query.data
        if get_user(query.from_user.id).is_admin:
            return query.edit_message_text(MSG('settings_msg', query.data),
                                           reply_markup=get_settings_keyboard(
                                               query.data))
        else:
            return query.edit_message_text(MSG('users_help', query.data),
                                           disable_web_page_preview=True,
                                           reply_markup=InlineKeyboardMarkup([[
                                               InlineKeyboardButton(
                                                   MSG('button_lang',
                                                       query.data),
                                                   'help_lang')
                                           ]]))
def prevent_multiple_queries_from_a_user(client: TopUpGifter,
                                         query: CallbackQuery):
    user_id = str(query.from_user.id)
    user_info = dict(client.users.find_one(id=user_id))
    user = User(user_info)
    query.answer(text=texts['errors']['multiple_queries'][user.language],
                 show_alert=True)
def go_to_previous_step(client: TopUpGifter, query: CallbackQuery):
    user_id = str(query.from_user.id)
    user_info = dict(client.users.find_one(id=user_id))
    user = User(user_info)
    query_data = query.data.split(',')
    user.state = State.get_previous_state(user.state)
    user.last_interaction = datetime.now()
    client.users.update(user.to_dict(), ['id'])
    client.db.commit()
    query.continue_propagation()
Exemple #6
0
 async def settings_toggle(c_q: CallbackQuery):
     Config.BOT_ANTIFLOOD = False
     await asyncio.gather(
         c_q.answer(),
         SAVED_SETTINGS.update_one(
             {"_id": "BOT_ANTIFLOOD"},
             {"$set": {"data": Config.BOT_ANTIFLOOD}},
             upsert=True,
         ),
         c_q.edit_message_text("BOT_ANTIFLOOD is now disabled !"),
     )
Exemple #7
0
async def stop_user_from_doing_anything_callback(_, callback: CallbackQuery):
    """
    Checks if user is allowed to use MediaCenterBot via CallbackQuery
    """
    if callback.message.chat.id not in UserDB().all_user_ids():
        if callback.message.chat and callback.message.chat.type in {
                'group', 'supergroup'
        }:
            await callback.answer('Groups not allowed.')
            await callback.edit_message_text(GROUPS_NOT_ALLOWED_MESSAGE)
            callback.stop_propagation()

        await callback.edit_message_text(NOT_ALLOWED_MESSAGE)
        callback.stop_propagation()
def playlist_callback(client: Client, query: CallbackQuery):
    cp = player.currently_playing

    if query.data.startswith("add_to"):
        if db.add_item_to_playlist("custom", {
                "url": cp["url"],
                "title": cp["title"]
        }):
            query.message.edit_reply_markup(
                InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(_("playlist_6"),
                                             "rm_from_playlist"),
                    ],
                ]))
            query.answer(_("playlist_4"))
        else:
            query.answer(_("playlist_5"))
    elif query.data.startswith("rm_from"):
        if db.remove_item_from_playlist("custom", {
                "url": cp["url"],
                "title": cp["title"]
        }):
            query.message.edit_reply_markup(
                InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(_("playlist_3"),
                                             "add_to_playlist"),
                    ],
                ]))
            query.answer(_("playlist_7"))
        else:
            query.answer(_("playlist_8"))
Exemple #9
0
async def notify_callback(bot: Amime, callback: CallbackQuery):
    content_type = callback.matches[0]["c_type"]
    content_id = int(callback.matches[0]["c_id"])
    recipient_type = callback.matches[0]["r_type"]
    recipient_id = int(callback.matches[0]["r_id"])
    message = callback.message
    chat = message.chat
    user = callback.from_user
    lang = callback._lang

    if recipient_type == "group":
        if not await filters.administrator(bot, callback):
            return
    elif content_type == "episodes":
        callback.continue_propagation()

    notify = await Notify.get_or_none(
        recipient=recipient_id,
        recipient_type=recipient_type,
        item=content_id,
        type=content_type,
    )

    if notify is None:
        await Notify.create(
            recipient=recipient_id,
            recipient_type=recipient_type,
            item=content_id,
            type=content_type,
        )
        await callback.answer(lang.notifications_linked_alert, show_alert=True)
    else:
        await notify.delete()
        await callback.answer(lang.notifications_turned_off_alert,
                              show_alert=True)

    keyboard = bki(message.reply_markup)

    for line, column in enumerate(keyboard):
        for index, button in enumerate(column):
            if button[1].startswith("notify"):
                keyboard[line][index] = await get_notify_button(
                    lang,
                    user if recipient_type == "user" else chat,
                    content_type,
                    content_id,
                )

    await callback.edit_message_reply_markup(ikb(keyboard))
Exemple #10
0
 async def help_query(_, c_q: CallbackQuery):
     command_name = c_q.matches[0].group(1)
     buttons = InlineKeyboardMarkup([[
         InlineKeyboardButton("◀️  Back", callback_data="backbtn_ihelp"),
         InlineKeyboardButton(
             "📕  EXAMPLE",
             switch_inline_query_current_chat=_COMMANDS[command_name]
             ["i_q"],
         ),
     ]])
     await gather(
         c_q.answer(),
         c_q.edit_message_text(_COMMANDS[command_name]["help_txt"],
                               reply_markup=buttons),
     )
Exemple #11
0
async def set_language_callback(bot: Amime, callback: CallbackQuery):
    message = callback.message
    chat = message.chat
    user = callback.from_user
    if not user:
        return
    lang = callback._lang
    code: str = ""
    user_code = user.language_code or "en"
    if "." in user_code:
        user_code = user_code.split(".")[0]
    if user_code not in lang.strings.keys():
        user_code = "en"

    if await filters.private(bot, message):
        code = (await Users.get_or_create(
            {
                "name": user.first_name,
                "username": user.username or "",
                "language_bot": user_code,
                "language_anime": user_code,
                "is_collaborator": False,
            },
            id=user.id,
        ))[0].language_bot
    else:
        code = (await Chats.get_or_create(
            {
                "title": chat.title,
                "username": chat.username or "",
                "language": "en",
            },
            id=chat.id,
        ))[0].language
    callback._lang = lang.get_language(code)
Exemple #12
0
async def request_episodes_confirm(bot: Amime, callback: CallbackQuery):
    user = callback.from_user
    lang = callback._lang

    anime_id = int(callback.matches[0].group(1))
    language = callback.matches[0].group(2)

    anime = await anilist.AsyncClient().get(anime_id)

    is_collaborator = await filters.collaborator(bot,
                                                 callback) or bot.is_sudo(user)

    requests = await Requests.filter(item=anime_id, type="anime")
    requests = sorted(requests, key=lambda request: request.id)

    now_date = datetime.datetime.now().replace(tzinfo=datetime.timezone.utc)

    if not is_collaborator and len(requests) > 0:
        request = requests[-1]
        request_date = request.datetime
        date = now_date - request_date
        if date.seconds < (1 * 60 * 60 * 24):
            await callback.answer(
                lang.requested_in_last_24h_alert(
                    date=request_date.strftime("%H:%M:%S - %d/%m/%Y")),
                show_alert=True,
            )
            return

    await Requests.create(
        user=user.id,
        item=anime_id,
        type="anime",
        datetime=now_date,
        done=False,
    )

    text = "<b>New request</b>"
    text += f"\n<b>From</b>: {user.mention()}"
    text += "\n<b>Anime</b>:"
    text += f"\n    <b>ID</b>: <code>{anime.id}</code>"
    text += f"\n    <b>Name</b>: <code>{anime.title.romaji}</code>"
    text += (
        f"\n    <b>Language</b>: <code>{lang.strings[language]['LANGUAGE_NAME']}</code>"
    )
    text += "\n\n#REQUEST"

    await bot.send_message(
        CHATS["requests"],
        text,
        reply_markup=ikb([[("🆙 Get",
                            f"request get anime {anime_id} {language}")]]),
    )

    await callback.answer(lang.request_sent_alert, show_alert=True)

    matches = re.match(r"(\d+) (\d+)\s?(\d+)?", f"{anime_id} {user.id}")
    callback.matches = [matches]

    await anime_view(bot, callback)
Exemple #13
0
    async def func(ftl, __, query: CallbackQuery):
        if payload:
            thing = r"{}\_"
            if re.search(re.compile(thing.format(ftl.data)), query.data):
                search = re.search(re.compile(r"\_{1}(.*)"), query.data)
                if search:
                    query.payload = search.group(1)
                else:
                    query.payload = None

                return True

            return False
        else:
            if ftl.data == query.data:
                return True

            return False
    async def handle_callback_query(self, client: Client,
                                    msg: CallbackQuery) -> None:
        args = msg.data.split()
        if len(args) != 3:
            if args[0] == 'ignore':
                await asyncio.gather(msg.edit_message_reply_markup(),
                                     msg.answer())
            return

        # Account process
        if args[0] == 'account':
            _arg, sub_arg, user_id = args
            user_id = int(user_id)
            if sub_arg == 'grant':
                answer_msg = None
                if await self.query_authorized_user(user_id):
                    answer_msg = 'Already granted'
                else:
                    await self.insert_authorized_user(user_id)
                await asyncio.gather(
                    msg.message.edit_reply_markup(
                        InlineKeyboardMarkup([[
                            InlineKeyboardButton('Revoke',
                                                 f'account revoke {user_id}')
                        ]])), msg.answer(answer_msg),
                    client.send_message(user_id, 'Access granted'))
            elif sub_arg == 'deny':
                if await self.query_authorized_user(user_id):
                    await asyncio.gather(msg.message.edit_reply_markup(),
                                         msg.answer('Out of dated'))
                    return
                await asyncio.gather(
                    msg.message.edit_reply_markup(),
                    client.send_message(user_id, 'Access denied'),
                    msg.answer())
            elif sub_arg == 'revoke':
                await self.delete_authorized_user(user_id)
                await asyncio.gather(
                    msg.message.edit_reply_markup(),
                    client.send_message(user_id, "Access revoked"),
                    msg.answer())
            return
        # Account end

        _msg_text = f'<del>{args[1]}</del>' if args[
            0] == 'm' else f'<code>{args[1]}</code>'
        await asyncio.gather(
            client.edit_message_text(self.channel_id, int(args[2]), _msg_text,
                                     'html'),
            self.conn.update(args[1], args[0] == 'm'),
            self.hook_mark_full_redeemed_passcode(args[1], args[0] == 'm'),
            msg.edit_message_reply_markup(),
            msg.answer(),
        )
Exemple #15
0
def refresh_admin_keyboards(_, query: CallbackQuery):
    """
    refreshing the settings and the help keyboards.
    :param _: pyrogram Client, unused argument
    :param query: when the user press the keyboard
                  the query returns to this function.
    :type query: pyrogram.types.CallbackQuery
    """
    lang = get_user(query.from_user.id).language
    keyboard = InlineKeyboardMarkup([[
        InlineKeyboardButton(text=MSG('button_back', lang),
                             callback_data='back')
    ]])
    try:
        if query.data == 'lang':
            for k in MSG.locales.keys():
                keyboard.inline_keyboard.append(
                    [InlineKeyboardButton(text=MSG(k), callback_data=k)])
            return query.message.edit(MSG('chang_lang', lang),
                                      reply_markup=keyboard)
        elif query.data == 'explain_welcome':
            return query.answer(MSG('explain_welcome', lang),
                                show_alert=True,
                                cache_time=60)
        elif query.data == 'on_welcome':
            if data['start_msg']:
                data['start_msg'] = ''
                save_data()
                query.answer(MSG('welcome_removed', lang), show_alert=True)
            return query.message.edit_reply_markup(get_settings_keyboard(lang))
        elif query.data == 'admin_list':
            return query.message.edit(admin_list(lang), reply_markup=keyboard)
        elif query.data == 'block_list':
            return query.message.edit(block_list(lang), reply_markup=keyboard)
        elif query.data == 'back':
            return query.message.edit(MSG('settings_msg', lang),
                                      reply_markup=get_settings_keyboard(lang))
        elif query.data in ['block', 'admins', 'welcome', 'group']:
            return query.message.edit(
                MSG(f'help_{query.data}', lang),
                disable_web_page_preview=True,
                reply_markup=get_admin_help_keyboard(lang))
    except MessageNotModified:
        query.message.delete()
def callback(client: Client, query: CallbackQuery):
    current_volume = int(query.message.text.split()[-1].replace("%", ""))

    if query.data == "decrease_volume":
        volume = current_volume - 1

        if volume < 0:
            volume = 0

        volume = f"{volume}%"

        subprocess.Popen(["pactl", "set-sink-volume", "MySink", volume]).wait()

        query.message.reply_text(
            _("volume_1").format(volume),
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("➖", callback_data="decrease_volume"),
                InlineKeyboardButton("➕", callback_data="increase_volume"),
            ]]),
            quote=False,
        )
        query.message.delete()
        query.answer()
    elif query.data == "increase_volume":
        volume = current_volume + 1

        if volume > 100:
            volume = 100

        volume = f"{volume}%"

        subprocess.Popen(["pactl", "set-sink-volume", "MySink", volume]).wait()

        query.message.reply_text(
            _("volume_1").format(volume),
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton("➖", callback_data="decrease_volume"),
                InlineKeyboardButton("➕", callback_data="increase_volume"),
            ]]),
            quote=False,
        )
        query.message.delete()
        query.answer()
Exemple #17
0
 def func(flt, client, query: CallbackQuery):
     user_id = str(query.from_user.id)
     with client.db as db:
         user_info = dict(client.users.find_one(id=user_id))
         user = User(user_info)
         user_brightid_info = client.node.verifications.get(
             client.app_name, context_id=user.context_id)
         user_accounts_states = [
             user_info['state'] for user_info in client.users.find(
                 contextId=user_brightid_info['contextIds'],
                 state=[
                     State.CHOOSE_OPERATOR, State.GET_PHONE, State.CLAIMED
                 ])
         ]
         if user_accounts_states:
             query.answer(
                 text=texts['errors']['in_receiving'][user.language],
                 show_alert=True)
             return False
         user.state = State.CHOOSE_OPERATOR
         user.last_interaction = datetime.now()
         client.users.update(user.to_dict(), ['id'])
         return True
Exemple #18
0
def on_captcha_attempt(client: Client, cbQuery: CallbackQuery) -> None:
    isCorrect, step, mistakes, userId = decrypt_cdata(cbQuery.data)

    if not cbQuery.message:
        cbQuery.answer("Something went wrong")
        return

    if not userId == cbQuery.from_user.id:
        cbQuery.answer("This isn't your captcha!", show_alert=True)
        return

    if not isCorrect and mistakes >= 1:
        client.kick_chat_member(cbQuery.message.chat.id,
                                cbQuery.from_user.id,
                                until_date=int(time.time()) +
                                36000)  # 10 hours
        cbQuery.message.reply(
            f"Banned {cbQuery.from_user.first_name} because they failed the captcha!"
        )
        cbQuery.message.delete()
        return

    if step >= 2:
        client.restrict_chat_member(
            cbQuery.message.chat.id,
            userId,
            ChatPermissions(
                can_send_messages=True,
                can_send_media_messages=True,
                can_send_stickers=True,
                can_send_animations=True,
                can_send_games=True,
                can_use_inline_bots=True,
                can_add_web_page_previews=True,
                can_send_polls=True,
            ),
        )
        cbQuery.message.delete()
        return 0

    with NamedTemporaryFile(suffix=".png") as ntf:
        captchaSolution = get_captcha(outfile=ntf.file)[0]
        correctEmoji = getattr(emoji, captchaSolution)
        cbQuery.message.edit_media(
            InputMediaPhoto(ntf.name, caption=f"Choose the correct emoji."),
            reply_markup=get_keyboard(correctEmoji,
                                      userId,
                                      step=step + 1,
                                      mistakes=mistakes + (not isCorrect)),
        )
    cbQuery.answer("Solve the next one!")
Exemple #19
0
async def delete_torrent(_, callback: CallbackQuery, **kwargs):
    torrent_hash = kwargs.get('torrent_hash') if kwargs.get(
        'torrent_hash') else callback.payload
    try:
        if kwargs.get('files'):
            QBT().delete_torrent_files(torrent_hash)
        else:
            QBT().delete_torrent(torrent_hash)

        await callback.answer("SUCCESS")
        await callback.message.reply(
            f"{emoji.FIRE} **Torrent {'and Files ' if kwargs.get('files') else ''}Deleted** {emoji.FIRE}"
        )
        time.sleep(2)
        await callback.message.delete()
        await all_torrents(_, callback.message)
    except Exception:
        await asyncio.gather(
            callback.answer("ERROR"),
            callback.message.reply(
                f"{emoji.SKULL} **An error has occurred** {emoji.SKULL}"))
Exemple #20
0
async def on_remove_plugin(c: Client, cq: CallbackQuery):
    lang = cq._lang
    basename = cq.matches[0]["basename"]
    plugin_type = cq.matches[0]["plugin_type"]
    pg = cq.matches[0]["page"]

    if basename not in plugins[plugin_type]:
        return await cq.answer(lang.plugin_not_found(name=basename))

    plugin = plugins[plugin_type][basename]

    inactive = await get_inactive_plugins(plugins)

    if not os.path.exists(plugin["filename"]):
        return await cq.edit(lang.plugin_not_exists_on_server)

    if plugin["notation"] in inactive:
        inactive = [x for x in inactive if x != plugin["notation"]]
        await Config.get(key="INACTIVE_PLUGINS"
                         ).update(value=json.dumps(inactive))

    try:
        module = importlib.import_module(plugin["notation"])
    except Exception as e:
        os.remove(plugin["filename"])
        return await cq.edit(lang.plugin_could_not_load(e=e))

    functions = [*filter(callable, module.__dict__.values())]
    functions = [*filter(lambda f: hasattr(f, "handler"), functions)]

    client = (user, bot)[plugin_type == "bot"]
    for f in functions:
        client.remove_handler(*f.handler)
    del plugins[plugin_type][basename]
    os.remove(plugin["filename"])

    await cq.answer(lang.plugin_removed(name=basename))
    cq.matches = [{"page": pg, "type": plugin_type}]
    await on_list_plugins_type(c, cq)
def change_language(client: TopUpGifter, query: CallbackQuery):
    user_id = str(query.from_user.id)
    user_info = dict(client.users.find_one(id=user_id))
    user = User(user_info)
    query_data = query.data.split(',')
    action = query_data[0]
    if user.language == action:
        query.answer()
    else:
        query.edit_message_text(text=texts[State.START][action],
                                reply_markup=InlineKeyboardMarkup(
                                    keyborads[State.START][action]))
        user.language = action
        user.last_interaction = datetime.now()
        client.users.update(user.to_dict(), ['id'])
        client.db.commit()
        query.answer()
Exemple #22
0
def _dummy_btn_handler(_, callback_query: CallbackQuery):
    callback_query.answer()
Exemple #23
0
    async def gc_toggles(c_q: CallbackQuery):
        answer = ""
        alert = False
        to_edit = False
        gc = get_groupcall(c_q.message.chat.id)
        toggle_type = c_q.matches[0].group(1)
        to_change = c_q.matches[0].group(2)
        cb_text = to_change.title()
        if toggle_type == "rec":
            answer = "Not Implemented yet, 👉😬👈"
            alert = True
            # if to_change == "pause":
            #     gc.pause_recording()
            # elif to_change == "resume":
            #     gc.resume_recording()
            # elif to_change == "restart":
            #     gc.restart_recording()
        elif toggle_type == "plyr":
            if to_change == "playlist":
                to_edit = True
                text = "🗒  **Music Playlist**\n\n"
                if len(gc.playlist) != 0:
                    text += "\n".join([
                        f"• **{x}.** [{y['title']}]({y['msg'].link})"
                        for x, y in enumerate(gc.playlist, start=1)
                    ])
                else:
                    text += "`[ Empty ]`"
                buttons = [[
                    InlineKeyboardButton("Back", callback_data="vcbtn_player")
                ]]
                return await c_q.message.edit(
                    text, reply_markup=InlineKeyboardMarkup(buttons))

            if to_change == "pause":
                gc.pause_playout()
                answer = f"⏸  {cb_text}d Voice Chat"
            elif to_change == "join":
                await gc.join()
                answer = f"🔌  {cb_text}ed Voice Chat"
            elif to_change == "resume":
                gc.resume_playout()
                answer = f"▶️  {cb_text}d Voice Chat"
            # elif to_change == "restart":
            #     gc.restart_playout()
            elif to_change == "stop":
                answer = f"⏹  {cb_text}ped Voice chat."
                await gc.leave()
            elif to_change == "repeat":
                answer = f"🔁  {cb_text} :  {emojize(gc.replay())}"
            elif to_change == "skip":
                if len(gc.playlist) <= 1:
                    answer = "Nothing Found to Skip, add songs in queue first !"
                    alert = True
                else:
                    pop_and_del(gc)
                    await asyncio.gather(c_q.answer("⏭  Song Skipped"),
                                         play_now(gc))
                    return
            elif to_change == "clearall":
                gc.playlist.clear()
                answer = "🚮  Playlist Cleared !"
            elif to_change == "shuffle":
                if len(gc.playlist) <= 1:
                    answer = "Nothing Found to Shuffle, add songs in queue first !"
                    alert = True
                else:
                    current = gc.playlist.pop(0)
                    shuffle(gc.playlist)
                    gc.playlist.insert(0, current)
                    answer = "🔀  Playlist Shuffled"
        else:
            to_edit = True
            if match := re.search(r"([0-9.]+)%", c_q.message.text):
                volume = int(float(match.group(1)) * 2)
Exemple #24
0
async def anime_episode_delete(bot: Amime, callback: CallbackQuery):
    message = callback.message
    user = callback.from_user
    lang = callback._lang

    anime_id = int(callback.matches[0].group(1))
    season = int(callback.matches[0].group(2))
    number = int(callback.matches[0].group(3))
    subtitled = bool(int(callback.matches[0].group(4)))
    language = callback.matches[0].group(5)
    page = int(callback.matches[0].group(6))

    episodes = []

    if number == -1:
        keyboard = [
            [
                (
                    lang.confirm_button,
                    f"manage episode delete {anime_id} {season} -2 {int(subtitled)} {language} {page}",
                ),
                (
                    lang.cancel_button,
                    f"manage anime {anime_id} {season} {int(subtitled)} {language} {page}",
                ),
            ],
        ]

        await message.edit_text(
            lang.confirm_text,
            reply_markup=ikb(keyboard),
        )
        return
    elif number == -2:
        episodes = await Episodes.filter(
            anime=anime_id,
            season=season,
            language=language,
            subtitled=subtitled,
        )

        logger.debug(
            "%s deleted season %s of the anime %s (%s)",
            user.first_name,
            season,
            anime_id,
            language,
        )
    else:
        episodes = [
            await Episodes.get(
                anime=anime_id,
                season=season,
                number=number,
                language=language,
                subtitled=subtitled,
            )
        ]

        logger.debug(
            "%s deleted episode %s of the anime %s (%s)",
            user.first_name,
            number,
            anime_id,
            language,
        )

    for episode in episodes:
        notification = await Notifications.get_or_none(item=anime_id,
                                                       type="anime",
                                                       season=season,
                                                       number=number,
                                                       language=language)
        if notification is not None:
            await notification.delete()
        await episode.delete()

    await callback.answer(lang.confirm_delete_episode_alert, show_alert=True)

    matches = re.search(
        r"(\d+) (\d+) (\d+) (\w+) (\d+)",
        f"{anime_id} {season} {int(subtitled)} {language} {page}",
    )
    callback.matches = [matches]

    await anime_manage(bot, callback)
Exemple #25
0
async def anime_episode_save(bot: Amime, callback: CallbackQuery):
    user = callback.from_user
    lang = callback._lang

    anime_id = int(callback.matches[0].group(1))
    season = int(callback.matches[0].group(2))
    subtitled = bool(int(callback.matches[0].group(3)))
    language = callback.matches[0].group(4)
    page = int(callback.matches[0].group(5))

    episode = EPISODES[str(user.id)][str(anime_id)]

    logger.debug(
        "%s is edited/saved episode %s of the anime %s (%s)",
        user.first_name,
        episode["number"],
        anime_id,
        language,
    )

    episode["anime"] = anime_id
    episode["season"] = season
    episode["language"] = language
    episode["added_by"] = str(user.id)

    id = -1
    if "id" in episode.keys():
        id = episode["id"]

    video = episode["video"]

    if isinstance(episode["video"], Document):
        episode["file_id"] = ""
    elif isinstance(episode["video"], Video):
        episode["file_id"] = episode["video"].file_id
    del episode["video"]

    number = episode["number"]

    if "id" in episode.keys():
        episode_db = await Episodes.get(id=episode["id"])
        del episode["id"]
        episode_db.update_from_dict(episode)
        await episode_db.save()
    else:
        episode_db = await Episodes.create(**episode)
        id = episode_db.id

        now_date = datetime.datetime.now().replace(
            tzinfo=datetime.timezone.utc)
        await Notifications.create(
            item=anime_id,
            type="anime",
            season=season,
            number=number,
            language=language,
            datetime=now_date,
        )

    if "update_video" in episode.keys() and episode["update_video"] is True:
        await bot.video_queue.add(id, video)

    await callback.answer(lang.confirm_save_episode_alert, show_alert=True)

    matches = re.search(
        r"(\d+) (\d+) (\d+) (\w+) (\d+)",
        f"{anime_id} {season} {int(subtitled)} {language} {page}",
    )
    callback.matches = [matches]

    await anime_manage(bot, callback)

    del EPISODES[str(user.id)][str(anime_id)]
Exemple #26
0
async def anime_manage(bot: Amime, callback: CallbackQuery):
    message = callback.message
    chat = message.chat
    user = callback.from_user
    lang = callback._lang

    anime_id = int(callback.matches[0].group(1))
    season = int(callback.matches[0].group(2))
    subtitled = bool(int(callback.matches[0].group(3)))
    language = callback.matches[0].group(4)
    page = int(callback.matches[0].group(5))

    if str(user.id) in VIDEOS.keys() and str(anime_id) in VIDEOS[str(
            user.id)].keys():
        chat.cancel_listener()
        del VIDEOS[str(user.id)][str(anime_id)]

    buttons = [
        (
            f"{lang.language_button}: {lang.strings[language]['LANGUAGE_NAME']}",
            f"manage anime language {anime_id} {season} {int(subtitled)} {language} {page}",
        ),
        (
            f"{lang.season_button}: {season}",
            f"manage anime season {anime_id} {season} {int(subtitled)} {language} {page}",
        ),
        (
            f"{lang.subtitled_button}: {lang.yes if subtitled else lang.no}",
            f"manage anime {anime_id} {season} {int(not subtitled)} {language} {page}",
        ),
        (
            lang.add_button,
            f"manage episode {anime_id} {season} -1 {int(subtitled)} {language} {page}",
        ),
    ]

    episodes = await Episodes.filter(anime=anime_id,
                                     season=season,
                                     language=language,
                                     subtitled=subtitled)
    episodes = sorted(episodes, key=lambda episode: episode.number)

    if len(episodes) >= 2:
        buttons.append((
            lang.del_season_button,
            f"manage episode delete {anime_id} {season} -1 {int(subtitled)} {language} {page}",
        ))
    else:
        if page > 0:
            page -= 1
            matches = re.search(
                r"(\d+) (\d+) (\d+) (\w+) (\d+)",
                f"{anime_id} {season} {int(subtitled)} {language} {page}",
            )
            callback.matches = [matches]
            await anime_manage(bot, callback)
            return

    buttons.append((
        lang.add_in_batch_button,
        f"manage episode batch {anime_id} {season} {int(subtitled)} {language} {page}",
    ))

    notifications = await Notifications.filter(
        item=anime_id,
        type="anime",
        language=language,
    )
    if len(notifications) > 0:
        buttons.append((
            lang.notify_users_button,
            f"notify episodes {anime_id} {season} {int(subtitled)} {language} {page}",
        ))

    keyboard = array_chunk(buttons, 2)

    layout = Pagination(
        episodes,
        item_data=lambda i, pg:
        f"manage episode {i.anime} {i.season} {i.number} {int(subtitled)} {language} {pg}",
        item_title=lambda i, pg: f"📝 {i.number}",
        page_data=lambda pg:
        f"manage anime {anime_id} {season} {int(subtitled)} {language} {pg}",
    )

    lines = layout.create(page, lines=5, columns=3)

    if len(lines) > 0:
        keyboard += lines

    keyboard.append([(lang.back_button, f"anime {anime_id}")])

    if bool(message.photo):
        await message.edit_text(
            lang.manage_anime_text,
            reply_markup=ikb(keyboard),
        )
    else:
        await callback.edit_message_media(
            InputMediaPhoto(
                f"https://img.anili.st/media/{anime_id}",
                caption=lang.manage_anime_text,
            ),
            reply_markup=ikb(keyboard),
        )
Exemple #27
0
async def anime_episode_edit(bot: Amime, callback: CallbackQuery):
    message = callback.message
    chat = message.chat
    user = callback.from_user
    lang = callback._lang

    item = callback.matches[0].group(1)
    anime_id = int(callback.matches[0].group(2))
    season = int(callback.matches[0].group(3))
    number = int(callback.matches[0].group(4))
    subtitled = bool(int(callback.matches[0].group(5)))
    language = callback.matches[0].group(6)
    page = int(callback.matches[0].group(7))

    episode = EPISODES[str(user.id)][str(anime_id)]

    keyboard = [
        [
            (
                lang.cancel_button,
                f"manage episode {anime_id} {season} {number} {int(subtitled)} {language} {page}",
            ),
        ],
    ]

    await message.edit_text(
        lang.send_me_the_item_text(item=lang.strings[lang.code][item].lower()),
        reply_markup=ikb(keyboard),
    )

    answer = None

    if item == "video":
        while True:
            try:
                answer = await chat.listen(filters.video | filters.document)
            except ListenerCanceled:
                return

            if bool(answer.video):
                duration = answer.video.duration
                if duration <= 30:
                    try:
                        await callback.answer(lang.very_short_video_alert,
                                              show_alert=True)
                        continue
                    except QueryIdInvalid:
                        sent = await answer.reply_text(
                            lang.very_short_video_alert)
                        await asyncio.sleep(3)
                        await sent.delete()
                        continue

                episode["video"] = answer.video
                episode["duration"] = duration // 60
            elif bool(answer.document):
                episode["video"] = answer.document

            if bool(answer.forward_from
                    ) and answer.forward_from.id == bot.me.id:
                episode["update_video"] = False
            else:
                episode["update_video"] = True
            break
    else:
        if item == "number":
            while True:
                try:
                    answer = await chat.listen(filters.text)
                except ListenerCanceled:
                    return

                ep = answer.text.split("-")
                if not int(ep[0]) == number:
                    number = ep[0]

                    if len(ep) > 1:
                        episode["unified_until"] = ep[1]
                    else:
                        episode["unified_until"] = "0"

                    answers = []

                    if bool(await Episodes.get_or_none(
                            anime=anime_id,
                            season=season,
                            number=number,
                            language=language,
                    )):
                        try:
                            await callback.answer(
                                lang.episode_already_exists_alert,
                                show_alert=True)
                        except QueryIdInvalid:
                            sent = await answer.reply_text(
                                lang.episode_already_exists_alert)
                            await asycio.sleep(3)
                            await sent.delete()
                        finally:
                            continue

                        number = answer.text
                        answers.append(answer)

                    for _answer in answers:
                        try:
                            await _answer.delete()
                            await asyncio.sleep(1)
                        except BaseException:
                            pass
                break
        else:
            try:
                answer = await chat.listen(filters.text)
            except ListenerCanceled:
                return

            episode[item] = answer.text

    try:
        await answer.delete()
    except BaseException:
        pass

    EPISODES[str(user.id)][str(anime_id)] = episode

    matches = re.search(
        r"(\d+) (\d+) (\-?\d+) (\d+) (\w+) (\d+)",
        f"{anime_id} {season} {number} {int(subtitled)} {language} {page}",
    )
    callback.matches = [matches]

    await anime_episode(bot, callback)
Exemple #28
0
 async def gc_toggles(c_q: CallbackQuery):
     answer = ""
     alert = False
     to_edit = False
     gc = await get_groupcall(c_q.message.chat.id)
     toggle_type = c_q.matches[0].group(1)
     to_change = c_q.matches[0].group(2)
     cb_text = to_change.title()
     if toggle_type == "rec":
         answer = "Not Implemented yet, 👉😬👈"
         alert = True
         # if to_change == "pause":
         #     gc.pause_recording()
         # elif to_change == "resume":
         #     gc.resume_recording()
         # elif to_change == "restart":
         #     gc.restart_recording()
     elif toggle_type == "plyr":
         if to_change == "playlist":
             buttons = [[InlineKeyboardButton("Back", callback_data="vcbtn_player")]]
             return await c_q.message.edit(
                 gc.get_playlist(),
                 reply_markup=InlineKeyboardMarkup(buttons),
                 disable_web_page_preview=True,
             )
         if to_change == "pause":
             gc.pause_playout()
             answer = f"⏸  {cb_text}d Voice Chat"
         elif to_change == "join":
             await gc.join()
             answer = f"🔌  {cb_text}ed Voice Chat"
         elif to_change == "resume":
             gc.resume_playout()
             answer = f"▶️  {cb_text}d Voice Chat"
         # elif to_change == "restart":
         #     gc.restart_playout()
         elif to_change == "stop":
             answer = f"⏹  {cb_text}ped Voice chat."
             await gc.leave()
         elif to_change == "repeat":
             answer = f"🔁  {cb_text} :  {_parse_arg(gc.replay())}"
         elif to_change == "skip":
             if len(gc.playlist) <= 1:
                 answer = "Nothing Found to Skip, add songs in queue first !"
                 alert = True
             else:
                 to_del = keypath(gc.playlist.pop(0)["id"])
                 await asyncio.gather(c_q.answer("⏭  Song Skipped"), play_now(gc))
                 if os.path.exists(to_del):
                     os.remove(to_del)
                 return
         elif to_change == "clearall":
             gc.playlist.clear()
             answer = "🚮  Playlist Cleared !"
         elif to_change == "shuffle":
             if len(gc.playlist) <= 1:
                 answer = "Nothing Found to Shuffle, add songs in queue first !"
                 alert = True
             else:
                 current = gc.playlist.pop(0)
                 shuffle(gc.playlist)
                 gc.playlist.insert(0, current)
                 answer = "🔀  Playlist Shuffled"
     else:
         to_edit = True
         if match := re.search(r"([0-9.]+)%", c_q.message.text):
             volume = int(float(match.group(1)) * 2)
Exemple #29
0
async def deflang(c: Client, cq: CallbackQuery):
    cq._lang = langs.get_language(os.getenv("LANGUAGE"))
def bypass_invalid_queries(client: TopUpGifter, query: CallbackQuery):
    user_id = str(query.from_user.id)
    user_info = dict(client.users.find_one(id=user_id))
    user = User(user_info)
    query.answer(text=texts['errors']['not_valid_query'][user.language],
                 show_alert=True)