コード例 #1
0
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)
コード例 #2
0
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"))
コード例 #3
0
ファイル: inline_help.py プロジェクト: AmineSoukara/Damien
 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())
         ),
     )
コード例 #4
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}"),
     )
コード例 #5
0
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()
コード例 #6
0
ファイル: settings.py プロジェクト: idokar/TGanonymusChatBot
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()
コード例 #7
0
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()
コード例 #8
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 !"),
     )
コード例 #9
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
コード例 #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),
     )
コード例 #11
0
    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(),
        )
コード例 #12
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!")
コード例 #13
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}"))
コード例 #14
0
async def cb_(client: Client, callback_query: CallbackQuery):
    cb_data = callback_query.data
    msg = callback_query.message
    if not cb_data == "render" or cb_data == "cancel" or cb_data == "statics":
        # cause @Spechide said so
        await client.answer_callback_query(callback_query.id, )
    if cb_data == "render":
        await client.answer_callback_query(callback_query.id,
                                           text="Processing your request..!")
        await primary_task(client, msg)
    elif cb_data == "splits":
        if "PDF" not in msg.reply_markup.inline_keyboard[0][0].text:
            index_number = 1
        current_boolean = msg.reply_markup.inline_keyboard[index_number][0]
        boolean_to_change = ("Split - No" if "Yes" in current_boolean.text else
                             "Split - Yes")
        msg.reply_markup.inline_keyboard[index_number][0][
            "text"] = boolean_to_change
        await msg.edit(text="Choose the prefered settings",
                       reply_markup=msg.reply_markup)

    elif cb_data == "page":
        if "PDF" in msg.reply_markup.inline_keyboard[0][0].text:
            index_number = 1
        else:
            index_number = 2
        current_page = msg.reply_markup.inline_keyboard[index_number][0]
        page_to_change = ("Page - Partial"
                          if "Full" in current_page.text else "Page - Full")
        msg.reply_markup.inline_keyboard[index_number][0][
            "text"] = page_to_change
        await msg.edit(text="Choose the prefered settings",
                       reply_markup=msg.reply_markup)

    elif cb_data == "options":
        current_option = msg.reply_markup.inline_keyboard[-3][0].text
        options_to_change = ("hide additional options ˄"
                             if "show" in current_option else
                             "show additional options ˅")
        if "hide" in options_to_change:
            msg.reply_markup.inline_keyboard.insert(
                -2,
                [
                    InlineKeyboardButton(text="resolution | 800x600",
                                         callback_data="res")
                ],
            )
            msg.reply_markup.inline_keyboard.insert(
                -2,
                [
                    InlineKeyboardButton(text="▫️ site statitics ▫️",
                                         callback_data="statics")
                ],
            )
            if "PDF" in msg.reply_markup.inline_keyboard[0][0].text:
                index_to_change = 2
            else:
                index_to_change = 3
            msg.reply_markup.inline_keyboard[index_to_change][0][
                "text"] = options_to_change
        else:
            for _ in range(2):
                msg.reply_markup.inline_keyboard.pop(-3)
            msg.reply_markup.inline_keyboard[-3][0]["text"] = options_to_change
        await msg.edit(text="Choose the prefered settings",
                       reply_markup=msg.reply_markup)

    elif cb_data == "res":
        current_res = msg.reply_markup.inline_keyboard[-4][0].text
        if "800" in current_res:
            res_to_change = "resolution | 1280x720"
        elif "1280" in current_res:
            # cause asked by <ll>//𝚂𝚊𝚢𝚊𝚗𝚝𝚑//<ll>
            res_to_change = "resolution | 2560x1440"
        elif "2560" in current_res:
            res_to_change = "resolution | 640x480"
        else:
            res_to_change = "resolution | 800x600"
        msg.reply_markup.inline_keyboard[-4][0]["text"] = res_to_change
        await msg.edit(text="Choose the prefered settings",
                       reply_markup=msg.reply_markup)

    elif cb_data == "format":
        current_format = msg.reply_markup.inline_keyboard[0][0]
        if "PDF" in current_format.text:
            format_to_change = "Format - PNG"
        elif "PNG" in current_format.text:
            format_to_change = "Format - JPEG"
        elif "JPEG" in current_format.text:
            format_to_change = "Format - PDF"
        msg.reply_markup.inline_keyboard[0][0]["text"] = format_to_change
        if "PNG" in format_to_change:
            msg.reply_markup.inline_keyboard.insert(1, [
                InlineKeyboardButton(text="Split - No", callback_data="splits")
            ])
        if "PDF" in format_to_change:
            if "Split" in msg.reply_markup.inline_keyboard[1][0].text:
                msg.reply_markup.inline_keyboard.pop(1)
        await msg.edit(text="Choose the prefered settings",
                       reply_markup=msg.reply_markup)

    elif cb_data == "cancel":
        await client.answer_callback_query(callback_query.id,
                                           text="Canceled your request..!")
        await msg.delete()
    elif cb_data == "statics":
        await asyncio.gather(
            callback_query.answer("Processing the website...", ), msg.delete())
        t = await msg.reply_text("<b>processing...</b>")
        try:
            main_paper = await metrics_graber(msg.reply_to_message.text)
            await msg.reply_document(main_paper)
            LOGGER.info("WEB_SCRS --> site_metrics >> request satisfied")
        except Exception as e:
            await msg.reply_text(f"<b>{e}</b>")
            LOGGER.info(f"WEB_SCRS --> site_metrics -> request failed >> {e}")
        finally:
            await t.delete()
    elif cb_data == "deleteno" or cb_data == "deleteyes":
        if cb_data == "deleteno":
            await msg.edit(text="process canceled")
            await asyncio.sleep(2)
            await msg.delete()
        else:
            await msg.edit(text="deleting")
            try:
                shutil.rmtree("./FILES/")
            except Exception as e:
                await msg.edit(text=e)
            finally:
                await asyncio.sleep(2)
                await msg.delete()
    elif cb_data == "about_cb":
        await msg.delete()
        await feedback(client, msg)
コード例 #15
0
def _dummy_btn_handler(_, callback_query: CallbackQuery):
    callback_query.answer()
コード例 #16
0
ファイル: xplayer.py プロジェクト: sddgr807/CustomPluginsForX
 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)
コード例 #17
0
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)
コード例 #18
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)