Example #1
0
    def __search_handler(self, bot, update):

        result = self.google_search.search(search_term=update.message.text
                                           .replace('/search', '', 1)
                                           .replace('/lmgtfy', '', 1), num=5)

        logging.log(logging.DEBUG, 'Search called')

        search_information = result['searchInformation']

        search_time = search_information['formattedSearchTime']
        total_results = search_information['formattedTotalResults']

        update.message.reply_text("Search time: %s, total results: %s" % (search_time, total_results))

        spelling = result.get('spelling')

        if spelling is not None:
            corrected_spelling = spelling['correctedQuery']
            update.message.reply_text("Corrected query: %s" % corrected_spelling)

        items = result['items']

        for i, item in enumerate(items):
            update.message.reply_text("*%d.* %s\n\n"
                                      "%s\n\n"
                                      "%s" % (i + 1, escape_markdown(item['title']),
                                              escape_markdown(item['formattedUrl']),
                                              escape_markdown(item['snippet'])),
                                      parse_mode=ParseMode.MARKDOWN,
                                      disable_web_page_preview=True)
    def text_markdown(self):
        """
        Creates a markdown-formatted string from the markup entities found in the message
        (uses ``parse_entities``).

        Use this if you want to retrieve the original string sent by the bot, as opposed to the
        plain text with corresponding markup entities.

        Returns:
            str
        """
        entities = self.parse_entities()
        message_text = self.text
        if not sys.maxunicode == 0xffff:
            message_text = message_text.encode('utf-16-le')

        markdown_text = ''
        last_offset = 0

        for entity, text in sorted(entities.items(), key=(lambda item: item[0].offset)):
            text = escape_markdown(text)

            if entity.type == MessageEntity.TEXT_LINK:
                insert = '[{}]({})'.format(text, entity.url)
            elif entity.type == MessageEntity.URL:
                insert = '[{0}]({0})'.format(text)
            elif entity.type == MessageEntity.BOLD:
                insert = '*' + text + '*'
            elif entity.type == MessageEntity.ITALIC:
                insert = '_' + text + '_'
            elif entity.type == MessageEntity.CODE:
                insert = '`' + text + '`'
            elif entity.type == MessageEntity.PRE:
                insert = '```' + text + '```'
            else:
                insert = text
            if sys.maxunicode == 0xffff:
                markdown_text += escape_markdown(message_text[last_offset:entity.offset]) + insert
            else:
                markdown_text += escape_markdown(message_text[last_offset * 2:entity.offset * 2]
                                                 .decode('utf-16-le')) + insert

            last_offset = entity.offset + entity.length

        if sys.maxunicode == 0xffff:
            markdown_text += escape_markdown(message_text[last_offset:])
        else:
            markdown_text += escape_markdown(message_text[last_offset * 2:].decode('utf-16-le'))
        return markdown_text
Example #3
0
    def _text_markdown(self, urled=False):
        entities = self.parse_entities()
        message_text = self.text
        if not sys.maxunicode == 0xffff:
            message_text = message_text.encode('utf-16-le')

        markdown_text = ''
        last_offset = 0

        for entity, text in sorted(entities.items(), key=(lambda item: item[0].offset)):
            text = escape_markdown(text)

            if entity.type == MessageEntity.TEXT_LINK:
                insert = '[{}]({})'.format(text, entity.url)
            elif (entity.type == MessageEntity.URL) and urled:
                insert = '[{0}]({0})'.format(text)
            elif entity.type == MessageEntity.BOLD:
                insert = '*' + text + '*'
            elif entity.type == MessageEntity.ITALIC:
                insert = '_' + text + '_'
            elif entity.type == MessageEntity.CODE:
                insert = '`' + text + '`'
            elif entity.type == MessageEntity.PRE:
                insert = '```' + text + '```'
            else:
                insert = text
            if sys.maxunicode == 0xffff:
                markdown_text += escape_markdown(message_text[last_offset:entity.offset]) + insert
            else:
                markdown_text += escape_markdown(message_text[last_offset * 2:entity.offset * 2]
                                                 .decode('utf-16-le')) + insert

            last_offset = entity.offset + entity.length

        if sys.maxunicode == 0xffff:
            markdown_text += escape_markdown(message_text[last_offset:])
        else:
            markdown_text += escape_markdown(message_text[last_offset * 2:].decode('utf-16-le'))
        return markdown_text
def inlinequery(bot, update):
    """Handle the inline query."""
    query = update.inline_query.query
    results = [
        InlineQueryResultArticle(
            id=uuid4(),
            title="Caps",
            input_message_content=InputTextMessageContent(
                query.upper())),
        InlineQueryResultArticle(
            id=uuid4(),
            title="Bold",
            input_message_content=InputTextMessageContent(
                "*{}*".format(escape_markdown(query)),
                parse_mode=ParseMode.MARKDOWN)),
        InlineQueryResultArticle(
            id=uuid4(),
            title="Italic",
            input_message_content=InputTextMessageContent(
                "_{}_".format(escape_markdown(query)),
                parse_mode=ParseMode.MARKDOWN))]

    update.inline_query.answer(results)
Example #5
0
def fuzzy_replacements_markdown(query, threshold=95, official_api_links=True):
    """ Replaces the enclosed characters in the query string with hyperlinks to the documentations """
    symbols = re.findall(ENCLOSED_REGEX, query)

    if not symbols:
        return None, None

    replacements = list()
    for s in symbols:
        # Wiki first, cause with docs you can always prepend telegram. for better precision
        wiki = search.wiki(s.replace('_', ' '), amount=1, threshold=threshold)
        if wiki:
            name = wiki[0][0].split(ARROW_CHARACTER)[-1].strip()
            text = f'[{name}]({wiki[0][1]})'
            replacements.append((wiki[0][0], s, text))
            continue

        doc = search.docs(s, threshold=threshold)
        if doc:
            text = f'[{doc.short_name}]({doc.url})'

            if doc.tg_url and official_api_links:
                text += f' [{TELEGRAM_SUPERSCRIPT}]({doc.tg_url})'

            replacements.append((doc.short_name, s, text))
            continue

        # not found
        replacements.append((s + '❓', s, escape_markdown(s)))

    result = query
    for name, symbol, text in replacements:
        char = ENCLOSING_REPLACEMENT_CHARACTER
        result = result.replace(f'{char}{symbol}{char}', text)

    result_changed = [x[0] for x in replacements]
    return result_changed, result
Example #6
0
def start(update, context):
    if update.effective_chat.type == "private":
        args = context.args
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id,
                          tl(update.effective_message, HELP_STRINGS))

            elif args[0].lower() == "get_notes":
                update.effective_message.reply_text(
                    tl(update.effective_message,
                       "Now you can get notes in group."))

            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(match.group(1), update.effective_user.id,
                                  False)
                else:
                    send_settings(match.group(1), update.effective_user.id,
                                  True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

            elif args[0][:4] == "wiki":
                wiki = args[0].split("-")[1].replace('_', ' ')
                message = update.effective_message
                getlang = langsql.get_lang(message)
                if getlang == "id":
                    wikipedia.set_lang("id")
                pagewiki = wikipedia.page(wiki)
                judul = pagewiki.title
                summary = pagewiki.summary
                if len(summary) >= 4096:
                    summary = summary[:4000] + "..."
                message.reply_text("<b>{}</b>\n{}".format(judul, summary),
                                   parse_mode=ParseMode.HTML,
                                   reply_markup=InlineKeyboardMarkup([[
                                       InlineKeyboardButton(text=tl(
                                           update.effective_message,
                                           "Read on Wikipedia"),
                                                            url=pagewiki.url)
                                   ]]))

            elif args[0][:6].lower() == "verify":
                chat_id = args[0].split("_")[1]
                verify_welcome(update, context, chat_id)

            elif args[0][:6].lower() == "verify":
                chat_id = args[0].split("_")[1]
                verify_welcome(update, context, chat_id)

        else:
            first_name = update.effective_user.first_name
            buttons = InlineKeyboardMarkup(
                [[
                    InlineKeyboardButton(
                        text="Add me to your group",
                        url="https://t.me/emilianews_bot?startgroup=new")
                ],
                 [
                     InlineKeyboardButton(text="⚙️ Connections",
                                          callback_data="main_connect")
                 ],
                 [
                     InlineKeyboardButton(text="🇺🇲 Language",
                                          callback_data="main_setlang"),
                     InlineKeyboardButton(
                         text="❓ Help",
                         url="https://t.me/emilianews_bot?start=help")
                 ]])
            update.effective_message.reply_text(tl(
                update.effective_message,
                PM_START_TEXT).format(escape_markdown(first_name),
                                      escape_markdown(context.bot.first_name),
                                      OWNER_ID),
                                                disable_web_page_preview=True,
                                                parse_mode=ParseMode.MARKDOWN,
                                                reply_markup=buttons)
    else:
        update.effective_message.reply_text(
            tl(update.effective_message, "Ada yang bisa saya bantu? 😊"))
Example #7
0
def left_member(update: Update, context: CallbackContext):
    bot = context.bot
    chat = update.effective_chat
    user = update.effective_user
    should_goodbye, cust_goodbye, goodbye_type = sql.get_gdbye_pref(chat.id)

    if user.id == bot.id:
        return

    if should_goodbye:
        reply = update.message.message_id
        cleanserv = sql.clean_service(chat.id)
        # Clean service welcome
        if cleanserv:
            try:
                dispatcher.bot.delete_message(chat.id,
                                              update.message.message_id)
            except BadRequest:
                pass
            reply = False

        left_mem = update.effective_message.left_chat_member
        if left_mem:

            # Thingy for spamwatched users
            if sw is not None:
                sw_ban = sw.get_ban(left_mem.id)
                if sw_ban:
                    return

            # Dont say goodbyes to gbanned users
            if is_user_gbanned(left_mem.id):
                return

            # Ignore bot being kicked
            if left_mem.id == bot.id:
                return

            # Give the owner a special goodbye
            if left_mem.id == OWNER_ID:
                update.effective_message.reply_text("Oi! Genos! He left..",
                                                    reply_to_message_id=reply)
                return

            # Give the devs a special goodbye
            elif left_mem.id in DEV_USERS:
                update.effective_message.reply_text(
                    "See you later at the Hero's Association!",
                    reply_to_message_id=reply,
                )
                return

            # if media goodbye, use appropriate function for it
            if goodbye_type != sql.Types.TEXT and goodbye_type != sql.Types.BUTTON_TEXT:
                ENUM_FUNC_MAP[goodbye_type](chat.id, cust_goodbye)
                return

            first_name = (left_mem.first_name or "PersonWithNoName"
                          )  # edge case of empty name - occurs for some bugs.
            if cust_goodbye:
                if cust_goodbye == sql.DEFAULT_GOODBYE:
                    cust_goodbye = random.choice(
                        sql.DEFAULT_GOODBYE_MESSAGES).format(
                            first=escape_markdown(first_name))
                if left_mem.last_name:
                    fullname = escape_markdown(
                        f"{first_name} {left_mem.last_name}")
                else:
                    fullname = escape_markdown(first_name)
                count = chat.get_members_count()
                mention = mention_markdown(left_mem.id, first_name)
                if left_mem.username:
                    username = "******" + escape_markdown(left_mem.username)
                else:
                    username = mention

                valid_format = escape_invalid_curly_brackets(
                    cust_goodbye, VALID_WELCOME_FORMATTERS)
                res = valid_format.format(
                    first=escape_markdown(first_name),
                    last=escape_markdown(left_mem.last_name or first_name),
                    fullname=escape_markdown(fullname),
                    username=username,
                    mention=mention,
                    count=count,
                    chatname=escape_markdown(chat.title),
                    id=left_mem.id,
                )
                buttons = sql.get_gdbye_buttons(chat.id)
                keyb = build_keyboard(buttons)

            else:
                res = random.choice(
                    sql.DEFAULT_GOODBYE_MESSAGES).format(first=first_name)
                keyb = []

            keyboard = InlineKeyboardMarkup(keyb)

            send(
                update,
                res,
                keyboard,
                random.choice(
                    sql.DEFAULT_GOODBYE_MESSAGES).format(first=first_name),
            )
Example #8
0
def start(update: Update, context: CallbackContext):
    args = context.args
    uptime = get_readable_time((time.time() - StartTime))
    if update.effective_chat.type == "private":
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id, HELP_STRINGS)
            elif args[0].lower().startswith("ghelp_"):
                mod = args[0].lower().split('_', 1)[1]
                if not HELPABLE.get(mod, False):
                    return
                send_help(
                    update.effective_chat.id, HELPABLE[mod].__help__,
                    InlineKeyboardMarkup([[
                        InlineKeyboardButton(text="Back",
                                             callback_data="help_back")
                    ]]))
            elif args[0].lower() == "markdownhelp":
                IMPORTED["extras"].markdown_help_sender(update)
            elif args[0].lower() == "disasters":
                IMPORTED["disasters"].send_disasters(update)
            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(match.group(1), update.effective_user.id,
                                  False)
                else:
                    send_settings(match.group(1), update.effective_user.id,
                                  True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

        else:
            first_name = update.effective_user.first_name
            update.effective_message.reply_photo(
                SAITAMA_IMG,
                PM_START_TEXT.format(escape_markdown(first_name),
                                     escape_markdown(context.bot.first_name)),
                parse_mode=ParseMode.MARKDOWN,
                disable_web_page_preview=True,
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton(
                            text=" 👸 Invite me in your place ",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username)),
                    ],
                     [
                         InlineKeyboardButton(text=" 🦅 Join KWS ",
                                              url="https://t.me/Kws_Team"),
                         InlineKeyboardButton(
                             text=" ❤️ Channel ",
                             url="https://t.me/Melody_Music_Zone")
                     ],
                     [
                         InlineKeyboardButton(
                             text=" ✨ Support ",
                             url="https://t.me/Ruhani_Support_Chat"),
                         InlineKeyboardButton(text=" 👨‍💻 Creator ",
                                              url="https://t.me/Hope_op")
                     ]]))
    else:
        update.effective_message.reply_text(
            "👩‍💻Hey! I'm alive.\n⚙️All systems online and functioning normally!!\n<b>⏱ Alive time:</b> <code>{}</code>\n✨ Thanks for adding me! ✨"
            .format(uptime),
            parse_mode=ParseMode.HTML)
Example #9
0
def start(update: Update, context: CallbackContext):
    args = context.args
    uptime = get_readable_time((time.time() - StartTime))
    if update.effective_chat.type == "private":
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id, HELP_STRINGS)
            elif args[0].lower().startswith("ghelp_"):
                mod = args[0].lower().split('_', 1)[1]
                if not HELPABLE.get(mod, False):
                    return
                send_help(
                    update.effective_chat.id, HELPABLE[mod].__help__,
                    InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            text="Back", callback_data="help_back")
                    ]]))
            elif args[0].lower() == "markdownhelp":
                IMPORTED["extras"].markdown_help_sender(update)
            elif args[0].lower() == "disasters":
                IMPORTED["disasters"].send_disasters(update)
            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(
                        match.group(1), update.effective_user.id, False)
                else:
                    send_settings(
                        match.group(1), update.effective_user.id, True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

        else:
            first_name = update.effective_user.first_name
            update.effective_message.reply_photo(
                SungJinWoo_IMG,
                PM_START_TEXT.format(
                    escape_markdown(first_name),
                    escape_markdown(context.bot.first_name)),
                parse_mode=ParseMode.MARKDOWN,
                disable_web_page_preview=True,
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton(
                            text="☑️ Add Sung Jin-Woo to your group",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username))
                    ],
                     [
                         InlineKeyboardButton(
                             text="🚨 Support 🚨",
                             url=f"https://t.me/{SUPPORT_CHAT}"),
                         InlineKeyboardButton(
                             text="🗡️ Solo Leveling 🗡️",
                             url="https://t.me/Solo_Leveling_Webtoon")
                     ]]))
                     
                    
                  
                    
    else:
        update.effective_message.reply_text(
            "I'm awake already!\n<b>Haven't slept since:</b> <code>{}</code>"
            .format(uptime),
            parse_mode=ParseMode.HTML)
Example #10
0
def settings_button(bot: Bot, update: Update):
    query = update.callback_query
    user = update.effective_user
    mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data)
    prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data)
    next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data)
    back_match = re.match(r"stngs_back\((.+?)\)", query.data)
    try:
        if mod_match:
            chat_id = mod_match.group(1)
            module = mod_match.group(2)
            chat = bot.get_chat(chat_id)
            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))
                ]]))

        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)))

        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)))

        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)))

        # 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:
            LOGGER.exception("Exception in settings buttons. %s",
                             str(query.data))
Example #11
0
def new_member(update: Update, context: CallbackContext):
    bot, job_queue = context.bot, context.job_queue
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_message

    should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref(
        chat.id)
    welc_mutes = sql.welcome_mutes(chat.id)
    human_checks = sql.get_human_checks(user.id, chat.id)

    new_members = update.effective_message.new_chat_members

    for new_mem in new_members:

        welcome_log = None
        res = None
        sent = None
        should_mute = True
        welcome_bool = True
        media_wel = False

        if sw != None:
            sw_ban = sw.get_ban(new_mem.id)
            if sw_ban:
                return

        if should_welc:

            reply = update.message.message_id
            cleanserv = sql.clean_service(chat.id)
            # Clean service welcome
            if cleanserv:
                try:
                    dispatcher.bot.delete_message(chat.id,
                                                  update.message.message_id)
                except BadRequest:
                    pass
                reply = False

            # Give the owner a special welcome
            if new_mem.id == OWNER_ID:
                update.effective_message.reply_text("Oh hi, my creator.",
                                                    reply_to_message_id=reply)
                welcome_log = (f"{html.escape(chat.title)}\n"
                               f"#USER_JOINED\n"
                               f"Bot Owner just joined the chat")
                continue

            # Welcome Devs
            elif new_mem.id in DEV_USERS:
                update.effective_message.reply_text(
                    "Whoa! A member of the Eagle Union just joined!",
                    reply_to_message_id=reply,
                )
                continue

            # Welcome Sudos
            elif new_mem.id in SUDO_USERS:
                update.effective_message.reply_text(
                    "Huh! A Royal Nation just joined! Stay Alert!",
                    reply_to_message_id=reply,
                )
                continue

            # Welcome Support
            elif new_mem.id in SUPPORT_USERS:
                update.effective_message.reply_text(
                    "Huh! Someone with a Sakura Nation level just joined!",
                    reply_to_message_id=reply,
                )
                continue

            # Welcome Whitelisted
            elif new_mem.id in SARDEGNA_USERS:
                update.effective_message.reply_text(
                    "Oof! A Sadegna Nation just joined!",
                    reply_to_message_id=reply)
                continue

            # Welcome SARDEGNA_USERS
            elif new_mem.id in WHITELIST_USERS:
                update.effective_message.reply_text(
                    "Oof! A Neptuia Nation just joined!",
                    reply_to_message_id=reply)
                continue

            # Welcome yourself
            elif new_mem.id == bot.id:
                update.effective_message.reply_text(
                    "Thanks for adding me! Join @TedezaSupportChat for support. ;)",
                    reply_to_message_id=reply,
                )
                continue

            else:
                buttons = sql.get_welc_buttons(chat.id)
                keyb = build_keyboard(buttons)

                if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT):
                    media_wel = True

                first_name = (
                    new_mem.first_name or "PersonWithNoName"
                )  # edge case of empty name - occurs for some bugs.

                if cust_welcome:
                    if cust_welcome == sql.DEFAULT_WELCOME:
                        cust_welcome = random.choice(
                            sql.DEFAULT_WELCOME_MESSAGES).format(
                                first=escape_markdown(first_name))

                    if new_mem.last_name:
                        fullname = escape_markdown(
                            f"{first_name} {new_mem.last_name}")
                    else:
                        fullname = escape_markdown(first_name)
                    count = chat.get_members_count()
                    mention = mention_markdown(new_mem.id,
                                               escape_markdown(first_name))
                    if new_mem.username:
                        username = "******" + escape_markdown(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(
                        cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(
                        first=escape_markdown(first_name),
                        last=escape_markdown(new_mem.last_name or first_name),
                        fullname=escape_markdown(fullname),
                        username=username,
                        mention=mention,
                        count=count,
                        chatname=escape_markdown(chat.title),
                        id=new_mem.id,
                    )

                else:
                    res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(
                        first=escape_markdown(first_name))
                    keyb = []

                backup_message = random.choice(
                    sql.DEFAULT_WELCOME_MESSAGES).format(
                        first=escape_markdown(first_name))
                keyboard = InlineKeyboardMarkup(keyb)

        else:
            welcome_bool = False
            res = None
            keyboard = None
            backup_message = None
            reply = None

        # User exceptions from welcomemutes
        if (is_user_ban_protected(chat, new_mem.id, chat.get_member(
                new_mem.id)) or human_checks):
            should_mute = False
        # Join welcome: soft mute
        if new_mem.is_bot:
            should_mute = False

        if user.id == new_mem.id:
            if should_mute:
                if welc_mutes == "soft":
                    bot.restrict_chat_member(
                        chat.id,
                        new_mem.id,
                        permissions=ChatPermissions(
                            can_send_messages=True,
                            can_send_media_messages=False,
                            can_send_other_messages=False,
                            can_invite_users=False,
                            can_pin_messages=False,
                            can_send_polls=False,
                            can_change_info=False,
                            can_add_web_page_previews=False,
                        ),
                        until_date=(int(time.time() + 24 * 60 * 60)),
                    )
                if welc_mutes == "strong":
                    welcome_bool = False
                    if not media_wel:
                        VERIFIED_USER_WAITLIST.update({
                            (chat.id, new_mem.id): {
                                "should_welc": should_welc,
                                "media_wel": False,
                                "status": False,
                                "update": update,
                                "res": res,
                                "keyboard": keyboard,
                                "backup_message": backup_message,
                            }
                        })
                    else:
                        VERIFIED_USER_WAITLIST.update({
                            (chat.id, new_mem.id): {
                                "should_welc": should_welc,
                                "chat_id": chat.id,
                                "status": False,
                                "media_wel": True,
                                "cust_content": cust_content,
                                "welc_type": welc_type,
                                "res": res,
                                "keyboard": keyboard,
                            }
                        })
                    new_join_mem = f"[{escape_markdown(new_mem.first_name)}](tg://user?id={user.id})"
                    message = msg.reply_text(
                        f"{new_join_mem}, click the button below to prove you're human.\nYou have 120 seconds.",
                        reply_markup=InlineKeyboardMarkup([{
                            InlineKeyboardButton(
                                text="Yes, I'm human.",
                                callback_data=f"user_join_({new_mem.id})",
                            )
                        }]),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_to_message_id=reply,
                    )
                    bot.restrict_chat_member(
                        chat.id,
                        new_mem.id,
                        permissions=ChatPermissions(
                            can_send_messages=False,
                            can_invite_users=False,
                            can_pin_messages=False,
                            can_send_polls=False,
                            can_change_info=False,
                            can_send_media_messages=False,
                            can_send_other_messages=False,
                            can_add_web_page_previews=False,
                        ),
                    )
                    job_queue.run_once(
                        partial(check_not_bot, new_mem, chat.id,
                                message.message_id),
                        120,
                        name="welcomemute",
                    )
                if welc_mutes == "captcha":
                    btn = []
                    # Captcha image size number (2 -> 640x360)
                    CAPCTHA_SIZE_NUM = 2
                    # Create Captcha Generator object of specified size
                    generator = CaptchaGenerator(CAPCTHA_SIZE_NUM)

                    # Generate a captcha image
                    captcha = generator.gen_captcha_image(difficult_level=3)
                    # Get information
                    image = captcha["image"]
                    characters = captcha["characters"]
                    #print(characters)
                    fileobj = BytesIO()
                    fileobj.name = f'captcha_{new_mem.id}.png'
                    image.save(fp=fileobj)
                    fileobj.seek(0)
                    CAPTCHA_ANS_DICT[(chat.id, new_mem.id)] = int(characters)
                    welcome_bool = False
                    if not media_wel:
                        VERIFIED_USER_WAITLIST.update({
                            (chat.id, new_mem.id): {
                                "should_welc": should_welc,
                                "media_wel": False,
                                "status": False,
                                "update": update,
                                "res": res,
                                "keyboard": keyboard,
                                "backup_message": backup_message,
                                "captcha_correct": characters,
                            }
                        })
                    else:
                        VERIFIED_USER_WAITLIST.update({
                            (chat.id, new_mem.id): {
                                "should_welc": should_welc,
                                "chat_id": chat.id,
                                "status": False,
                                "media_wel": True,
                                "cust_content": cust_content,
                                "welc_type": welc_type,
                                "res": res,
                                "keyboard": keyboard,
                                "captcha_correct": characters,
                            }
                        })

                    nums = [random.randint(1000, 9999) for _ in range(7)]
                    nums.append(characters)
                    random.shuffle(nums)
                    to_append = []
                    #print(nums)
                    for a in nums:
                        to_append.append(
                            InlineKeyboardButton(
                                text=str(a),
                                callback_data=
                                f"user_captchajoin_({chat.id},{new_mem.id})_({a})"
                            ))
                        if len(to_append) > 2:
                            btn.append(to_append)
                            to_append = []
                    if to_append:
                        btn.append(to_append)

                    message = msg.reply_photo(
                        fileobj,
                        caption=
                        f'Welcome [{escape_markdown(new_mem.first_name)}](tg://user?id={user.id}). Click the correct button to get unmuted!',
                        reply_markup=InlineKeyboardMarkup(btn),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_to_message_id=reply,
                    )
                    bot.restrict_chat_member(
                        chat.id,
                        new_mem.id,
                        permissions=ChatPermissions(
                            can_send_messages=False,
                            can_invite_users=False,
                            can_pin_messages=False,
                            can_send_polls=False,
                            can_change_info=False,
                            can_send_media_messages=False,
                            can_send_other_messages=False,
                            can_add_web_page_previews=False,
                        ),
                    )

        if welcome_bool:
            if media_wel:
                if ENUM_FUNC_MAP[welc_type] == dispatcher.bot.send_sticker:
                    sent = ENUM_FUNC_MAP[welc_type](
                        chat.id,
                        cust_content,
                        reply_markup=keyboard,
                        reply_to_message_id=reply,
                    )
                else:
                    sent = ENUM_FUNC_MAP[welc_type](
                        chat.id,
                        cust_content,
                        caption=res,
                        reply_markup=keyboard,
                        reply_to_message_id=reply,
                        parse_mode="markdown",
                    )
            else:
                sent = send(update, res, keyboard, backup_message)
            prev_welc = sql.get_clean_pref(chat.id)
            if prev_welc:
                try:
                    bot.delete_message(chat.id, prev_welc)
                except BadRequest:
                    pass

                if sent:
                    sql.set_clean_welcome(chat.id, sent.message_id)

        if welcome_log:
            return welcome_log

        return (f"{html.escape(chat.title)}\n"
                f"#USER_JOINED\n"
                f"<b>User</b>: {mention_html(user.id, user.first_name)}\n"
                f"<b>ID</b>: <code>{user.id}</code>")

    return ""
Example #12
0
def new_member(update: Update, context: CallbackContext):
    bot, job_queue = context.bot, context.job_queue
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_message

    should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id)
    welc_mutes = sql.welcome_mutes(chat.id)
    human_checks = sql.get_human_checks(user.id, chat.id)

    new_members = update.effective_message.new_chat_members

    for new_mem in new_members:

        welcome_log = None
        res = None
        sent = None
        should_mute = True
        welcome_bool = True

        if sw != None:
            sw_ban = sw.get_ban(new_mem.id)
            if sw_ban:
                return

        if should_welc:

            reply = update.message.message_id
            cleanserv = sql.clean_service(chat.id)
            # Clean service welcome
            if cleanserv:
                try:
                    dispatcher.bot.delete_message(chat.id,
                                                  update.message.message_id)
                except BadRequest:
                    pass
                reply = False

            # Give the owner a special welcome
            if new_mem.id == OWNER_ID:
                update.effective_message.reply_text(
                    "Oh, Genos? Let's get this moving.",
                    reply_to_message_id=reply)
                welcome_log = (f"{html.escape(chat.title)}\n"
                               f"#USER_JOINED\n"
                               f"Bot Owner just joined the chat")

            # Welcome Devs
            elif new_mem.id in DEV_USERS:
                update.effective_message.reply_text(
                    "Whoa! A member of the Heroes Association just joined!",
                    reply_to_message_id=reply)

            # Welcome Sudos
            elif new_mem.id in SUDO_USERS:
                update.effective_message.reply_text(
                    "Huh! A Dragon disaster just joined! Stay Alert!",
                    reply_to_message_id=reply)

            # Welcome Support
            elif new_mem.id in SUPPORT_USERS:
                update.effective_message.reply_text(
                    "Huh! Someone with a Demon disaster level just joined!",
                    reply_to_message_id=reply)

            # Welcome Whitelisted
            elif new_mem.id in TIGER_USERS:
                update.effective_message.reply_text(
                    "Oof! A Tiger disaster just joined!",
                    reply_to_message_id=reply)

            # Welcome Tigers
            elif new_mem.id in WHITELIST_USERS:
                update.effective_message.reply_text(
                    "Oof! A Wolf disaster just joined!",
                    reply_to_message_id=reply)

            # Welcome yourself
            elif new_mem.id == bot.id:
                update.effective_message.reply_text("Watashi ga kita!",
                                                    reply_to_message_id=reply)

            else:
                # If welcome message is media, send with appropriate function
                if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT):
                    ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome)
                    continue

                # else, move on
                first_name = new_mem.first_name or "PersonWithNoName"  # edge case of empty name - occurs for some bugs.

                if cust_welcome:
                    if cust_welcome == sql.DEFAULT_WELCOME:
                        cust_welcome = random.choice(
                            sql.DEFAULT_WELCOME_MESSAGES).format(
                                first=escape_markdown(first_name))

                    if new_mem.last_name:
                        fullname = escape_markdown(
                            f"{first_name} {new_mem.last_name}")
                    else:
                        fullname = escape_markdown(first_name)
                    count = chat.get_members_count()
                    mention = mention_markdown(new_mem.id,
                                               escape_markdown(first_name))
                    if new_mem.username:
                        username = "******" + escape_markdown(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(
                        cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(
                        first=escape_markdown(first_name),
                        last=escape_markdown(new_mem.last_name or first_name),
                        fullname=escape_markdown(fullname),
                        username=username,
                        mention=mention,
                        count=count,
                        chatname=escape_markdown(chat.title),
                        id=new_mem.id)
                    buttons = sql.get_welc_buttons(chat.id)
                    keyb = build_keyboard(buttons)

                else:
                    res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(
                        first=escape_markdown(first_name))
                    keyb = []

                backup_message = random.choice(
                    sql.DEFAULT_WELCOME_MESSAGES).format(
                        first=escape_markdown(first_name))
                keyboard = InlineKeyboardMarkup(keyb)

        else:
            welcome_bool = False
            res = None
            keyboard = None
            backup_message = None
            reply = None

        # User exceptions from welcomemutes
        if is_user_ban_protected(chat, new_mem.id, chat.get_member(
                new_mem.id)) or human_checks:
            should_mute = False
        # Join welcome: soft mute
        if new_mem.is_bot:
            should_mute = False

        if user.id == new_mem.id:
            if should_mute:
                if welc_mutes == "soft":
                    bot.restrict_chat_member(
                        chat.id,
                        new_mem.id,
                        permissions=ChatPermissions(
                            can_send_messages=True,
                            can_send_media_messages=False,
                            can_send_other_messages=False,
                            can_invite_users=False,
                            can_pin_messages=False,
                            can_send_polls=False,
                            can_change_info=False,
                            can_add_web_page_previews=False,
                            until_date=(int(time.time() + 24 * 60 * 60))))
                if welc_mutes == "strong":
                    welcome_bool = False
                    VERIFIED_USER_WAITLIST.update({
                        new_mem.id: {
                            "should_welc": should_welc,
                            "status": False,
                            "update": update,
                            "res": res,
                            "keyboard": keyboard,
                            "backup_message": backup_message
                        }
                    })
                    new_join_mem = f"[{escape_markdown(new_mem.first_name)}](tg://user?id={user.id})"
                    message = msg.reply_text(
                        f"{new_join_mem}, click the button below to prove you're human.\nYou have 120 seconds.",
                        reply_markup=InlineKeyboardMarkup([{
                            InlineKeyboardButton(
                                text="Yes, I'm human.",
                                callback_data=f"user_join_({new_mem.id})")
                        }]),
                        parse_mode=ParseMode.MARKDOWN,
                        reply_to_message_id=reply)
                    bot.restrict_chat_member(
                        chat.id,
                        new_mem.id,
                        permissions=ChatPermissions(
                            can_send_messages=False,
                            can_invite_users=False,
                            can_pin_messages=False,
                            can_send_polls=False,
                            can_change_info=False,
                            can_send_media_messages=False,
                            can_send_other_messages=False,
                            can_add_web_page_previews=False))
                    job_queue.run_once(partial(check_not_bot, new_mem, chat.id,
                                               message.message_id),
                                       120,
                                       name="welcomemute")

        if welcome_bool:
            sent = send(update, res, keyboard, backup_message)

            prev_welc = sql.get_clean_pref(chat.id)
            if prev_welc:
                try:
                    bot.delete_message(chat.id, prev_welc)
                except BadRequest:
                    pass

                if sent:
                    sql.set_clean_welcome(chat.id, sent.message_id)

        if welcome_log:
            return welcome_log

        return (f"{html.escape(chat.title)}\n"
                f"#USER_JOINED\n"
                f"<b>User</b>: {mention_html(user.id, user.first_name)}\n"
                f"<b>ID</b>: <code>{user.id}</code>")

    return ""
Example #13
0
def new_member(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    new_members = update.effective_message.new_chat_members

    for mems in new_members:
        if is_user_ban_protected(chat, mems.id, chat.get_member(mems.id)):
            continue
        val = is_safemoded(chat.id)
        if val and val.safemode_status:
            try:
                bot.restrict_chat_member(chat.id,
                                         mems.id,
                                         can_send_messages=True,
                                         can_send_media_messages=False,
                                         can_send_other_messages=False,
                                         can_add_web_page_previews=False,
                                         until_date=(int(time.time() +
                                                         24 * 60 * 60)))
            except BadRequest as excp:
                LOGGER.warning(update)
                LOGGER.exception(
                    "ERROR muting user %s in chat %s (%s) due to %s", mems.id,
                    chat.title, chat.id, excp.message)

    should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id)
    if should_welc:
        sent = None
        new_members = update.effective_message.new_chat_members
        for new_mem in new_members:
            # Give the owner a special welcome
            if new_mem.id == OWNER_ID:
                update.effective_message.reply_text(
                    "Master is in the houseeee, let's get this party started!")
                continue

            # Don't welcome yourself
            elif new_mem.id == bot.id:
                continue

            else:
                # If welcome message is media, send with appropriate function
                if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT:
                    ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome)
                    return
                # else, move on
                first_name = new_mem.first_name or "PersonWithNoName"  # edge case of empty name - occurs for some bugs.

                if cust_welcome:
                    if new_mem.last_name:
                        fullname = "{} {}".format(first_name,
                                                  new_mem.last_name)
                    else:
                        fullname = first_name
                    count = chat.get_members_count()
                    mention = mention_markdown(new_mem.id, first_name)
                    if new_mem.username:
                        username = "******" + escape_markdown(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(
                        cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(
                        first=escape_markdown(first_name),
                        last=escape_markdown(new_mem.last_name or first_name),
                        fullname=escape_markdown(fullname),
                        username=username,
                        mention=mention,
                        count=count,
                        chatname=escape_markdown(chat.title),
                        id=new_mem.id)
                    buttons = sql.get_welc_buttons(chat.id)
                    keyb = build_keyboard(buttons)
                else:
                    res = sql.DEFAULT_WELCOME.format(first=first_name)
                    keyb = []

                keyboard = InlineKeyboardMarkup(keyb)

                sent = send(update, res, keyboard,
                            sql.DEFAULT_WELCOME.format(
                                first=first_name))  # type: Optional[Message]
            delete_join(bot, update)

        prev_welc = sql.get_clean_pref(chat.id)
        if prev_welc:
            try:
                bot.delete_message(chat.id, prev_welc)
            except BadRequest as excp:
                pass

            if sent:
                sql.set_clean_welcome(chat.id, sent.message_id)
Example #14
0
def start(bot: Bot, update: Update, args: List[str]):
    spam = spamfilters(update.effective_message.text,
                       update.effective_message.from_user.id,
                       update.effective_chat.id, update.effective_message)
    if spam == True:
        return
    if update.effective_chat.type == "private":
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id,
                          tl(update.effective_message, HELP_STRINGS))

            elif args[0].lower() == "get_notes":
                update.effective_message.reply_text(
                    tl(update.effective_message,
                       "Anda sekarang dapat mengambil catatan di grup."))

            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(match.group(1), update.effective_user.id,
                                  False)
                else:
                    send_settings(match.group(1), update.effective_user.id,
                                  True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

            elif args[0][:4] == "wiki":
                wiki = args[0].split("-")[1].replace('_', ' ')
                message = update.effective_message
                getlang = langsql.get_lang(message)
                if getlang == "id":
                    wikipedia.set_lang("id")
                pagewiki = wikipedia.page(wiki)
                judul = pagewiki.title
                summary = pagewiki.summary
                if len(summary) >= 4096:
                    summary = summary[:4000] + "..."
                message.reply_text("<b>{}</b>\n{}".format(judul, summary),
                                   parse_mode=ParseMode.HTML,
                                   reply_markup=InlineKeyboardMarkup([[
                                       InlineKeyboardButton(text=tl(
                                           update.effective_message,
                                           "Baca di Wikipedia"),
                                                            url=pagewiki.url)
                                   ]]))

        else:
            first_name = update.effective_user.first_name
            buttons = InlineKeyboardMarkup(
                [[
                    InlineKeyboardButton(
                        text="🎉 Add me to your group",
                        url="https://t.me/UserbotindoBot?startgroup=new")
                ],
                 [
                     InlineKeyboardButton(text="💭 Language",
                                          callback_data="main_setlang"),
                     InlineKeyboardButton(text="⚙️ Connect Group",
                                          callback_data="main_connect")
                 ],
                 [
                     InlineKeyboardButton(text="👥 Support Group",
                                          url="https://t.me/userbotindo"),
                     InlineKeyboardButton(text="🔔 Update Channel",
                                          url="https://t.me/userbotindocloud")
                 ],
                 [
                     InlineKeyboardButton(
                         text="❓ Help",
                         url="https://t.me/UserbotindoBot?start=help"),
                     InlineKeyboardButton(text="💖 Donate",
                                          url="http://paypal.me/MoveAngel")
                 ]])
            update.effective_message.reply_text(
                tl(update.effective_message,
                   PM_START_TEXT).format(escape_markdown(first_name),
                                         escape_markdown(bot.first_name),
                                         OWNER_ID),
                disable_web_page_preview=True,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=buttons)
    else:
        update.effective_message.reply_text(
            tl(update.effective_message, "Ada yang bisa saya bantu? 😊"))
def start(update: Update, context: CallbackContext):
    args = context.args
    uptime = get_readable_time((time.time() - StartTime))
    if update.effective_chat.type == "private":
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id, HELP_STRINGS)
            elif args[0].lower().startswith("ghelp_"):
                mod = args[0].lower().split('_', 1)[1]
                if not HELPABLE.get(mod, False):
                    return
                send_help(
                    update.effective_chat.id, HELPABLE[mod].__help__,
                    InlineKeyboardMarkup([[
                        InlineKeyboardButton(text="Back",
                                             callback_data="help_back")
                    ]]))
            elif args[0].lower() == "markdownhelp":
                IMPORTED["extras"].markdown_help_sender(update)
            elif args[0].lower() == "disasters":
                IMPORTED["disasters"].send_disasters(update)
            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(match.group(1), update.effective_user.id,
                                  False)
                else:
                    send_settings(match.group(1), update.effective_user.id,
                                  True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

        else:
            first_name = update.effective_user.first_name
            update.effective_message.reply_photo(
                SAITAMA_IMG,
                PM_START_TEXT.format(escape_markdown(first_name),
                                     escape_markdown(context.bot.first_name)),
                parse_mode=ParseMode.MARKDOWN,
                disable_web_page_preview=True,
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton(
                            text=" 👑 Add Me ",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username)),
                        InlineKeyboardButton(
                            text=" 🔔 Channel ",
                            url="https://t.me/Kannada_HD_Films")
                    ],
                     [
                         InlineKeyboardButton(
                             text=" ✨ My Master 🧑‍💻",
                             url="https://t.me/The_Noob_Hackerr"),
                         InlineKeyboardButton(
                             text=" ⚡️ Support group",
                             url="https://t.me/Kannada_Films_Request")
                     ],
                     [
                         InlineKeyboardButton(
                             text=" 🤝 Help ",
                             url="http://t.me/The_NOoB_HackerR_BoT?start=help")
                     ]]))
    else:
        update.effective_message.reply_text(
            "I'm awake already! \nAm not lazy like you\n<b>Haven't slept since:</b> <code>{}</code>"
            .format(uptime),
            parse_mode=ParseMode.HTML)
Example #16
0
def new_member(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    msg = update.effective_message  # type: Optional[Message]
    chat_name = chat.title or chat.first or chat.username  # type: Optional:[chat name]
    should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id)
    welc_mutes = sql.welcome_mutes(chat.id)
    casPrefs = sql.get_cas_status(str(chat.id))  #check if enabled, obviously
    autoban = sql.get_cas_autoban(str(chat.id))
    chatbanned = sql.isBanned(str(chat.id))
    defense = sql.getDefenseStatus(str(chat.id))
    time_value = sql.getKickTime(str(chat.id))
    fed_id = feds_sql.get_fed_id(chat.id)
    fed_info = feds_sql.get_fed_info(fed_id)
    fban, fbanreason, fbantime = feds_sql.get_fban_user(fed_id, user.id)
    if chatbanned:
        bot.leave_chat(int(chat.id))
    elif fban:
        update.effective_message.reply_text(
            "🔨 User {} is banned in the current Federation ({}), and so has been Removed.\n<b>Reason</b>: {}"
            .format(mention_html(user.id, user.first_name), fed_info['fname'],
                    fbanreason or "No reason given"),
            parse_mode=ParseMode.HTML)
        bot.kick_chat_member(chat.id, user.id)
    elif casPrefs and not autoban and cas.banchecker(user.id):
        bot.restrict_chat_member(chat.id,
                                 user.id,
                                 can_send_messages=False,
                                 can_send_media_messages=False,
                                 can_send_other_messages=False,
                                 can_add_web_page_previews=False)
        msg.reply_text(
            "Warning! This user is CAS Banned. I have muted them to avoid spam. Ban is advised."
        )
        isUserGbanned = gbansql.is_user_gbanned(user.id)
        if not isUserGbanned:
            report = "CAS Banned user detected: <code>{}</code>".format(
                user.id)
            send_to_list(bot, SUDO_USERS + SUPPORT_USERS, report, html=True)
        if defense:
            bantime = int(time.time()) + 60
            chat.kick_member(new_mem.id, until_date=bantime)
    elif casPrefs and autoban and cas.banchecker(user.id):
        chat.kick_member(user.id)
        msg.reply_text(
            "CAS banned user detected! User has been automatically banned!")
        isUserGbanned = gbansql.is_user_gbanned(user.id)
        if not isUserGbanned:
            report = "CAS Banned user detected: <code>{}</code>".format(
                user.id)
            send_to_list(bot, SUDO_USERS + SUPPORT_USERS, report, html=True)
    elif defense and (user.id not in SUDO_USERS + SUPPORT_USERS):
        bantime = int(time.time()) + 60
        chat.kick_member(user.id, until_date=bantime)
    elif should_welc:
        sent = None
        new_members = update.effective_message.new_chat_members
        for new_mem in new_members:
            # Give the owner a special welcome
            if new_mem.id == OWNER_ID:
                update.effective_message.reply_text(
                    "Oh! 🤴🏻Genos, My Developer has just joined your group.")
                continue

            # Welcome Devs
            elif new_mem.id in DEV_USERS:
                update.effective_message.reply_text(
                    "Whoa! A member of the Heroes Association just joined!")

            # Welcome Sudos
            elif new_mem.id in SUDO_USERS:
                update.effective_message.reply_text(
                    "Huh! A Sudo User just joined! Stay Alert!")

            # Welcome Support
            elif new_mem.id in SUPPORT_USERS:
                update.effective_message.reply_text(
                    "Huh! Someone with a Support User just joined!")

            # Welcome Whitelisted
            elif new_mem.id in WHITELIST_USERS:
                update.effective_message.reply_text(
                    "Oof! A Whitelist User just joined!")

            elif new_mem.id == 1238300672:
                update.effective_message.reply_text(
                    "Oh! 🤴🏻Genos, My Creator/Developer has just joined your group."
                )

            # Make bot greet admins
            elif new_mem.id == bot.id:
                update.effective_message.reply_text(
                    "Hey {}, I'm {}! Thank you for adding me to {}"
                    " and be sure to check /help in PM for more commands and tricks!"
                    .format(user.first_name, bot.first_name, chat_name))
                bot.send_message(
                    MESSAGE_DUMP,
                    "I have been added to {} with \nID: <pre>{}</pre>".format(
                        chat.title, chat.id),
                    parse_mode=ParseMode.HTML)
            else:
                # If welcome message is media, send with appropriate function
                if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT:
                    ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome)
                    return
                # else, move on
                first_name = new_mem.first_name or "PersonWithNoName"  # edge case of empty name - occurs for some bugs.

                if cust_welcome:
                    if new_mem.last_name:
                        fullname = "{} {}".format(first_name,
                                                  new_mem.last_name)
                    else:
                        fullname = first_name
                    count = chat.get_members_count()
                    mention = mention_markdown(new_mem.id, first_name)
                    if new_mem.username:
                        username = "******" + escape_markdown(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(
                        cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(
                        first=escape_markdown(first_name),
                        last=escape_markdown(new_mem.last_name or first_name),
                        fullname=escape_markdown(fullname),
                        username=username,
                        mention=mention,
                        count=count,
                        chatname=escape_markdown(chat.title),
                        id=new_mem.id)
                    buttons = sql.get_welc_buttons(chat.id)
                    keyb = build_keyboard(buttons)
                else:
                    res = sql.DEFAULT_WELCOME.format(first=first_name,
                                                     chatname=chat.title)
                    keyb = []

                keyboard = InlineKeyboardMarkup(keyb)

                sent = send(
                    update, res, keyboard,
                    sql.DEFAULT_WELCOME.format(
                        first=first_name,
                        chatname=chat.title))  # type: Optional[Message]

                #Sudo user exception from mutes:
                if is_user_ban_protected(chat, new_mem.id,
                                         chat.get_member(new_mem.id)):
                    continue

                #Safe mode
                newMember = chat.get_member(int(new_mem.id))
                if welc_mutes == "on" and ((newMember.can_send_messages is None
                                            or newMember.can_send_messages)):
                    buttonMsg = msg.reply_text(
                        "Click the button below to prove you're human",
                        reply_markup=InlineKeyboardMarkup([[
                            InlineKeyboardButton(
                                text="I'm not a bot! 🤖",
                                callback_data="userverify_({})".format(
                                    new_mem.id))
                        ]]))
                    bot.restrict_chat_member(chat.id,
                                             new_mem.id,
                                             can_send_messages=False,
                                             can_send_media_messages=False,
                                             can_send_other_messages=False,
                                             can_add_web_page_previews=False)

            delete_join(bot, update)

        prev_welc = sql.get_clean_pref(chat.id)
        if prev_welc:
            try:
                bot.delete_message(chat.id, prev_welc)
            except BadRequest as excp:
                pass

            if sent:
                sql.set_clean_welcome(chat.id, sent.message_id)
Example #17
0
def adminlist(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    args = context.args
    bot = context.bot

    if update.effective_message.chat.type == "private":
        send_message(update.effective_message,
                     "This command only works in Groups.")
        return

    chat = update.effective_chat
    chat_id = update.effective_chat.id
    chat_name = update.effective_message.chat.title

    try:
        msg = update.effective_message.reply_text(
            'Fetching group admins...', parse_mode=ParseMode.MARKDOWN)
    except BadRequest:
        msg = update.effective_message.reply_text(
            'Fetching group admins...',
            quote=False,
            parse_mode=ParseMode.MARKDOWN)

    administrators = bot.getChatAdministrators(chat_id)
    text = "Admins in *{}*:".format(update.effective_chat.title)

    bot_admin_list = []

    for admin in administrators:
        user = admin.user
        status = admin.status
        custom_title = admin.custom_title

        if user.first_name == '':
            name = "☠ Deleted Account"
        else:
            name = "{}".format(
                mention_markdown(
                    user.id, user.first_name + " " + (user.last_name or "")))

        if user.is_bot:
            bot_admin_list.append(name)
            administrators.remove(admin)
            continue

        #if user.username:
        #    name = escape_markdown("@" + user.username)
        if status == "creator":
            text += "\n 👑 Creator:"
            text += "\n` • `{}\n".format(name)

            if custom_title:
                text += f"┗━ `{escape_markdown(custom_title)}`\n"

    text += "\n🔱 Admins:"

    custom_admin_list = {}
    normal_admin_list = []

    for admin in administrators:
        user = admin.user
        status = admin.status
        custom_title = admin.custom_title

        if user.first_name == '':
            name = "☠ Deleted Account"
        else:
            name = "{}".format(
                mention_markdown(
                    user.id, user.first_name + " " + (user.last_name or "")))
        #if user.username:
        #    name = escape_markdown("@" + user.username)
        if status == "administrator":
            if custom_title:
                try:
                    custom_admin_list[custom_title].append(name)
                except KeyError:
                    custom_admin_list.update({custom_title: [name]})
            else:
                normal_admin_list.append(name)

    for admin in normal_admin_list:
        text += "\n` • `{}".format(admin)

    for admin_group in custom_admin_list.copy():
        if len(custom_admin_list[admin_group]) == 1:
            text += "\n` • `{} | `{}`".format(
                custom_admin_list[admin_group][0],
                escape_markdown(admin_group))
            custom_admin_list.pop(admin_group)

    text += "\n"
    for admin_group in custom_admin_list:
        text += "\n🔘 `{}`".format(admin_group)
        for admin in custom_admin_list[admin_group]:
            text += "\n` • `{}".format(admin)
        text += "\n"

    text += "\n🤖 Bots:"
    for each_bot in bot_admin_list:
        text += "\n` • `{}".format(each_bot)

    try:
        msg.edit_text(text, parse_mode=ParseMode.MARKDOWN)
    except BadRequest:  # if original message is deleted
        return
Example #18
0
def start(update, context):
    if update.effective_chat.type == "private":
        args = context.args
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id, HELP_STRINGS)

            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(match.group(1), update.effective_user.id,
                                  False)
                else:
                    send_settings(match.group(1), update.effective_user.id,
                                  True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

        else:
            first_name = update.effective_user.first_name
            update.effective_message.reply_photo(
                BOT_IMG,
                caption=PM_START_TEXT.format(
                    escape_markdown(first_name),
                    escape_markdown(context.bot.first_name), OWNER_ID),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton(
                            text="Add Asuna to your group",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username))
                    ],
                     [
                         InlineKeyboardButton(
                             text="Support Chat ",
                             url="https://t.me/zerouninoxasuna"),
                         InlineKeyboardButton(
                             text="Updates ",
                             url="https://t.me/zerouninoxasunaupdates")
                     ],
                     [
                         InlineKeyboardButton(
                             text="help",
                             url="https://t.me/Asuna_1_bot?start=help")
                     ]]))


#@run_async
#def tg_bot_about_callback(update, context):
#query = update.callback_query
#if query.data == "home_back":
#query.message.edit_text(
#PM_START_TEXT,
#parse_mode=ParseMode.MARKDOWN,
#reply_markup=InlineKeyboardMarkup(buttons),
#timeout=60,)

    else:
        update.effective_message.reply_text("HI, Why u summoned me")
Example #19
0
def new_member(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]

    should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id)
    if should_welc:
        sent = None
        new_members = update.effective_message.new_chat_members
        for new_mem in new_members:
            # Give the owner a special welcome
            if new_mem.id == OWNER_ID:
                update.effective_message.reply_text("Bhau agyela h @admins Seva me lag jao! Welcome bhau @king_un_007 Group chota h par apko koi taklif nhi hone denge ")
                continue

            # Don't welcome yourself
            elif new_mem.id == bot.id:
                continue

            else:
                # If welcome message is media, send with appropriate function
                if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT:
                    ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome)
                    return
                # else, move on
                first_name = new_mem.first_name or "PersonWithNoName"  # edge case of empty name - occurs for some bugs.

                if cust_welcome:
                    if new_mem.last_name:
                        fullname = "{} {}".format(first_name, new_mem.last_name)
                    else:
                        fullname = first_name
                    count = chat.get_members_count()
                    mention = mention_markdown(new_mem.id, escape_markdown(first_name))
                    if new_mem.username:
                        username = "******" + escape_markdown(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(first=escape_markdown(first_name),
                                              last=escape_markdown(new_mem.last_name or first_name),
                                              fullname=escape_markdown(fullname), username=username, mention=mention,
                                              count=count, chatname=escape_markdown(chat.title), id=new_mem.id)
                    buttons = sql.get_welc_buttons(chat.id)
                    keyb = build_keyboard(buttons)
                else:
                    res = sql.DEFAULT_WELCOME.format(first=first_name)
                    keyb = []

                keyboard = InlineKeyboardMarkup(keyb)

                sent = send(update, res, keyboard,
                            sql.DEFAULT_WELCOME.format(first=first_name))  # type: Optional[Message]
            delete_join(bot, update)

        prev_welc = sql.get_clean_pref(chat.id)
        if prev_welc:
            try:
                bot.delete_message(chat.id, prev_welc)
            except BadRequest as excp:
                pass

            if sent:
                sql.set_clean_welcome(chat.id, sent.message_id)
Example #20
0
def settings_button(update, context):
    query = update.callback_query
    user = update.effective_user
    mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data)
    prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data)
    next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data)
    back_match = re.match(r"stngs_back\((.+?)\)", query.data)
    try:
        if mod_match:
            chat_id = mod_match.group(1)
            module = mod_match.group(2)
            chat = context.bot.get_chat(chat_id)
            getstatusadmin = context.bot.get_chat_member(chat_id, user.id)
            isadmin = getstatusadmin.status in ('administrator', 'creator')
            if isadmin == False or user.id != OWNER_ID:
                query.message.edit_text("Your admin status has changed")
                return
            text = tl(update.effective_message, "*{}* memiliki pengaturan berikut untuk modul *{}* module:\n\n").format(escape_markdown(chat.title),
                                                                                     CHAT_SETTINGS[
                                                                                        module].__mod_name__) + \
                   CHAT_SETTINGS[module].__chat_settings__(chat_id, user.id)
            try:
                set_button = CHAT_SETTINGS[module].__chat_settings_btn__(
                    chat_id, user.id)
            except AttributeError:
                set_button = []
            set_button.append([
                InlineKeyboardButton(
                    text=tl(query.message, "⬅️ kembali"),
                    callback_data="stngs_back({})".format(chat_id))
            ])
            query.message.edit_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(set_button))

        elif prev_match:
            chat_id = prev_match.group(1)
            curr_page = int(prev_match.group(2))
            chat = context.bot.get_chat(chat_id)
            query.message.reply_text(text=tl(
                update.effective_message,
                "Hai! Ada beberapa pengaturan untuk {} - lanjutkan dan pilih "
                "apa yang Anda minati.").format(chat.title),
                                     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 = context.bot.get_chat(chat_id)
            query.message.reply_text(text=tl(
                update.effective_message,
                "Hai! Ada beberapa pengaturan untuk {} - lanjutkan dan pilih "
                "apa yang Anda minati.").format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(next_page + 1,
                                                          CHAT_SETTINGS,
                                                          "stngs",
                                                          chat=chat_id)))

        elif back_match:
            chat_id = back_match.group(1)
            chat = context.bot.get_chat(chat_id)
            query.message.reply_text(text=tl(
                update.effective_message,
                "Hai! Ada beberapa pengaturan untuk {} - lanjutkan dan pilih "
                "apa yang Anda minati.").format(escape_markdown(chat.title)),
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(0,
                                                          CHAT_SETTINGS,
                                                          "stngs",
                                                          chat=chat_id)))

        # ensure no spinny white circle

        context.bot.answer_callback_query(query.id)
    except Exception 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:
            query.message.edit_text(excp.message)
            LOGGER.exception("Exception in settings buttons. %s",
                             str(query.data))
    def process_telegram_message(self,
                                 update: Update,
                                 context: CallbackContext,
                                 destination: EFBChannelChatIDStr,
                                 quote: bool = False,
                                 edited: Optional["MsgLog"] = None):
        """
        Process messages came from Telegram.

        Args:
            update: Telegram message update
            context: PTB update context
            destination: Destination of the message specified.
            quote: If the message shall quote another one
            edited: old message log entry if the message can be edited.
        """
        assert isinstance(update, Update)
        assert update.effective_message

        # Message ID for logging
        message_id = utils.message_id_to_str(update=update)

        message: Message = update.effective_message

        channel, uid, gid = utils.chat_id_str_to_id(destination)
        if channel not in coordinator.slaves:
            return self.bot.reply_error(
                update,
                self._("Internal error: Slave channel “{0}” not found.").
                format(channel))

        m = ETMMsg()
        log_message = True
        try:
            m.uid = MessageID(message_id)
            # Store Telegram message type
            m.type_telegram = mtype = get_msg_type(message)

            if self.TYPE_DICT.get(mtype, None):
                m.type = self.TYPE_DICT[mtype]
                self.logger.debug("[%s] EFB message type: %s", message_id,
                                  mtype)
            else:
                self.logger.info(
                    "[%s] Message type %s is not supported by ETM", message_id,
                    mtype)
                raise EFBMessageTypeNotSupported(
                    self.
                    _("{type_name} messages are not supported by EFB Telegram Master channel."
                      ).format(type_name=mtype.name))

            m.put_telegram_file(message)
            # Chat and author related stuff
            m.chat = self.chat_manager.get_chat(channel, uid, build_dummy=True)
            m.author = m.chat.self or m.chat.add_self()

            m.deliver_to = coordinator.slaves[channel]

            if quote:
                self.attach_target_message(message, m, channel)
            # Type specific stuff
            self.logger.debug("[%s] Message type from Telegram: %s",
                              message_id, mtype)

            if m.type not in coordinator.slaves[
                    channel].supported_message_types:
                self.logger.info(
                    "[%s] Message type %s is not supported by channel %s",
                    message_id, m.type.name, channel)
                raise EFBMessageTypeNotSupported(
                    self.
                    _("{type_name} messages are not supported by slave channel {channel_name}."
                      ).format(type_name=m.type.name,
                               channel_name=coordinator.slaves[channel].
                               channel_name))

            # Convert message text and caption to markdown
            # Keep original text if what *_markdown_2 did is just escaping the text.
            msg_md_text = message.text and message.text_markdown_v2 or ""
            if message.text and msg_md_text == escape_markdown(message.text,
                                                               version=2):
                msg_md_text = message.text
            msg_md_text = msg_md_text or ""

            msg_md_caption = message.caption and message.caption_markdown_v2 or ""
            if message.caption and msg_md_caption == escape_markdown(
                    message.caption, version=2):
                msg_md_caption = message.caption
            msg_md_caption = msg_md_caption or ""

            # Flag for edited message
            if edited:
                m.edit = True
                text = msg_md_text or msg_md_caption

                m.uid = edited.slave_message_id
                if text.startswith(self.DELETE_FLAG):
                    coordinator.send_status(
                        MessageRemoval(
                            source_channel=self.channel,
                            destination_channel=coordinator.slaves[channel],
                            message=m))
                    if not self.channel.flag('prevent_message_removal'):
                        try:
                            message.delete()
                        except TelegramError:
                            message.reply_text(
                                self._("Message is removed in remote chat."))
                    else:
                        message.reply_text(
                            self._("Message is removed in remote chat."))
                    log_message = False
                    return
                self.logger.debug('[%s] Message is edited (%s)', m.uid, m.edit)
                if m.file_unique_id and m.file_unique_id != edited.file_unique_id:
                    self.logger.debug(
                        "[%s] Message media is edited (%s -> %s)", m.uid,
                        edited.file_unique_id, m.file_unique_id)
                    m.edit_media = True

            # Enclose message as an Message object by message type.
            if mtype is TGMsgType.Text:
                m.text = msg_md_text
            elif mtype is TGMsgType.Photo:
                assert message.photo
                m.text = msg_md_caption
                m.mime = "image/jpeg"
                self._check_file_download(message.photo[-1])
            elif mtype in (TGMsgType.Sticker, TGMsgType.AnimatedSticker):
                assert message.sticker
                # Convert WebP to the more common PNG
                m.text = ""
                self._check_file_download(message.sticker)
            elif mtype is TGMsgType.Animation:
                assert message.animation
                m.text = msg_md_caption
                self.logger.debug(
                    "[%s] Telegram message is a \"Telegram GIF\".", message_id)
                m.filename = getattr(message.animation, "file_name",
                                     None) or None
                if m.filename and not m.filename.lower().endswith(".gif"):
                    m.filename += ".gif"
                m.mime = message.animation.mime_type or m.mime
            elif mtype is TGMsgType.Document:
                assert message.document
                m.text = msg_md_caption
                self.logger.debug("[%s] Telegram message type is document.",
                                  message_id)
                m.filename = getattr(message.document, "file_name",
                                     None) or None
                m.mime = message.document.mime_type
                self._check_file_download(message.document)
            elif mtype is TGMsgType.Video:
                assert message.video
                m.text = msg_md_caption
                m.mime = message.video.mime_type
                self._check_file_download(message.video)
            elif mtype is TGMsgType.VideoNote:
                assert message.video_note
                m.text = msg_md_caption
                self._check_file_download(message.video_note)
            elif mtype is TGMsgType.Audio:
                assert message.audio
                m.text = "%s - %s\n%s" % (message.audio.title,
                                          message.audio.performer,
                                          msg_md_caption)
                m.mime = message.audio.mime_type
                self._check_file_download(message.audio)
            elif mtype is TGMsgType.Voice:
                assert message.voice
                m.text = msg_md_caption
                m.mime = message.voice.mime_type
                self._check_file_download(message.voice)
            elif mtype is TGMsgType.Location:
                # TRANSLATORS: Message body text for location messages.
                assert message.location
                m.text = self._("Location")
                m.attributes = LocationAttribute(message.location.latitude,
                                                 message.location.longitude)
            elif mtype is TGMsgType.Venue:
                assert message.venue
                m.text = f"📍 {message.venue.title}\n{message.venue.address}"
                m.attributes = LocationAttribute(
                    message.venue.location.latitude,
                    message.venue.location.longitude)
            elif mtype is TGMsgType.Contact:
                assert message.contact
                contact: Contact = message.contact
                m.text = self._(
                    "Shared a contact: {first_name} {last_name}\n{phone_number}"
                ).format(first_name=contact.first_name,
                         last_name=contact.last_name,
                         phone_number=contact.phone_number)
            elif mtype is TGMsgType.Dice:
                assert message.dice
                m.text = f"{message.dice.emoji} = {message.dice.value}"
            else:
                raise EFBMessageTypeNotSupported(
                    self._("Message type {0} is not supported.").format(
                        mtype.name))

            slave_msg = coordinator.send_message(m)
            if slave_msg and slave_msg.uid:
                m.uid = slave_msg.uid
            else:
                m.uid = None
        except EFBChatNotFound as e:
            self.bot.reply_error(update, e.args[0]
                                 or self._("Chat is not found."))
        except EFBMessageTypeNotSupported as e:
            self.bot.reply_error(
                update, e.args[0] or self._("Message type is not supported."))
        except EFBOperationNotSupported as e:
            self.bot.reply_error(
                update,
                self._("Message editing is not supported.\n\n{exception!s}".
                       format(exception=e)))
        except EFBException as e:
            self.bot.reply_error(
                update,
                self._("Message is not sent.\n\n{exception!s}".format(
                    exception=e)))
            self.logger.exception(
                "Message is not sent. (update: %s, exception: %s)", update, e)
        except Exception as e:
            self.bot.reply_error(
                update,
                self._("Message is not sent.\n\n{exception!r}".format(
                    exception=e)))
            self.logger.exception(
                "Message is not sent. (update: %s, exception: %s)", update, e)
        finally:
            if log_message:
                self.db.add_or_update_message_log(m, update.effective_message)
                if m.file:
                    m.file.close()
Example #22
0
def control_panel(bot, update):
    LOGGER.info("Control panel")
    chat = update.effective_chat
    user = update.effective_user

    # ONLY send help in PM
    if chat.type != chat.PRIVATE:

        update.effective_message.reply_text(
            "Contact me in PM to access the control panel.",
            reply_markup=InlineKeyboardMarkup([[
                InlineKeyboardButton(
                    text="Control Panel",
                    url=f"t.me/{bot.username}?start=controlpanel")
            ]]))
        return

    #Support to run from command handler
    query = update.callback_query
    if query:
        query.message.delete()

        M_match = re.match(r"cntrl_panel_M", query.data)
        U_match = re.match(r"cntrl_panel_U", query.data)
        G_match = re.match(r"cntrl_panel_G", query.data)
        back_match = re.match(r"help_back", query.data)

        LOGGER.info(query.data)
    else:
        M_match = "ThaNos is the best bot"  #LMAO, don't uncomment

    if M_match:
        text = "*Control panel* 🛠"

        keyboard = [[
            InlineKeyboardButton(text="👤 My settings",
                                 callback_data="cntrl_panel_U(1)")
        ]]

        #Show connected chat and add chat settings button
        conn = connected(bot, update, chat, user.id, need_admin=False)

        if conn:
            chatG = bot.getChat(conn)
            #admin_list = chatG.get_administrators() #Unused variable

            #If user admin
            member = chatG.get_member(user.id)
            if member.status in ('administrator', 'creator'):
                text += f"\nConnected chat - *{chatG.title}* (you {member.status})"
                keyboard += [[
                    InlineKeyboardButton(text="👥 Group settings",
                                         callback_data="cntrl_panel_G_back")
                ]]
            elif user.id in SUDO_USERS:
                text += f"\nConnected chat - *{chatG.title}* (you sudo)"
                keyboard += [[
                    InlineKeyboardButton(text="👥 Group settings (SUDO)",
                                         callback_data="cntrl_panel_G_back")
                ]]
            else:
                text += f"\nConnected chat - *{chatG.title}* (you aren't an admin!)"
        else:
            text += "\nNo chat connected!"

        keyboard += [[
            InlineKeyboardButton(text="Back", callback_data="bot_start")
        ]]

        update.effective_message.reply_text(
            text,
            reply_markup=InlineKeyboardMarkup(keyboard),
            parse_mode=ParseMode.MARKDOWN)

    elif U_match:

        mod_match = re.match(r"cntrl_panel_U_module\((.+?)\)", query.data)
        back_match = re.match(r"cntrl_panel_U\((.+?)\)", query.data)

        chatP = update.effective_chat  # type: Optional[Chat]
        if mod_match:
            module = mod_match.group(1)

            R = CHAT_SETTINGS[module].__user_settings__(bot, update, user)

            text = "You has the following settings for the *{}* module:\n\n".format(
                CHAT_SETTINGS[module].__mod_name__) + R[0]

            keyboard = R[1]
            keyboard += [[
                InlineKeyboardButton(text="Back",
                                     callback_data="cntrl_panel_U(1)")
            ]]

            query.message.reply_text(
                text=text,
                arse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(keyboard))

        elif back_match:
            text = "*User control panel* 🛠"

            query.message.reply_text(text=text,
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             user.id, 0, USER_SETTINGS,
                                             "cntrl_panel_U")))

    elif G_match:
        mod_match = re.match(r"cntrl_panel_G_module\((.+?)\)", query.data)
        prev_match = re.match(r"cntrl_panel_G_prev\((.+?)\)", query.data)
        next_match = re.match(r"cntrl_panel_G_next\((.+?)\)", query.data)
        back_match = re.match(r"cntrl_panel_G_back", query.data)

        chatP = chat
        conn = connected(bot, update, chat, user.id)

        if not conn == False:
            chat = bot.getChat(conn)
        else:
            query.message.reply_text(text="Error with connection to chat")
            exit(1)

        if mod_match:
            module = mod_match.group(1)
            R = CHAT_SETTINGS[module].__chat_settings__(
                bot, update, chat, chatP, user)

            if type(R) is list:
                text = R[0]
                keyboard = R[1]
            else:
                text = R
                keyboard = []

            text = "*{}* has the following settings for the *{}* module:\n\n".format(
                escape_markdown(chat.title),
                CHAT_SETTINGS[module].__mod_name__) + text

            keyboard += [[
                InlineKeyboardButton(text="Back",
                                     callback_data="cntrl_panel_G_back")
            ]]

            query.message.reply_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(keyboard))

        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(tld(
                user.id, "send-group-settings").format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(curr_page - 1,
                                                          0,
                                                          CHAT_SETTINGS,
                                                          "cntrl_panel_G",
                                                          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(tld(
                user.id, "send-group-settings").format(chat.title),
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(next_page + 1,
                                                          0,
                                                          CHAT_SETTINGS,
                                                          "cntrl_panel_G",
                                                          chat=chat_id)))

        elif back_match:
            text = "Test"
            query.message.reply_text(text=text,
                                     parse_mode=ParseMode.MARKDOWN,
                                     reply_markup=InlineKeyboardMarkup(
                                         paginate_modules(
                                             user.id, 0, CHAT_SETTINGS,
                                             "cntrl_panel_G")))
Example #23
0
def new_member(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]

    should_welc, cust_welcome, welc_type = sql.get_welc_pref(chat.id)
    if should_welc:
        sent = None
        new_members = update.effective_message.new_chat_members
        for new_mem in new_members:
            # Give the owner a special welcome
            if new_mem.id == OWNER_ID:
                update.effective_message.reply_text("Oh, You're here Genos. Lets get this moving.")
                continue

            # Give the owner a special welcome
            elif new_mem.id in DEV_USERS:
                update.effective_message.reply_text("Huh! A member of the Hero's Association just joined!")
                continue

            # Welcome Sudos 
            elif new_mem.id in SUDO_USERS:
                update.effective_message.reply_text("Huh! Someone with a Disaster Level just joined!")
                continue
				#Generalised the diaster notices so that ppl check a user manually and engage with bot functions.
            # Welcome Support
            elif new_mem.id in SUPPORT_USERS:
                update.effective_message.reply_text("Huh! Someone with a Disaster Level just joined!")
                continue

            # Don't welcome yourself
            elif new_mem.id == bot.id:
                continue

            else:
                # If welcome message is media, send with appropriate function
                if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT:
                    ENUM_FUNC_MAP[welc_type](chat.id, cust_welcome)
                    return
                # else, move on
                first_name = new_mem.first_name or "PersonWithNoName"  # edge case of empty name - occurs for some bugs.

                if cust_welcome:
                    if cust_welcome == sql.DEFAULT_WELCOME:
                        cust_welcome = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(first=first_name)
                    LOGGER.info("Custom Message: {}".format(cust_welcome))
                    if new_mem.last_name:
                        fullname = "{} {}".format(first_name, new_mem.last_name)
                    else:
                        fullname = first_name
                    count = chat.get_members_count()
                    mention = mention_markdown(new_mem.id, first_name)
                    if new_mem.username:
                        username = "******" + escape_markdown(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(first=escape_markdown(first_name),
                                              last=escape_markdown(new_mem.last_name or first_name),
                                              fullname=escape_markdown(fullname), username=username, mention=mention,
                                              count=count, chatname=escape_markdown(chat.title), id=new_mem.id)
                    buttons = sql.get_welc_buttons(chat.id)
                    keyb = build_keyboard(buttons)
                else:
                    res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(first=first_name)
                    LOGGER.info("res is {}".format(res))
                    keyb = []

                keyboard = InlineKeyboardMarkup(keyb)

                sent = send(update, res, keyboard, random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(first=first_name))  # type: Optional[Message]

        prev_welc = sql.get_clean_pref(chat.id)
        if prev_welc:
            try:
                bot.delete_message(chat.id, prev_welc)
            except BadRequest as excp:
                pass

            if sent:
                sql.set_clean_welcome(chat.id, sent.message_id)
Example #24
0
def start(update: Update, context: CallbackContext):
    args = context.args
    uptime = get_readable_time((time.time() - StartTime))
    if update.effective_chat.type == "private":
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id, HELP_STRINGS)
            elif args[0].lower().startswith("ghelp_"):
                mod = args[0].lower().split('_', 1)[1]
                if not HELPABLE.get(mod, False):
                    return
                send_help(
                    update.effective_chat.id, HELPABLE[mod].__help__,
                    InlineKeyboardMarkup([[
                        InlineKeyboardButton(text="Back",
                                             callback_data="help_back")
                    ]]))
            elif args[0].lower() == "markdownhelp":
                IMPORTED["extras"].markdown_help_sender(update)
            elif args[0].lower() == "disasters":
                IMPORTED["disasters"].send_disasters(update)
            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(match.group(1), update.effective_user.id,
                                  False)
                else:
                    send_settings(match.group(1), update.effective_user.id,
                                  True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

        else:
            first_name = update.effective_user.first_name
            update.effective_message.reply_photo(
                SAITAMA_IMG,
                PM_START_TEXT.format(escape_markdown(first_name),
                                     escape_markdown(context.bot.first_name)),
                parse_mode=ParseMode.MARKDOWN,
                disable_web_page_preview=True,
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton(
                            text=" 👑 Summon Aku ",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username)),
                        InlineKeyboardButton(
                            text=" 🔔 Grup Chat ",
                            url="https://t.me/AnimeIndoReborn")
                    ],
                     [
                         InlineKeyboardButton(
                             text=" ✨ Help ",
                             url="https://t.me/AiKawai_bot?start=help"),
                     ],
                     [
                         InlineKeyboardButton(
                             text=" ❤️ Source Code ",
                             url="https://github.com/Nksama/hikigayarobot")
                     ]]))
    else:
        update.effective_message.reply_text(
            "Aku udah bangun kok!\n<b>Aku udah bangun dari:</b> <code>{}</code>"
            .format(uptime),
            parse_mode=ParseMode.HTML)
Example #25
0
def start(update: Update, context: CallbackContext):
    args = context.args
    uptime = get_readable_time((time.time() - StartTime))
    if update.effective_chat.type == "private":
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id, HELP_STRINGS)
            elif args[0].lower().startswith("ghelp_"):
                mod = args[0].lower().split('_', 1)[1]
                if not HELPABLE.get(mod, False):
                    return
                send_help(
                    update.effective_chat.id, HELPABLE[mod].__help__,
                    InlineKeyboardMarkup([[
                        InlineKeyboardButton(text="Back",
                                             callback_data="help_back")
                    ]]))
            elif args[0].lower() == "markdownhelp":
                IMPORTED["extras"].markdown_help_sender(update)
            elif args[0].lower() == "disasters":
                IMPORTED["disasters"].send_disasters(update)
            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(match.group(1), update.effective_user.id,
                                  False)
                else:
                    send_settings(match.group(1), update.effective_user.id,
                                  True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

        else:
            first_name = update.effective_user.first_name
            update.effective_message.reply_photo(
                SAITAMA_IMG,
                PM_START_TEXT.format(escape_markdown(first_name),
                                     escape_markdown(context.bot.first_name)),
                parse_mode=ParseMode.MARKDOWN,
                disable_web_page_preview=True,
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton(
                            text="  Support Group ",
                            url="https://t.me/mp3andvideodownloader"),
                        InlineKeyboardButton(text="  Support Channel ",
                                             url="https://t.me/mizolibrary")
                    ],
                     [
                         InlineKeyboardButton(
                             text="  Youtube Channel ",
                             url="https://www.youtube.com/c/RSR8D"),
                         InlineKeyboardButton(text="  Siam tu ",
                                              url="https://t.me/rsrmusic")
                     ],
                     [
                         InlineKeyboardButton(
                             text=" âž• I awmna group ah min add rawh ",
                             url="t.me/{}?startgroup=true".format(
                                 context.bot.username)),
                     ]]))
    else:
        update.effective_message.reply_text(
            "Hi! Online turin ka inring e😊</b> <code>{}</code>".format(
                uptime),
            parse_mode=ParseMode.HTML)
Example #26
0
def settings_button(bot: Bot, update: Update):
    query = update.callback_query
    user = update.effective_user
    mod_match = re.match(r"stngs_module\((.+?),(.+?)\)", query.data)
    prev_match = re.match(r"stngs_prev\((.+?),(.+?)\)", query.data)
    next_match = re.match(r"stngs_next\((.+?),(.+?)\)", query.data)
    back_match = re.match(r"stngs_back\((.+?)\)", query.data)
    try:
        if mod_match:
            chat_id = mod_match.group(1)
            module = mod_match.group(2)
            chat = bot.get_chat(chat_id)
            text = "تنضیمات *{}* در مورد بخش  *{}* عبارتند از:\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="بازگشت",
                                                                callback_data="stngs_back({})".format(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("خوب اینم چندتا تنضیمات خلاصه برای {} ! راحت باش گلم  "
                                     "هرکدومو میخوای وردار.".format(chat.title),
                                     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("خوب اینم چندتا تنضیمات خلاصه برای {} ! راحت باش گلم "
                                     "هرکدومو میخوای وردار.".format(chat.title),
                                     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="خوب اینم چندتا تنضیمات خلاصه برای {} ! راحت باش گلم "
                                          "هرکدومو میخوای وردار.".format(escape_markdown(chat.title)),
                                     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:
            LOGGER.exception("Exception in settings buttons. %s", str(query.data))
    def test_escape_markdown(self):
        test_str = '*bold*, _italic_, `code`, [text_link](http://github.com/)'
        expected_str = '\*bold\*, \_italic\_, \`code\`, \[text\_link](http://github.com/)'

        assert expected_str == helpers.escape_markdown(test_str)
Example #28
0
def start(update: Update, context: CallbackContext):
    args = context.args
    uptime = get_readable_time((time.time() - StartTime))
    if update.effective_chat.type == "private":
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id, HELP_STRINGS)
            elif args[0].lower().startswith("ghelp_"):
                mod = args[0].lower().split('_', 1)[1]
                if not HELPABLE.get(mod, False):
                    return
                send_help(
                    update.effective_chat.id, HELPABLE[mod].__help__,
                    InlineKeyboardMarkup([[
                        InlineKeyboardButton(
                            text="🚶Back", callback_data="help_back")
                    ]]))
            elif args[0].lower() == "markdownhelp":
                IMPORTED["extras"].markdown_help_sender(update)
            elif args[0].lower() == "disasters":
                IMPORTED["disasters"].send_disasters(update)
            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(
                        match.group(1), update.effective_user.id, False)
                else:
                    send_settings(
                        match.group(1), update.effective_user.id, True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

        else:
            first_name = update.effective_user.first_name
            update.effective_message.reply_photo(
                SAITAMA_IMG,
                PM_START_TEXT.format(
                    escape_markdown(first_name),
                    escape_markdown(context.bot.first_name)),
                parse_mode=ParseMode.MARKDOWN,
                disable_web_page_preview=True,
                reply_markup=InlineKeyboardMarkup(
                    [[
                        InlineKeyboardButton(
                            text="➕Add me to a Group➕",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username))
                    ],
                     [
                         InlineKeyboardButton(
                             text="⚙️ Support Group",
                             url=f"https://t.me/{SUPPORT_CHAT}"),
                         InlineKeyboardButton(
                             text="🔔Updates Channel",
                             url="https://t.me/iGroupZoid")
                     ],
                     [
                         InlineKeyboardButton(
                             text="📖 Getting Started Guide",
                             url="https://telegra.ph/Getting-Started-Guide-04-17")
                     ]]))
    else:
        update.effective_message.reply_text(
            "I'm online!\n<b>Up since:</b> <code>{}</code>".format(uptime),
            parse_mode=ParseMode.HTML)
Example #29
0
    def test_escape_markdown_v2(self):
        test_str = 'a_b*c[d]e (fg) h~I`>JK#L+MN -O=|p{qr}s.t! u'
        expected_str = r'a\_b\*c\[d\]e \(fg\) h\~I\`\>JK\#L\+MN \-O\=\|p\{qr\}s\.t\! u'

        assert expected_str == helpers.escape_markdown(test_str, version=2)
Example #30
0
def new_member(update: Update, context: CallbackContext):
    bot, job_queue = context.bot, context.job_queue
    chat = update.effective_chat
    user = update.effective_user
    msg = update.effective_message

    should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref(
        chat.id)
    welc_mutes = sql.welcome_mutes(chat.id)
    human_checks = sql.get_human_checks(user.id, chat.id)

    new_members = update.effective_message.new_chat_members

    for new_mem in new_members:

        welcome_log = None
        res = None
        sent = None
        should_mute = True
        welcome_bool = True
        media_wel = False

        if sw is not None:
            sw_ban = sw.get_ban(new_mem.id)
            if sw_ban:
                return

        if should_welc:

            reply = update.message.message_id
            cleanserv = sql.clean_service(chat.id)
            # Clean service welcome
            if cleanserv:
                try:
                    dispatcher.bot.delete_message(chat.id,
                                                  update.message.message_id)
                except BadRequest:
                    pass
                reply = False

            # Give the owner a special welcome
            if new_mem.id == OWNER_ID:
                update.effective_message.reply_text(
                    "Oh, Genos? Let's get this moving.",
                    reply_to_message_id=reply)
                welcome_log = (f"{html.escape(chat.title)}\n"
                               f"#USER_JOINED\n"
                               f"Bot Owner just joined the group")
                continue

            # Welcome Devs
            elif new_mem.id in DEV_USERS:
                update.effective_message.reply_text(
                    "Be cool! A member of the Heroes Association just joined.",
                    reply_to_message_id=reply,
                )
                welcome_log = (f"{html.escape(chat.title)}\n"
                               f"#USER_JOINED\n"
                               f"Bot Dev just joined the group")
                continue

            # Welcome Sudos
            elif new_mem.id in DRAGONS:
                update.effective_message.reply_text(
                    "Whoa! A Dragon disaster just joined! Stay Alert!",
                    reply_to_message_id=reply,
                )
                welcome_log = (f"{html.escape(chat.title)}\n"
                               f"#USER_JOINED\n"
                               f"Bot Sudo just joined the group")
                continue

            # Welcome Support
            elif new_mem.id in DEMONS:
                update.effective_message.reply_text(
                    "Huh! Someone with a Demon disaster level just joined!",
                    reply_to_message_id=reply,
                )
                welcome_log = (f"{html.escape(chat.title)}\n"
                               f"#USER_JOINED\n"
                               f"Bot Support just joined the group")
                continue

            # Welcome Whitelisted
            elif new_mem.id in TIGERS:
                update.effective_message.reply_text(
                    "Roar! A Tiger disaster just joined!",
                    reply_to_message_id=reply)
                welcome_log = (f"{html.escape(chat.title)}\n"
                               f"#USER_JOINED\n"
                               f"A whitelisted user joined the chat")
                continue

            # Welcome Tigers
            elif new_mem.id in WOLVES:
                update.effective_message.reply_text(
                    "Awoo! A Wolf disaster just joined!",
                    reply_to_message_id=reply)
                welcome_log = (f"{html.escape(chat.title)}\n"
                               f"#USER_JOINED\n"
                               f"A whitelisted user joined the chat")
                continue

            # Welcome yourself
            elif new_mem.id == bot.id:
                creator = None
                '''if not SaitamaRobot.ALLOW_CHATS:
                    with suppress(BadRequest):
                         update.effective_message.reply_text(f"Groups are disabled for {bot.first_name}, I'm outta here.")
                    bot.leave_chat(update.effective_chat.id)
                    return'''
                for x in bot.bot.get_chat_administrators(
                        update.effective_chat.id):
                    if x.status == "creator":
                        creator = x.user
                        break
                if creator:
                    bot.send_message(
                        JOIN_LOGGER,
                        "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>\n<b>Creator:</b> <code>{}</code>"
                        .format(html.escape(chat.title), chat.id,
                                html.escape(creator)),
                        parse_mode=ParseMode.HTML,
                    )
                else:
                    bot.send_message(
                        JOIN_LOGGER,
                        "#NEW_GROUP\n<b>Group name:</b> {}\n<b>ID:</b> <code>{}</code>"
                        .format(html.escape(chat.title), chat.id),
                        parse_mode=ParseMode.HTML,
                    )
                update.effective_message.reply_text("Watashi ga kita!",
                                                    reply_to_message_id=reply)
                continue

            else:
                buttons = sql.get_welc_buttons(chat.id)
                keyb = build_keyboard(buttons)

                if welc_type not in (sql.Types.TEXT, sql.Types.BUTTON_TEXT):
                    media_wel = True

                first_name = (
                    new_mem.first_name or "PersonWithNoName"
                )  # edge case of empty name - occurs for some bugs.

                if cust_welcome:
                    if cust_welcome == sql.DEFAULT_WELCOME:
                        cust_welcome = random.choice(
                            sql.DEFAULT_WELCOME_MESSAGES).format(
                                first=escape_markdown(first_name))

                    if new_mem.last_name:
                        fullname = escape_markdown(
                            f"{first_name} {new_mem.last_name}")
                    else:
                        fullname = escape_markdown(first_name)
                    count = chat.get_members_count()
                    mention = mention_markdown(new_mem.id,
                                               escape_markdown(first_name))
                    if new_mem.username:
                        username = "******" + escape_markdown(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(
                        cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(
                        first=escape_markdown(first_name),
                        last=escape_markdown(new_mem.last_name or first_name),
                        fullname=escape_markdown(fullname),
                        username=username,
                        mention=mention,
                        count=count,
                        chatname=escape_markdown(chat.title),
                        id=new_mem.id,
                    )

                else:
                    res = random.choice(sql.DEFAULT_WELCOME_MESSAGES).format(
                        first=escape_markdown(first_name))
                    keyb = []

                backup_message = random.choice(
                    sql.DEFAULT_WELCOME_MESSAGES).format(
                        first=escape_markdown(first_name))
                keyboard = InlineKeyboardMarkup(keyb)

        else:
            welcome_bool = False
            res = None
            keyboard = None
            backup_message = None
            reply = None

        # User exceptions from welcomemutes
        if (is_user_ban_protected(chat, new_mem.id, chat.get_member(
                new_mem.id)) or human_checks):
            should_mute = False
        # Join welcome: soft mute
        if new_mem.is_bot:
            should_mute = False

        if user.id == new_mem.id:
            if should_mute:
                if welc_mutes == "soft":
                    bot.restrict_chat_member(
                        chat.id,
                        new_mem.id,
                        permissions=ChatPermissions(
                            can_send_messages=True,
                            can_send_media_messages=False,
                            can_send_other_messages=False,
                            can_invite_users=False,
                            can_pin_messages=False,
                            can_send_polls=False,
                            can_change_info=False,
                            can_add_web_page_previews=False,
                        ),
                        until_date=(int(time.time() + 24 * 60 * 60)),
                    )
                if welc_mutes == "strong":
                    welcome_bool = False
                    if not media_wel:
                        VERIFIED_USER_WAITLIST.update({
                            new_mem.id: {
                                "should_welc": should_welc,
                                "media_wel": False,
                                "status": False,
                                "update": update,
                                "res": res,
                                "keyboard": keyboard,
                                "backup_message": backup_message,
                            }
                        })
                    else:
                        VERIFIED_USER_WAITLIST.update({
                            new_mem.id: {
                                "should_welc": should_welc,
                                "chat_id": chat.id,
                                "status": False,
                                "media_wel": True,
                                "cust_content": cust_content,
                                "welc_type": welc_type,
                                "res": res,
                                "keyboard": keyboard,
                            }
                        })
                    new_join_mem = f'<a href="tg://user?id={user.id}">{html.escape(new_mem.first_name)}</a>'
                    message = msg.reply_text(
                        f"{new_join_mem}, click the button below to prove you're human.\nYou have 120 seconds.",
                        reply_markup=InlineKeyboardMarkup([{
                            InlineKeyboardButton(
                                text="Yes, I'm human.",
                                callback_data=f"user_join_({new_mem.id})",
                            )
                        }]),
                        parse_mode=ParseMode.HTML,
                        reply_to_message_id=reply,
                    )
                    bot.restrict_chat_member(
                        chat.id,
                        new_mem.id,
                        permissions=ChatPermissions(
                            can_send_messages=False,
                            can_invite_users=False,
                            can_pin_messages=False,
                            can_send_polls=False,
                            can_change_info=False,
                            can_send_media_messages=False,
                            can_send_other_messages=False,
                            can_add_web_page_previews=False,
                        ),
                    )
                    job_queue.run_once(
                        partial(check_not_bot, new_mem, chat.id,
                                message.message_id),
                        120,
                        name="welcomemute",
                    )

        if welcome_bool:
            if media_wel:
                sent = ENUM_FUNC_MAP[welc_type](
                    chat.id,
                    cust_content,
                    caption=res,
                    reply_markup=keyboard,
                    reply_to_message_id=reply,
                    parse_mode="markdown",
                )
            else:
                sent = send(update, res, keyboard, backup_message)
            prev_welc = sql.get_clean_pref(chat.id)
            if prev_welc:
                try:
                    bot.delete_message(chat.id, prev_welc)
                except BadRequest:
                    pass

                if sent:
                    sql.set_clean_welcome(chat.id, sent.message_id)

        if welcome_log:
            return welcome_log

        return (f"{html.escape(chat.title)}\n"
                f"#USER_JOINED\n"
                f"<b>User</b>: {mention_html(user.id, user.first_name)}\n"
                f"<b>ID</b>: <code>{user.id}</code>")

    return ""
Example #31
0
    def test_escape_markdown(self):
        test_str = '*bold*, _italic_, `code`, [text_link](http://github.com/)'
        expected_str = r'\*bold\*, \_italic\_, \`code\`, \[text\_link](http://github.com/)'

        assert expected_str == helpers.escape_markdown(test_str)
Example #32
0
def get(update: Update,
        context: CallbackContext,
        notename,
        show_none=True,
        no_format=False):
    bot = context.bot
    user = update.effective_user
    chat_id = update.effective_message.chat.id
    note_chat_id = update.effective_chat.id
    note = sql.get_note(note_chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

    if note:
        if MessageHandlerChecker.check_user(update.effective_user.id):
            return
        # If we're replying to a message, reply to that message (unless it's an error)
        if message.reply_to_message:
            reply_id = message.reply_to_message.message_id
        else:
            reply_id = message.message_id
        if note.is_reply:
            if JOIN_LOGGER:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=JOIN_LOGGER,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "This message seems to have been lost - I'll remove it "
                            "from your notes list.")
                        sql.rm_note(note_chat_id, notename)
                    else:
                        raise
            else:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=chat_id,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "Looks like the original sender of this note has deleted "
                            "their message - sorry! Get your bot admin to start using a "
                            "message dump to avoid this. I'll remove this note from "
                            "your saved notes.")
                        sql.rm_note(note_chat_id, notename)
                    else:
                        raise
        else:
            VALID_NOTE_FORMATTERS = [
                "first",
                "last",
                "fullname",
                "username",
                "id",
                "chatname",
                "mention",
            ]
            valid_format = escape_invalid_curly_brackets(
                note.value, VALID_NOTE_FORMATTERS)
            if valid_format:
                if not no_format:
                    if "%%%" in valid_format:
                        split = valid_format.split("%%%")
                        if all(split):
                            text = random.choice(split)
                        else:
                            text = valid_format
                    else:
                        text = valid_format
                else:
                    text = valid_format
                text = text.format(
                    first=escape_markdown(message.from_user.first_name),
                    last=escape_markdown(message.from_user.last_name
                                         or message.from_user.first_name),
                    fullname=escape_markdown(
                        " ".join([
                            message.from_user.first_name, message.from_user.
                            last_name
                        ] if message.from_user.last_name else
                                 [message.from_user.first_name])),
                    username="******" + message.from_user.username
                    if message.from_user.username else mention_markdown(
                        message.from_user.id, message.from_user.first_name),
                    mention=mention_markdown(message.from_user.id,
                                             message.from_user.first_name),
                    chatname=escape_markdown(
                        message.chat.title if message.chat.type != "private"
                        else message.from_user.first_name),
                    id=message.from_user.id,
                )
            else:
                text = ""

            keyb = []
            parseMode = ParseMode.MARKDOWN
            buttons = sql.get_buttons(note_chat_id, notename)
            if no_format:
                parseMode = None
                text += revert_buttons(buttons)
            else:
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                setting = getprivatenotes(chat_id)
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    if setting:
                        bot.send_message(
                            user.id,
                            text,
                            parse_mode=parseMode,
                            disable_web_page_preview=True,
                            reply_markup=keyboard,
                        )
                    else:
                        delmsg = bot.send_message(
                            chat_id,
                            text,
                            reply_to_message_id=reply_id,
                            parse_mode=parseMode,
                            disable_web_page_preview=True,
                            reply_markup=keyboard,
                        )

                        cleartime = get_clearcmd(chat_id, "notes")

                        if cleartime:
                            context.dispatcher.run_async(
                                delete, delmsg, cleartime.time)

                else:
                    if setting:
                        ENUM_FUNC_MAP[note.msgtype](
                            user.id,
                            note.file,
                            caption=text,
                            reply_to_message_id=reply_id,
                            parse_mode=parseMode,
                            reply_markup=keyboard,
                        )
                    else:
                        delmsg = ENUM_FUNC_MAP[note.msgtype](
                            chat_id,
                            note.file,
                            caption=text,
                            reply_to_message_id=reply_id,
                            parse_mode=parseMode,
                            reply_markup=keyboard,
                        )

                        cleartime = get_clearcmd(chat_id, "notes")

                        if cleartime:
                            context.dispatcher.run_async(
                                delete, delmsg, cleartime.time)

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Looks like you tried to mention someone I've never seen before. If you really "
                        "want to mention them, forward one of their messages to me, and I'll be able "
                        "to tag them!")
                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "This note was an incorrectly imported file from another bot - I can't use "
                        "it. If you really need it, you'll have to save it again. In "
                        "the meantime, I'll remove it from your notes list.")
                    sql.rm_note(note_chat_id, notename)
                else:
                    message.reply_text(
                        "This note could not be sent, as it is incorrectly formatted. Ask in "
                        f"@{SUPPORT_CHAT} if you can't figure out why!")
                    LOGGER.exception(
                        "Could not parse message #%s in chat %s",
                        notename,
                        str(note_chat_id),
                    )
                    LOGGER.warning("Message was: %s", str(note.value))
        return
    elif show_none:
        message.reply_text("This note doesn't exist")
Example #33
0
 def test_markdown_invalid_version(self):
     with pytest.raises(ValueError):
         helpers.escape_markdown('abc', version=-1)
 def test_escape_markdown(self):
     test_str = "*bold*, _italic_, `code`, [text_link](http://github.com/)"
     expected_str = "\*bold\*, \_italic\_, \`code\`, \[text\_link](http://github.com/)"
     self.assertEquals(expected_str, helpers.escape_markdown(test_str))
Example #35
0
def start(bot, update):
    user_name = update.effective_user.name
    update.message.reply_text('Hello {}!'.format(escape_markdown(user_name)))
Example #36
0
import os


from telegram.ext import Updater
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram.utils.helpers import escape_markdown


BOT_TOKEN = os.environ.get('BOT_TOKEN') # remember we set this earlier :)
APP_NAME = os.environ.get('HEROKU_APP_NAME') # remember we set this earlier :)
BOT_NAME = "@blahblahblah" # please insert bot name
BOT_NAME_ESCAPED = escape_markdown(BOT_NAME)

PORT = int(os.environ.get('PORT', '80')) # this is set by heroku

WEBHOOK_PATH = "hook{}".format(BOT_TOKEN)
WEBHOOK_URL ="https://{}.herokuapp.com/{}".format(APP_NAME, WEBHOOK_PATH)

def start(bot, update):
    user_name = update.effective_user.name
    update.message.reply_text('Hello {}!'.format(escape_markdown(user_name)))


def help(bot, update):
    update.message.reply_text('this is the list of commands i support!!! \n...')

# go crazy here
def handleTextMessage(bot, update):

	text = update.message.text
    
Example #37
0
def start(update: Update, context: CallbackContext):
    args = context.args
    uptime = get_readable_time((time.time() - StartTime))
    if update.effective_chat.type == "private":
        if len(args) >= 1:
            if args[0].lower() == "help":
                send_help(update.effective_chat.id, HELP_STRINGS)
            elif args[0].lower().startswith("ghelp_"):
                mod = args[0].lower().split("_", 1)[1]
                if not HELPABLE.get(mod, False):
                    return
                send_help(
                    update.effective_chat.id,
                    HELPABLE[mod].__help__,
                    InlineKeyboardMarkup([[
                        InlineKeyboardButton(text="Back",
                                             callback_data="help_back")
                    ]]),
                )
            elif args[0].lower() == "markdownhelp":
                IMPORTED["extras"].markdown_help_sender(update)
            elif args[0].lower() == "super_users":
                IMPORTED["super_users"].send_super_users(update)
            elif args[0].lower().startswith("stngs_"):
                match = re.match("stngs_(.*)", args[0].lower())
                chat = dispatcher.bot.getChat(match.group(1))

                if is_user_admin(chat, update.effective_user.id):
                    send_settings(match.group(1), update.effective_user.id,
                                  False)
                else:
                    send_settings(match.group(1), update.effective_user.id,
                                  True)

            elif args[0][1:].isdigit() and "rules" in IMPORTED:
                IMPORTED["rules"].send_rules(update, args[0], from_pm=True)

        else:
            first_name = update.effective_user.first_name
            update.effective_message.reply_photo(
                ASTRAKOBOT_IMG,
                PM_START_TEXT.format(escape_markdown(first_name),
                                     escape_markdown(context.bot.first_name)),
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup([
                    [
                        InlineKeyboardButton(
                            text="Add AstrakoBot to your group",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username),
                        )
                    ],
                    [
                        InlineKeyboardButton(
                            text="Support Group",
                            url=f"https://t.me/AstrakoBotSupport",
                        ),
                    ],
                    [
                        InlineKeyboardButton(
                            text="Getting started guide",
                            url="https://t.me/OnePunchUpdates/29",
                        )
                    ],
                    [
                        InlineKeyboardButton(
                            text="Source code",
                            url="https://github.com/Astrako/AstrakoBot",
                        )
                    ],
                    [
                        InlineKeyboardButton(
                            text="Recommended federation",
                            url="https://t.me/ALTF4Fed",
                        )
                    ],
                ]),
            )
    else:
        update.effective_message.reply_text(
            "I'm awake already!\n<b>Haven't slept since:</b> <code>{}</code>".
            format(uptime),
            parse_mode=ParseMode.HTML,
        )