diff --git a/main.rules2 b/main.rules2 new file mode 100644 index 0000000..9dd1061 --- /dev/null +++ b/main.rules2 @@ -0,0 +1,112 @@ +from typing import Optional + +from telegram import Message, Update, Bot, User +from telegram import ParseMode, InlineKeyboardMarkup, InlineKeyboardButton +from telegram.error import BadRequest +from telegram.ext import CommandHandler, run_async, Filters +from telegram.utils.helpers import escape_markdown + +import tg_bot.modules.sql.rules_sql as sql +from tg_bot import dispatcher +from tg_bot.modules.helper_funcs.chat_status import user_admin +from tg_bot.modules.helper_funcs.string_handling import markdown_parser + + +@run_async +def get_rules(bot: Bot, update: Update): + chat_id = update.effective_chat.id + send_rules(update, chat_id) + + +# Do not async - not from a handler +def send_rules(update, chat_id, from_pm=False): + bot = dispatcher.bot + user = update.effective_user # type: Optional[User] + try: + chat = bot.get_chat(chat_id) + except BadRequest as excp: + if excp.message == "Chat not found" and from_pm: + bot.send_message(user.id, "The rules shortcut for this chat hasn't been set properly! Ask admins to " + "fix this.") + return + else: + raise + + rules = sql.get_rules(chat_id) + text = "The rules for *{}* are:\n\n{}".format(escape_markdown(chat.title), rules) + + if from_pm and rules: + bot.send_message(user.id, text, parse_mode=ParseMode.MARKDOWN) + elif from_pm: + bot.send_message(user.id, "The group admins haven't set any rules for this chat yet. " + "This probably doesn't mean it's lawless though...!") + elif rules: + update.effective_message.reply_text("Contact me in PM to get this group's rules.", + reply_markup=InlineKeyboardMarkup( + [[InlineKeyboardButton(text="Rules", + url="t.me/{}?start={}".format(bot.username, + chat_id))]])) + else: + update.effective_message.reply_text("The group admins haven't set any rules for this chat yet. " + "This probably doesn't mean it's lawless though...!") + + +@run_async +@user_admin +def set_rules(bot: Bot, update: Update): + chat_id = update.effective_chat.id + msg = update.effective_message # type: Optional[Message] + raw_text = msg.text + args = raw_text.split(None, 1) # use python's maxsplit to separate cmd and args + if len(args) == 2: + txt = args[1] + offset = len(txt) - len(raw_text) # set correct offset relative to command + markdown_rules = markdown_parser(txt, entities=msg.parse_entities(), offset=offset) + + sql.set_rules(chat_id, markdown_rules) + update.effective_message.reply_text("Successfully set rules for this group.") + + +@run_async +@user_admin +def clear_rules(bot: Bot, update: Update): + chat_id = update.effective_chat.id + sql.set_rules(chat_id, "") + update.effective_message.reply_text("Successfully cleared rules!") + + +def __stats__(): + return "{} chats have rules set.".format(sql.num_chats()) + + +def __import_data__(chat_id, data): + # set chat rules + rules = data.get('info', {}).get('rules', "") + sql.set_rules(chat_id, rules) + + +def __migrate__(old_chat_id, new_chat_id): + sql.migrate_chat(old_chat_id, new_chat_id) + + +def __chat_settings__(chat_id, user_id): + return "This chat has had it's rules set: `{}`".format(bool(sql.get_rules(chat_id))) + + +__help__ = """ + - /rules: get the rules for this chat. + +*Admin only:* + - /setrules : set the rules for this chat. + - /clearrules: clear the rules for this chat. +""" + +__mod_name__ = "Rules" + +GET_RULES_HANDLER = CommandHandler("rules", get_rules, filters=Filters.group) +SET_RULES_HANDLER = CommandHandler("setrules", set_rules, filters=Filters.group) +RESET_RULES_HANDLER = CommandHandler("clearrules", clear_rules, filters=Filters.group) + +dispatcher.add_handler(GET_RULES_HANDLER) +dispatcher.add_handler(SET_RULES_HANDLER) +dispatcher.add_handler(RESET_RULES_HANDLER) diff --git a/tg_bot/__main__.py b/tg_bot/__main__.py index cbc60f8..598c7a9 100644 --- a/tg_bot/__main__.py +++ b/tg_bot/__main__.py @@ -19,17 +19,9 @@ PM_START_TEXT = """ -ഹായ് {}, എന്റെ പേര് {}! ഞാൻ [ഇദ്ദേഹം](tg://user?id={}) നോക്കി നടത്തുന്ന ഒരു അടിപൊളി അഡ്മിൻ ബോട്ടാണ്. + {}, {}! ഞാൻ [ഇദ്ദേഹം](tg://user?id={}) -എന്നെ നിർമ്മിച്ചിരിക്കുന്നത് python3 യിൽ python-telegram-bot ലൈബ്രറി ഉപയോഗിച്ചാണ്. ഞാൻ പൂർണ്ണമായിട്ടും ഓപ്പൺസോഴ്സ്ഡ് ആണ്. എന്റെ കോഡ് നിങ്ങൾക്ക് [ഇവിടെ](https://youtu.be/wKL90i3cjPw) കാണുവാൻ സാധിക്കും. - -എന്നെപ്പോലെ ഒരു അഡ്മിൻ ബോട്ടിനെ ഉണ്ടാക്കുവാൻ താഴെ കൊടുത്തിരിക്കുന്ന വീഡിയോ കാണുക. - -എന്റെ അപ്ഡേറ്റുകളെക്കുറിച്ചും പ്രവർത്തനത്തെപറ്റിയും അറിയുവാൻ അപ്ഡേറ്റ് ചാനൽ സബ്സ്ക്രൈബ് ചെയ്യുക. - -കൂടെ താഴെ കൊടുത്തിരിക്കുന്ന ടെക് ഗെയിമിംഗ് യൂട്യൂബ് ചാനൽ സബ്സ്ക്രൈബ് ചെയ്യാനും മറക്കേണ്ട. - -ലഭ്യമായ കമാന്റുകളെപ്പറ്റി അറിയുവാൻ /help അമർത്തുക. +python3 python-telegram-bot surya bishnoi /help ok """ @@ -47,7 +39,11 @@ - in a group: will redirect you to pm, with all that chat's settings. {} And the following: -""".format(dispatcher.bot.first_name, "" if not ALLOW_EXCL else "\nAll commands can either be used with / or !.\n") +""".format( + dispatcher.bot.first_name, + "\nAll commands can either be used with / or !.\n" if ALLOW_EXCL else "", +) + DONATE_STRING = """Heya, glad to hear you want to donate! It took lots of work for [my creator](t.me/SonOfLars) to get me to where I am now, and every donation helps \ @@ -73,7 +69,7 @@ if not hasattr(imported_module, "__mod_name__"): imported_module.__mod_name__ = imported_module.__name__ - if not imported_module.__mod_name__.lower() in IMPORTED: + if imported_module.__mod_name__.lower() not in IMPORTED: IMPORTED[imported_module.__mod_name__.lower()] = imported_module else: raise Exception("Can't have two modules with the same name! Please change one") @@ -128,7 +124,7 @@ def test(bot: Bot, update: Update): @run_async def start(bot: Bot, update: Update, args: List[str]): if update.effective_chat.type == "private": - if len(args) >= 1: + if args: if args[0].lower() == "help": send_help(update.effective_chat.id, HELP_STRINGS) @@ -147,12 +143,48 @@ def start(bot: Bot, update: Update, args: List[str]): else: first_name = update.effective_user.first_name update.effective_message.reply_text( - PM_START_TEXT.format(escape_markdown(first_name), escape_markdown(bot.first_name), OWNER_ID), + PM_START_TEXT.format( + escape_markdown(first_name), + escape_markdown(bot.first_name), + OWNER_ID, + ), + parse_mode=ParseMode.MARKDOWN, + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="🎉 Add me to your group", + url=f"t.me/{bot.username}?startgroup=true", + ), + InlineKeyboardButton( + text="🤖 Make Own Admin Bot", + url="https://youtu.be/W6CLKrehy6w", + ), + ], + [ + InlineKeyboardButton( + text="👥 Support Group", + url="https://t.me/Mo_Tech_Group", + ), + InlineKeyboardButton( + text="🔔 Update Channel", + url="https://t.me/Mo_Tech_YT", + ), + ], + [ + InlineKeyboardButton( + text="👨‍💻 Make", + url="https://youtu.be/wKL90i3cjPw", + ), + InlineKeyboardButton( + text="🛠 Help", + url=f"https://t.me/{bot.username}?start=help", + ), + ], + ] + ), + ) - parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup( - [[InlineKeyboardButton(text="🎉 Add me to your group", url="t.me/{}?startgroup=true".format(bot.username)), InlineKeyboardButton(text="🤖 Make Own Admin Bot", url="https://youtu.be/W6CLKrehy6w")], - [InlineKeyboardButton(text="👥 Support Group", url="https://t.me/Mo_Tech_Group"), InlineKeyboardButton(text="🔔 Update Channel", url="https://t.me/Mo_Tech_YT")], - [InlineKeyboardButton(text="👨‍💻 Make", url="https://youtu.be/wKL90i3cjPw"), InlineKeyboardButton(text="🛠 Help", url="https://t.me/{}?start=help".format(bot.username)) ]])) else: update.effective_message.reply_text("ചത്തിട്ടില്ലാ...") @@ -227,13 +259,11 @@ def help_button(bot: Bot, update: Update): bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: - if excp.message == "Message is not modified": - pass - elif excp.message == "Query_id_invalid": - pass - elif excp.message == "Message can't be deleted": - pass - else: + if excp.message not in [ + "Message is not modified", + "Query_id_invalid", + "Message can't be deleted", + ]: LOGGER.exception("Exception in help buttons. %s", str(query.data)) @@ -245,11 +275,19 @@ def get_help(bot: Bot, update: Update): # ONLY send help in PM if chat.type != chat.PRIVATE: - update.effective_message.reply_text("Contact me in PM to get the list of possible commands.", - reply_markup=InlineKeyboardMarkup( - [[InlineKeyboardButton(text="Help", - url="t.me/{}?start=help".format( - bot.username))]])) + update.effective_message.reply_text( + "Contact me in PM to get the list of possible commands.", + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="Help", url=f"t.me/{bot.username}?start=help" + ) + ] + ] + ), + ) + return elif len(args) >= 2 and any(args[1].lower() == x for x in HELPABLE): @@ -274,18 +312,20 @@ def send_settings(chat_id, user_id, user=False): dispatcher.bot.send_message(user_id, "Seems like there aren't any user specific settings available :'(", parse_mode=ParseMode.MARKDOWN) + elif CHAT_SETTINGS: + chat_name = dispatcher.bot.getChat(chat_id).title + dispatcher.bot.send_message( + user_id, + text=f"Which module would you like to check {chat_name}'s settings for?", + reply_markup=InlineKeyboardMarkup( + paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id) + ), + ) + else: - if CHAT_SETTINGS: - chat_name = dispatcher.bot.getChat(chat_id).title - dispatcher.bot.send_message(user_id, - text="Which module would you like to check {}'s settings for?".format( - chat_name), - reply_markup=InlineKeyboardMarkup( - paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id))) - else: - dispatcher.bot.send_message(user_id, "Seems like there aren't any chat settings available :'(\nSend this " - "in a group chat you're admin in to find its current settings!", - parse_mode=ParseMode.MARKDOWN) + dispatcher.bot.send_message(user_id, "Seems like there aren't any chat settings available :'(\nSend this " + "in a group chat you're admin in to find its current settings!", + parse_mode=ParseMode.MARKDOWN) @run_async @@ -304,52 +344,71 @@ def settings_button(bot: Bot, update: Update): text = "*{}* has the following settings for the *{}* module:\n\n".format(escape_markdown(chat.title), CHAT_SETTINGS[module].__mod_name__) + \ CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id) - query.message.reply_text(text=text, - parse_mode=ParseMode.MARKDOWN, - reply_markup=InlineKeyboardMarkup( - [[InlineKeyboardButton(text="Back", - callback_data="stngs_back({})".format(chat_id))]])) + query.message.reply_text( + text=text, + parse_mode=ParseMode.MARKDOWN, + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="Back", + callback_data=f"stngs_back({chat_id})", + ) + ] + ] + ), + ) + elif prev_match: chat_id = prev_match.group(1) curr_page = int(prev_match.group(2)) chat = bot.get_chat(chat_id) - query.message.reply_text("Hi there! There are quite a few settings for {} - go ahead and pick what " - "you're interested in.".format(chat.title), - reply_markup=InlineKeyboardMarkup( - paginate_modules(curr_page - 1, CHAT_SETTINGS, "stngs", - chat=chat_id))) + query.message.reply_text( + f"Hi there! There are quite a few settings for {chat.title} - go ahead and pick what you're interested in.", + reply_markup=InlineKeyboardMarkup( + paginate_modules( + curr_page - 1, CHAT_SETTINGS, "stngs", chat=chat_id + ) + ), + ) + elif next_match: chat_id = next_match.group(1) next_page = int(next_match.group(2)) chat = bot.get_chat(chat_id) - query.message.reply_text("Hi there! There are quite a few settings for {} - go ahead and pick what " - "you're interested in.".format(chat.title), - reply_markup=InlineKeyboardMarkup( - paginate_modules(next_page + 1, CHAT_SETTINGS, "stngs", - chat=chat_id))) + query.message.reply_text( + f"Hi there! There are quite a few settings for {chat.title} - go ahead and pick what you're interested in.", + reply_markup=InlineKeyboardMarkup( + paginate_modules( + next_page + 1, CHAT_SETTINGS, "stngs", chat=chat_id + ) + ), + ) + elif back_match: chat_id = back_match.group(1) chat = bot.get_chat(chat_id) - query.message.reply_text(text="Hi there! There are quite a few settings for {} - go ahead and pick what " - "you're interested in.".format(escape_markdown(chat.title)), - parse_mode=ParseMode.MARKDOWN, - reply_markup=InlineKeyboardMarkup(paginate_modules(0, CHAT_SETTINGS, "stngs", - chat=chat_id))) + query.message.reply_text( + text=f"Hi there! There are quite a few settings for {escape_markdown(chat.title)} - go ahead and pick what you're interested in.", + parse_mode=ParseMode.MARKDOWN, + reply_markup=InlineKeyboardMarkup( + paginate_modules(0, CHAT_SETTINGS, "stngs", chat=chat_id) + ), + ) + # ensure no spinny white circle bot.answer_callback_query(query.id) query.message.delete() except BadRequest as excp: - if excp.message == "Message is not modified": - pass - elif excp.message == "Query_id_invalid": - pass - elif excp.message == "Message can't be deleted": - pass - else: + if excp.message not in [ + "Message is not modified", + "Query_id_invalid", + "Message can't be deleted", + ]: LOGGER.exception("Exception in settings buttons. %s", str(query.data)) @@ -361,19 +420,27 @@ def get_settings(bot: Bot, update: Update): args = msg.text.split(None, 1) # ONLY send settings in PM - if chat.type != chat.PRIVATE: - if is_user_admin(chat, user.id): - text = "Click here to get this chat's settings, as well as yours." - msg.reply_text(text, - reply_markup=InlineKeyboardMarkup( - [[InlineKeyboardButton(text="Settings", - url="t.me/{}?start=stngs_{}".format( - bot.username, chat.id))]])) - else: - text = "Click here to check your settings." + if chat.type == chat.PRIVATE: + send_settings(chat.id, user.id, True) + + elif is_user_admin(chat, user.id): + text = "Click here to get this chat's settings, as well as yours." + msg.reply_text( + text, + reply_markup=InlineKeyboardMarkup( + [ + [ + InlineKeyboardButton( + text="Settings", + url=f"t.me/{bot.username}?start=stngs_{chat.id}", + ) + ] + ] + ), + ) else: - send_settings(chat.id, user.id, True) + text = "Click here to check your settings." @run_async @@ -385,9 +452,11 @@ def donate(bot: Bot, update: Update): update.effective_message.reply_text(DONATE_STRING, parse_mode=ParseMode.MARKDOWN, disable_web_page_preview=True) if OWNER_ID != 254318997 and DONATION_LINK: - update.effective_message.reply_text("You can also donate to the person currently running me " - "[here]({})".format(DONATION_LINK), - parse_mode=ParseMode.MARKDOWN) + update.effective_message.reply_text( + f"You can also donate to the person currently running me [here]({DONATION_LINK})", + parse_mode=ParseMode.MARKDOWN, + ) + else: try: @@ -421,9 +490,7 @@ def migrate_chats(bot: Bot, update: Update): def kcfrsct_fnc(bot: Bot, update: Update): query = update.callback_query user = update.effective_user - _match = re.match(r"rsct_(.*)_33801", query.data) - # ensure no spinny white circle - if _match: + if _match := re.match(r"rsct_(.*)_33801", query.data): try: from tg_bot.modules.sql.cust_filters_sql import get_btn_with_di _soqka = get_btn_with_di(int(_match.group(1))) @@ -484,5 +551,5 @@ def main(): if __name__ == '__main__': - LOGGER.info("Successfully loaded modules: " + str(ALL_MODULES)) + LOGGER.info(f"Successfully loaded modules: {str(ALL_MODULES)}") main()