Просмотр исходного кода

Added inline keyboard support in filters/notes (#104)

* Welcome formatting

* Improved extractor and added parser in filters/notes
Akshay Rajput 5 лет назад
Родитель
Сommit
081373d52f
6 измененных файлов с 99 добавлено и 41 удалено
  1. 4 1
      wbb/core/decorators/permissions.py
  2. 17 5
      wbb/modules/filters.py
  3. 36 34
      wbb/modules/greetings.py
  4. 13 1
      wbb/modules/notes.py
  5. 2 0
      wbb/utils/dbfunctions.py
  6. 27 0
      wbb/utils/functions.py

+ 4 - 1
wbb/core/decorators/permissions.py

@@ -41,7 +41,10 @@ async def authorised(
     except ChatWriteForbidden:
     except ChatWriteForbidden:
         await app.leave_chat(chatID)
         await app.leave_chat(chatID)
     except Exception as e:
     except Exception as e:
-        await message.reply_text(str(e.MESSAGE))
+        try:
+            await message.reply_text(str(e.MESSAGE))
+        except AttributeError:
+            await message.reply_text(str(e))
         e = err()
         e = err()
         print(str(e))
         print(str(e))
     return subFunc2
     return subFunc2

+ 17 - 5
wbb/modules/filters.py

@@ -28,9 +28,11 @@ from pyrogram import filters
 from wbb import app
 from wbb import app
 from wbb.core.decorators.errors import capture_err
 from wbb.core.decorators.errors import capture_err
 from wbb.core.decorators.permissions import adminsOnly
 from wbb.core.decorators.permissions import adminsOnly
+from wbb.core.keyboard import ikb
 from wbb.utils.dbfunctions import (delete_filter, get_filter,
 from wbb.utils.dbfunctions import (delete_filter, get_filter,
                                    get_filters_names, save_filter)
                                    get_filters_names, save_filter)
 from wbb.utils.filter_groups import chat_filters_group
 from wbb.utils.filter_groups import chat_filters_group
+from wbb.utils.functions import extract_text_and_keyb
 
 
 __MODULE__ = "Filters"
 __MODULE__ = "Filters"
 __HELP__ = """/filters To Get All The Filters In The Chat.
 __HELP__ = """/filters To Get All The Filters In The Chat.
@@ -133,20 +135,30 @@ async def filters_re(_, message):
             data_type = _filter["type"]
             data_type = _filter["type"]
             data = _filter["data"]
             data = _filter["data"]
             if data_type == "text":
             if data_type == "text":
+                keyb = None
+                if re.findall(r"\[.+\,.+\]", data):
+                    keyboard = extract_text_and_keyb(ikb, data)
+                    if keyboard:
+                        data, keyb = keyboard
+
                 if message.reply_to_message:
                 if message.reply_to_message:
                     await message.reply_to_message.reply_text(
                     await message.reply_to_message.reply_text(
-                        data, disable_web_page_preview=True
+                        data,
+                        reply_markup=keyb,
+                        disable_web_page_preview=True,
                     )
                     )
-                    if text[0] == "~":
+                    if text.startswith("~"):
                         return await message.delete()
                         return await message.delete()
                     return
                     return
-                await message.reply_text(
-                    data, disable_web_page_preview=True
+                return await message.reply_text(
+                    data,
+                    reply_markup=keyb,
+                    disable_web_page_preview=True,
                 )
                 )
             else:
             else:
                 if message.reply_to_message:
                 if message.reply_to_message:
                     await message.reply_to_message.reply_sticker(data)
                     await message.reply_to_message.reply_sticker(data)
-                    if text[0] == "~":
+                    if text.startswith("~"):
                         return await message.delete()
                         return await message.delete()
                     return
                     return
                 return await message.reply_sticker(data)
                 return await message.reply_sticker(data)

+ 36 - 34
wbb/modules/greetings.py

@@ -31,19 +31,22 @@ from pykeyboard import InlineKeyboard
 from pyrogram import filters
 from pyrogram import filters
 from pyrogram.errors.exceptions.bad_request_400 import (
 from pyrogram.errors.exceptions.bad_request_400 import (
     ChatAdminRequired, UserNotParticipant)
     ChatAdminRequired, UserNotParticipant)
-from pyrogram.types import (ChatPermissions, InlineKeyboardButton,
+from pyrogram.types import (Chat, ChatPermissions,
+                            InlineKeyboardButton,
                             InlineKeyboardMarkup, Message, User)
                             InlineKeyboardMarkup, Message, User)
 
 
 from wbb import SUDOERS, WELCOME_DELAY_KICK_SEC, app
 from wbb import SUDOERS, WELCOME_DELAY_KICK_SEC, app
 from wbb.core.decorators.errors import capture_err
 from wbb.core.decorators.errors import capture_err
 from wbb.core.decorators.permissions import adminsOnly
 from wbb.core.decorators.permissions import adminsOnly
+from wbb.core.keyboard import ikb
 from wbb.utils.dbfunctions import (captcha_off, captcha_on,
 from wbb.utils.dbfunctions import (captcha_off, captcha_on,
                                    del_welcome, get_captcha_cache,
                                    del_welcome, get_captcha_cache,
                                    get_welcome, is_captcha_on,
                                    get_welcome, is_captcha_on,
                                    is_gbanned_user, set_welcome,
                                    is_gbanned_user, set_welcome,
                                    update_captcha_cache)
                                    update_captcha_cache)
 from wbb.utils.filter_groups import welcome_captcha_group
 from wbb.utils.filter_groups import welcome_captcha_group
-from wbb.utils.functions import generate_captcha
+from wbb.utils.functions import (extract_text_and_keyb,
+                                 generate_captcha)
 
 
 __MODULE__ = "Greetings"
 __MODULE__ = "Greetings"
 __HELP__ = """
 __HELP__ = """
@@ -186,41 +189,25 @@ async def welcome(_, message: Message):
         await asyncio.sleep(0.5)
         await asyncio.sleep(0.5)
 
 
 
 
-async def send_welcome_message(callback_query, pending_user_id):
-    try:
-        raw_text = await get_welcome(callback_query.message.chat.id)
-    except TypeError:
-        return
-    raw_text = raw_text.strip().replace("`", "")
+async def send_welcome_message(chat: Chat, user_id: int):
+    raw_text = await get_welcome(chat.id)
+
     if not raw_text:
     if not raw_text:
         return
         return
-    text = raw_text.split("~")[0].strip()
-    buttons_text_list = raw_text.split("~")[1].strip().splitlines()
+
+    text, keyb = extract_text_and_keyb(ikb, raw_text)
+
     if "{chat}" in text:
     if "{chat}" in text:
-        text = text.replace(
-            "{chat}", callback_query.message.chat.title
-        )
+        text = text.replace("{chat}", chat.title)
     if "{name}" in text:
     if "{name}" in text:
         text = text.replace(
         text = text.replace(
-            "{name}", (await app.get_users(pending_user_id)).mention
-        )
-    buttons = InlineKeyboard(row_width=2)
-    list_of_buttons = []
-    for button_string in buttons_text_list:
-        button_string = button_string.strip().split("=")[1].strip()
-        button_string = button_string.replace("[", "").strip()
-        button_string = button_string.replace("]", "").strip()
-        button_string = button_string.split(",")
-        button_text = button_string[0].strip()
-        button_url = button_string[1].strip()
-        list_of_buttons.append(
-            InlineKeyboardButton(text=button_text, url=button_url)
+            "{name}", (await app.get_users(user_id)).mention
         )
         )
-    buttons.add(*list_of_buttons)
+
     await app.send_message(
     await app.send_message(
-        callback_query.message.chat.id,
+        chat.id,
         text=text,
         text=text,
-        reply_markup=buttons,
+        reply_markup=keyb,
         disable_web_page_preview=True,
         disable_web_page_preview=True,
     )
     )
 
 
@@ -291,7 +278,9 @@ async def callback_query_welcome_button(_, callback_query):
                     answers_dicc.remove(ii)
                     answers_dicc.remove(ii)
                     await update_captcha_cache(answers_dicc)
                     await update_captcha_cache(answers_dicc)
         """ send welcome message """
         """ send welcome message """
-        await send_welcome_message(callback_query, pending_user_id)
+        await send_welcome_message(
+            callback_query.message.chat, pending_user_id
+        )
         return
         return
     else:
     else:
         await callback_query.answer("This is not for you")
         await callback_query.answer("This is not for you")
@@ -369,7 +358,11 @@ async def set_welcome_func(_, message):
         await message.reply_text(usage)
         await message.reply_text(usage)
         return
         return
     chat_id = message.chat.id
     chat_id = message.chat.id
-    raw_text = str(message.reply_to_message.text.markdown)
+    raw_text = message.reply_to_message.text.markdown
+    if not (extract_text_and_keyb(ikb, raw_text)):
+        return await message.reply_text(
+            "Wrong formating, check help section."
+        )
     await set_welcome(chat_id, raw_text)
     await set_welcome(chat_id, raw_text)
     await message.reply_text(
     await message.reply_text(
         "Welcome message has been successfully set."
         "Welcome message has been successfully set."
@@ -387,6 +380,15 @@ async def del_welcome_func(_, message):
 @app.on_message(filters.command("get_welcome") & ~filters.private)
 @app.on_message(filters.command("get_welcome") & ~filters.private)
 @adminsOnly("can_change_info")
 @adminsOnly("can_change_info")
 async def get_welcome_func(_, message):
 async def get_welcome_func(_, message):
-    chat_id = message.chat.id
-    welcome_message = await get_welcome(chat_id)
-    await message.reply_text(welcome_message)
+    chat = message.chat
+    welcome = await get_welcome(chat.id)
+    if not welcome:
+        return await message.reply_text("No welcome message set.")
+    if not message.from_user:
+        return await message.reply_text(
+            "You're anon, can't send welcome message."
+        )
+
+    await send_welcome_message(chat, message.from_user.id)
+
+    await message.reply_text(f'`{welcome.replace("`", "")}`')

+ 13 - 1
wbb/modules/notes.py

@@ -21,13 +21,17 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 SOFTWARE.
 SOFTWARE.
 """
 """
+from re import findall
+
 from pyrogram import filters
 from pyrogram import filters
 
 
 from wbb import app
 from wbb import app
 from wbb.core.decorators.errors import capture_err
 from wbb.core.decorators.errors import capture_err
 from wbb.core.decorators.permissions import adminsOnly
 from wbb.core.decorators.permissions import adminsOnly
+from wbb.core.keyboard import ikb
 from wbb.utils.dbfunctions import (delete_note, get_note,
 from wbb.utils.dbfunctions import (delete_note, get_note,
                                    get_note_names, save_note)
                                    get_note_names, save_note)
+from wbb.utils.functions import extract_text_and_keyb
 
 
 __MODULE__ = "Notes"
 __MODULE__ = "Notes"
 __HELP__ = """/notes To Get All The Notes In The Chat.
 __HELP__ = """/notes To Get All The Notes In The Chat.
@@ -101,8 +105,16 @@ async def get_one_note(_, message):
     if not _note:
     if not _note:
         return
         return
     if _note["type"] == "text":
     if _note["type"] == "text":
+        data = _note["data"]
+        keyb = None
+        if findall(r"\[.+\,.+\]", data):
+            keyboard = extract_text_and_keyb(ikb, data)
+            if keyboard:
+                data, keyb = keyboard
         await message.reply_text(
         await message.reply_text(
-            _note["data"], disable_web_page_preview=True
+            data,
+            reply_markup=keyb,
+            disable_web_page_preview=True,
         )
         )
     else:
     else:
         await message.reply_sticker(_note["data"])
         await message.reply_sticker(_note["data"])

+ 2 - 0
wbb/utils/dbfunctions.py

@@ -544,6 +544,8 @@ async def disapprove_pmpermit(user_id: int):
 
 
 async def get_welcome(chat_id: int) -> str:
 async def get_welcome(chat_id: int) -> str:
     text = await welcomedb.find_one({"chat_id": chat_id})
     text = await welcomedb.find_one({"chat_id": chat_id})
+    if not text:
+        return ""
     return text["text"]
     return text["text"]
 
 
 
 

+ 27 - 0
wbb/utils/functions.py

@@ -28,6 +28,7 @@ from math import atan2, cos, radians, sin, sqrt
 from os import execvp
 from os import execvp
 from random import randint
 from random import randint
 from re import findall
 from re import findall
+from re import sub as re_sub
 from sys import executable
 from sys import executable
 from time import time
 from time import time
 
 
@@ -343,3 +344,29 @@ async def get_file_id_from_message(message):
             return
             return
         file_id = message.video.thumbs[0].file_id
         file_id = message.video.thumbs[0].file_id
     return file_id
     return file_id
+
+
+def extract_text_and_keyb(ikb, text: str, row_width: int = 2):
+    keyboard = {}
+    try:
+        text = text.strip()
+        if text.startswith("`"):
+            text = text[1:]
+        if text.endswith("`"):
+            text = text[:-1]
+
+        text, keyb = text.split("~")
+
+        keyb = findall(r"\[.+\,.+\]", keyb)
+        for btn_str in keyb:
+            btn_str = re_sub(r"[\[\]]", "", btn_str)
+            btn_str = btn_str.split(",")
+            btn_txt, btn_url = btn_str[0], btn_str[1].strip()
+
+            if not get_urls_from_text(btn_url):
+                continue
+            keyboard[btn_txt] = btn_url
+        keyboard = ikb(keyboard, row_width)
+    except Exception:
+        return
+    return text, keyboard