def de_json(data):
        data = super(InlineQueryResultCachedVoice, InlineQueryResultCachedVoice).de_json(data)

        data["reply_markup"] = InlineKeyboardMarkup.de_json(data.get("reply_markup"))
        data["input_message_content"] = InputMessageContent.de_json(data.get("input_message_content"))

        return InlineQueryResultCachedVoice(**data)
    def de_json(data, bot):
        data = super(InlineQueryResultAudio, InlineQueryResultAudio).de_json(data, bot)

        data["reply_markup"] = InlineKeyboardMarkup.de_json(data.get("reply_markup"), bot)
        data["input_message_content"] = InputMessageContent.de_json(data.get("input_message_content"), bot)

        return InlineQueryResultAudio(**data)
    def de_json(data):
        data = super(InlineQueryResultDocument, InlineQueryResultDocument).de_json(data)

        data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'))
        data['input_message_content'] = InputMessageContent.de_json(data.get(
            'input_message_content'))

        return InlineQueryResultDocument(**data)
    def de_json(data, bot):
        data = super(InlineQueryResultContact, InlineQueryResultContact).de_json(data, bot)

        data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'), bot)
        data['input_message_content'] = InputMessageContent.de_json(
            data.get('input_message_content'), bot)

        return InlineQueryResultContact(**data)
    def de_json(cls, data, bot):
        data = super(InlineQueryResultGame, cls).de_json(data, bot)

        if not data:
            return None

        data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'), bot)

        return cls(**data)
    def de_json(cls, data, bot):
        data = super(InlineQueryResultPhoto, cls).de_json(data, bot)

        if not data:
            return None

        data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'), bot)
        data['input_message_content'] = InputMessageContent.de_json(
            data.get('input_message_content'), bot)

        return cls(**data)
Exemplo n.º 7
0
def left_member(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    should_goodbye, cust_goodbye, cust_content, goodbye_type = sql.get_gdbye_pref(
        chat.id)
    cust_goodbye = markdown_to_html(cust_goodbye)

    if should_goodbye:
        left_mem = update.effective_message.left_chat_member
        if left_mem:

            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(
                    "Well, My mater have left, The party now ended!")
                return

            # if media goodbye, use appropriate function for it
            if goodbye_type != sql.Types.TEXT and goodbye_type != sql.Types.BUTTON_TEXT:
                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
                # Formatting text
                first_name = left_mem.first_name or "PersonWithNoName"  # edge case of empty name - occurs for some bugs.
                if left_mem.last_name:
                    fullname = "{} {}".format(first_name, left_mem.last_name)
                else:
                    fullname = first_name
                count = chat.get_members_count()
                mention = mention_html(left_mem.id, first_name)
                if left_mem.username:
                    username = "******" + escape(left_mem.username)
                else:
                    username = mention
                formatted_text = cust_goodbye.format(
                    first=escape(first_name),
                    last=escape(left_mem.last_name or first_name),
                    fullname=escape(fullname),
                    username=username,
                    mention=mention,
                    count=count,
                    chatname=escape(chat.title),
                    id=left_mem.id)
                # Build keyboard
                buttons = sql.get_gdbye_buttons(chat.id)
                keyb = build_keyboard(buttons)
                keyboard = InlineKeyboardMarkup(keyb)
                # Send message
                ENUM_FUNC_MAP[goodbye_type](chat.id,
                                            cust_content,
                                            caption=cust_goodbye,
                                            reply_markup=keyboard,
                                            parse_mode="markdown",
                                            reply_to_message_id=reply)
                return

            first_name = left_mem.first_name or "PersonWithNoName"  # edge case of empty name - occurs for some bugs.
            if cust_goodbye:
                if left_mem.last_name:
                    fullname = "{} {}".format(first_name, left_mem.last_name)
                else:
                    fullname = first_name
                count = chat.get_members_count()
                mention = mention_html(left_mem.id, first_name)
                if left_mem.username:
                    username = "******" + escape(left_mem.username)
                else:
                    username = mention

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

            else:
                res = sql.DEFAULT_GOODBYE
                keyb = []

            keyboard = InlineKeyboardMarkup(keyb)

            send(update, res, keyboard, sql.DEFAULT_GOODBYE)
Exemplo n.º 8
0
def welcome(bot: Bot, update: Update, args: List[str]):
    chat = update.effective_chat  # type: Optional[Chat]
    # if no args, show current replies.
    if len(args) == 0 or args[0].lower() == "noformat":
        noformat = args and args[0].lower() == "noformat"
        pref, welcome_m, cust_content, welcome_type = sql.get_welc_pref(
            chat.id)
        prev_welc = sql.get_clean_pref(chat.id)
        if prev_welc:
            prev_welc = True
        else:
            prev_welc = False
        cleanserv = sql.clean_service(chat.id)
        getcur, cur_value, cust_text = sql.welcome_security(chat.id)
        if getcur:
            welcsec = "True "
        else:
            welcsec = "False "
        if cur_value[:1] == "0":
            welcsec += "(Muted forever until user clicked the button)"
        else:
            welcsec += "(Muting user for {})".format(cur_value)
        text = "This chat has it's welcome setting set to: `{}`\n".format(pref)
        text += "Deleting old welcome message: `{}`\n".format(prev_welc)
        text += "Deleting service message: `{}`\n".format(cleanserv)
        text += "Muting users when they joined: `{}`\n".format(welcsec)
        text += "Mute button text: `{}`\n".format(cust_text)
        text += "\n*The welcome message (not filling the {}) is:*"
        update.effective_message.reply_text(text,
                                            parse_mode=ParseMode.MARKDOWN)

        if welcome_type == sql.Types.BUTTON_TEXT or welcome_type == sql.Types.TEXT:
            buttons = sql.get_welc_buttons(chat.id)
            if noformat:
                welcome_m += revert_buttons(buttons)
                update.effective_message.reply_text(welcome_m)

            else:
                keyb = build_keyboard(buttons)
                keyboard = InlineKeyboardMarkup(keyb)

                send(update, welcome_m, keyboard, sql.DEFAULT_WELCOME)

        else:
            buttons = sql.get_welc_buttons(chat.id)
            if noformat:
                welcome_m += revert_buttons(buttons)
                ENUM_FUNC_MAP[welcome_type](chat.id,
                                            cust_content,
                                            caption=welcome_m)

            else:
                keyb = build_keyboard(buttons)
                keyboard = InlineKeyboardMarkup(keyb)
                ENUM_FUNC_MAP[welcome_type](chat.id,
                                            cust_content,
                                            caption=welcome_m,
                                            reply_markup=keyboard,
                                            parse_mode=ParseMode.MARKDOWN,
                                            disable_web_page_preview=True)

    elif len(args) >= 1:
        if args[0].lower() in ("on", "yes"):
            sql.set_welc_preference(str(chat.id), True)
            update.effective_message.reply_text(
                "New member will be greeted with warm welcome message now!")

        elif args[0].lower() in ("off", "no"):
            sql.set_welc_preference(str(chat.id), False)
            update.effective_message.reply_text(
                "I'm sulking, Not saying hello anymore :V")

        else:
            # idek what you're writing, say yes or no
            update.effective_message.reply_text(
                "Please choose 'on/yes' or 'off/no' only!")
Exemplo n.º 9
0
def help_button(update, context):
    query = update.callback_query
    mod_match = re.match(r"help_module\((.+?)\)", query.data)
    prev_match = re.match(r"help_prev\((.+?)\)", query.data)
    next_match = re.match(r"help_next\((.+?)\)", query.data)
    back_match = re.match(r"help_back", query.data)

    print(query.message.chat.id)

    try:
        if mod_match:
            module = mod_match.group(1)
            text = (
                "「 *HELP FOR* *{}* 」\n".format(
                    HELPABLE[module].__mod_name__
                )
                + HELPABLE[module].__help__
            )
            query.message.edit_text(
                text=text,
                parse_mode=ParseMode.MARKDOWN,
                disable_web_page_preview=True,
                reply_markup=InlineKeyboardMarkup(
                    [[InlineKeyboardButton(text="「 GO BACK 」", callback_data="help_back")]]
                ),
            )

        elif prev_match:
            curr_page = int(prev_match.group(1))
            query.message.edit_text(
                text=HELP_STRINGS,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(
                    paginate_modules(curr_page - 1, HELPABLE, "help")
                ),
            )

        elif next_match:
            next_page = int(next_match.group(1))
            query.message.edit_text(
                text=HELP_STRINGS,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(
                    paginate_modules(next_page + 1, HELPABLE, "help")
                ),
            )

        elif back_match:
            query.message.edit_text(
                text=HELP_STRINGS,
                parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(
                    paginate_modules(0, HELPABLE, "help")
                ),
            )

        # ensure no spinny white circle
        context.bot.answer_callback_query(query.id)
        # query.message.delete()

    except BadRequest:
        pass
Exemplo n.º 10
0
def on_msg(update, context):
    global last_top
    try:
        message: Message = update.message
        if message is None:
            return

        if message.text == None:
            return

        is_old = False
        if message.date and (datetime.now(timezone.utc) - message.date).seconds > 300:
            is_old = True

        user_id = message.from_user.id
        username = message.from_user.name
        _chat_id = message.chat_id
        _message_id = message.message_id

        # chats control, you can define it in telegram bot father
        # if _chat_id != chat_id and user_id != admin_id:
            # return

        messageText = message.text.lower()

        # karma message
        if message.reply_to_message and message.reply_to_message.from_user.id and user_id != message.reply_to_message.from_user.id:
            karma_changed = increase_karma(message.reply_to_message.from_user.id, messageText)
            if karma_changed and not is_old:
                msg = context.bot.send_message(_chat_id, text=karma_changed)
                context.job_queue.run_once(autodelete_message, destruction_timeout, context=[msg.chat_id, msg.message_id])

        # commands
        if ("шарий" in messageText or "шарій" in messageText) and not is_old:
            msg = message.reply_video(quote=True, video=open('sh.MOV', mode='rb'))
            context.job_queue.run_once(autodelete_message, 30, context=[msg.chat_id, msg.message_id])
        if ("xiaomi" in messageText or "сяоми" in messageText) and not is_old:
            msg = context.bot.send_photo(_chat_id, reply_to_message_id=_message_id, photo=open('xiaomi.jpg', 'rb'))
            context.job_queue.run_once(autodelete_message, 30, context=[msg.chat_id, msg.message_id])
        if messageText == "гіт" and not is_old:
            reply_text = 'github.com/awitwicki/rude\\_bot'
            msg = context.bot.send_message(_chat_id, text=reply_text, parse_mode=ParseMode.MARKDOWN)
            context.job_queue.run_once(autodelete_message, 300, context=[msg.chat_id, msg.message_id])
        if messageText == "карма" and not is_old:
            reply_text = get_karma(user_id)
            msg = context.bot.send_message(_chat_id, text=reply_text, parse_mode=ParseMode.MARKDOWN)
            context.job_queue.run_once(autodelete_message, destruction_timeout, context=[msg.chat_id, msg.message_id])
        if messageText == "топ" and not is_old:
            if not last_top or (datetime.now(timezone.utc) - last_top).seconds > 300:
                reply_text, reply_markup = getTop()
                msg = context.bot.send_message(_chat_id, text=reply_text, reply_markup=reply_markup, parse_mode=ParseMode.MARKDOWN)
                context.job_queue.run_once(autodelete_message, 300, context=[msg.chat_id, msg.message_id])
                last_top = datetime.now(timezone.utc)
        if messageText == "cat" or messageText == "кот" or messageText == "кіт" and not is_old:
            cat_url = get_random_cat_image_url()
            keyboard = [[InlineKeyboardButton("😻", callback_data='like_cat|0')]]
            reply_markup = InlineKeyboardMarkup(keyboard)
            msg = context.bot.send_photo(_chat_id, cat_url, reply_markup=reply_markup)
            context.job_queue.run_once(autodelete_message, destruction_timeout, context=[msg.chat_id, msg.message_id, _message_id])

        mats = count_mats(messageText)
        add_or_update_user(user_id, username, mats)

    except Exception as e:
        print(e)
Exemplo n.º 11
0
from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, KeyboardButton
from telegram.ext import (
    Updater,
    CommandHandler,
    ConversationHandler,
    CallbackQueryHandler,
    Filters,
    MessageHandler
)
import config

languages = InlineKeyboardMarkup([
    [InlineKeyboardButton(text='Русский 🇷🇺', callback_data='ru'),
     InlineKeyboardButton(text='O`zbek 🇺🇿', callback_data='uz'),
     InlineKeyboardButton(text='English 🇬🇧', callback_data='en')]
])
# Keyboard to share contact
share_contact_ru = ReplyKeyboardMarkup([
    [KeyboardButton(text='Отправить номер телефона', request_contact=True)],
    [KeyboardButton(text='Назад 🔙')]
], resize_keyboard=True, one_time_keyboard=True)
share_contact_en = ReplyKeyboardMarkup([
    [KeyboardButton(text='Share phone number', request_contact=True)],
    [KeyboardButton(text='Back 🔙')]
], resize_keyboard=True, one_time_keyboard=True)
share_contact_uz = ReplyKeyboardMarkup([
    [KeyboardButton(text='Telefon raqamini jonatish', request_contact=True)],
    [KeyboardButton(text='Ortga qaytish 🔙')]
], resize_keyboard=True, one_time_keyboard=True)
# Keyboard to share location
share_location_ru = ReplyKeyboardMarkup([
Exemplo n.º 12
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 💃",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username)),
                        InlineKeyboardButton(text="Updates 🎉 ",
                                             url="https://t.me/TG_BotZ")
                    ],
                     [
                         InlineKeyboardButton(
                             text="Help❔ ",
                             url="https://t.me/VillainProBot?start=help"),
                         InlineKeyboardButton(
                             text="Creator 🔱 ",
                             url="https://t.me/LEGEND_OF_UNIVERSE")
                     ],
                     [
                         InlineKeyboardButton(
                             text="Source Code ⚠️  ",
                             url="https://t.me/joinchat/WCAe3d8Ou71LTErh")
                     ]]))
    else:
        update.effective_message.reply_text(
            "Heya Angella 🧚‍♀ Here PM me if you have any questions on how to use me!"
            .format(uptime),
            parse_mode=ParseMode.HTML)
Exemplo n.º 13
0
def about(update, context):
    keyboard = [[InlineKeyboardButton(
        "Source Code", url="https://github.com/NandiyaLive/xIGDLBot")]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    context.bot.send_message(chat_id=update.message.chat_id,
                             text='''I can help you to download media from any public instagram account without leaving Telegram.\n\nMade with ❤️ + python-telegram-bot by @NandiyaLive''', parse_mode=telegram.ParseMode.HTML, reply_markup=reply_markup)
Exemplo n.º 14
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 𝙍𝙔𝘼𝙉 𝙊𝙋 to your group",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username))
                    ],
                     [
                         InlineKeyboardButton(
                             text="Support Group",
                             url=f"https://t.me/COLONY_OF_WEIRDOS_2"),
                         InlineKeyboardButton(
                             text="📘 Logs",
                             url="https://t.me/RYANOP_LOGS")
                     ],
                     [
                         InlineKeyboardButton(
                             text="☑️ Source code",
                             url="WORKING IN PROGRESS......")
                     ]]))
    else:
        update.effective_message.reply_text(
            "I'm online!\n<b>Up since:</b> <code>{}</code>".format(uptime),
            parse_mode=ParseMode.HTML)
Exemplo n.º 15
0
class TestInlineQueryResultCachedMpeg4Gif:
    id = 'id'
    type = 'mpeg4_gif'
    mpeg4_file_id = 'mpeg4 file id'
    title = 'title'
    caption = 'caption'
    input_message_content = InputTextMessageContent('input_message_content')
    reply_markup = InlineKeyboardMarkup(
        [[InlineKeyboardButton('reply_markup')]])

    def test_expected_values(self, inline_query_result_cached_mpeg4_gif):
        assert inline_query_result_cached_mpeg4_gif.type == self.type
        assert inline_query_result_cached_mpeg4_gif.id == self.id
        assert inline_query_result_cached_mpeg4_gif.mpeg4_file_id == self.mpeg4_file_id
        assert inline_query_result_cached_mpeg4_gif.title == self.title
        assert inline_query_result_cached_mpeg4_gif.caption == self.caption
        assert inline_query_result_cached_mpeg4_gif.input_message_content.to_dict() == \
               self.input_message_content.to_dict()
        assert inline_query_result_cached_mpeg4_gif.reply_markup.to_dict() == \
               self.reply_markup.to_dict()

    def test_to_json(self, inline_query_result_cached_mpeg4_gif):
        json.loads(inline_query_result_cached_mpeg4_gif.to_json())

    def test_to_dict(self, inline_query_result_cached_mpeg4_gif):
        inline_query_result_cached_mpeg4_gif_dict = inline_query_result_cached_mpeg4_gif.to_dict(
        )

        assert isinstance(inline_query_result_cached_mpeg4_gif_dict, dict)
        assert inline_query_result_cached_mpeg4_gif_dict['type'] == \
               inline_query_result_cached_mpeg4_gif.type
        assert inline_query_result_cached_mpeg4_gif_dict['id'] == \
               inline_query_result_cached_mpeg4_gif.id
        assert inline_query_result_cached_mpeg4_gif_dict['mpeg4_file_id'] == \
               inline_query_result_cached_mpeg4_gif.mpeg4_file_id
        assert inline_query_result_cached_mpeg4_gif_dict['title'] == \
               inline_query_result_cached_mpeg4_gif.title
        assert inline_query_result_cached_mpeg4_gif_dict['caption'] == \
               inline_query_result_cached_mpeg4_gif.caption
        assert inline_query_result_cached_mpeg4_gif_dict['input_message_content'] == \
               inline_query_result_cached_mpeg4_gif.input_message_content.to_dict()
        assert inline_query_result_cached_mpeg4_gif_dict['reply_markup'] == \
               inline_query_result_cached_mpeg4_gif.reply_markup.to_dict()

    def test_equality(self):
        a = InlineQueryResultCachedMpeg4Gif(self.id, self.mpeg4_file_id)
        b = InlineQueryResultCachedMpeg4Gif(self.id, self.mpeg4_file_id)
        c = InlineQueryResultCachedMpeg4Gif(self.id, "")
        d = InlineQueryResultCachedMpeg4Gif("", self.mpeg4_file_id)
        e = InlineQueryResultCachedVoice(self.id, "", "")

        assert a == b
        assert hash(a) == hash(b)
        assert a is not b

        assert a == c
        assert hash(a) == hash(c)

        assert a != d
        assert hash(a) != hash(d)

        assert a != e
        assert hash(a) != hash(e)
Exemplo n.º 16
0
 def _terms_keyboard(self, username):
     menu = utl.build_menu([InlineKeyboardButton("Accept Terms", callback_data=username)])
     return InlineKeyboardMarkup(menu, resize_keyboard=True)
Exemplo n.º 17
0
def get(update, context, notename, show_none=True, no_format=False):
    bot = context.bot
    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:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    bot.send_message(chat_id,
                                     text,
                                     reply_to_message_id=reply_id,
                                     parse_mode=parseMode,
                                     disable_web_page_preview=True,
                                     reply_markup=keyboard)
                else:
                    ENUM_FUNC_MAP[note.msgtype](chat_id,
                                                note.file,
                                                caption=text,
                                                reply_to_message_id=reply_id,
                                                parse_mode=parseMode,
                                                disable_web_page_preview=True,
                                                reply_markup=keyboard)

            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")
Exemplo n.º 18
0
def reply_filter(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    to_match = extract_text(message)
    if not to_match:
        return

    # my custom thing
    if message.reply_to_message:
        message = message.reply_to_message
    ad_filter = ""
    # my custom thing

    chat_filters = sql.get_chat_triggers(chat.id)
    for keyword in chat_filters:
        pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
        if re.search(pattern, to_match, flags=re.IGNORECASE):
            filt = sql.get_filter(chat.id, keyword)
            buttons = sql.get_buttons(chat.id, filt.keyword)
            if filt.is_sticker:
                message.reply_sticker(filt.reply)
            elif filt.is_document:
                message.reply_document(filt.reply)
            elif filt.is_image:
                if len(buttons) > 0:
                    keyb = build_keyboard(buttons)
                    keyboard = InlineKeyboardMarkup(keyb)
                    message.reply_photo(filt.reply, reply_markup=keyboard)
                else:
                    message.reply_photo(filt.reply)
            elif filt.is_audio:
                message.reply_audio(filt.reply)
            elif filt.is_voice:
                message.reply_voice(filt.reply)
            elif filt.is_video:
                message.reply_video(filt.reply)
            elif filt.has_markdown:
                keyb = build_keyboard(buttons)
                keyboard = InlineKeyboardMarkup(keyb)

                should_preview_disabled = True
                if "telegra.ph" in filt.reply or "youtu.be" in filt.reply:
                    should_preview_disabled = False

                try:
                    message.reply_text(
                        ad_filter + "\n" + filt.reply,
                        parse_mode=ParseMode.MARKDOWN,
                        disable_web_page_preview=should_preview_disabled,
                        reply_markup=keyboard)
                except BadRequest as excp:
                    if excp.message == "Unsupported url protocol":
                        message.reply_text(
                            "You seem to be trying to use an unsupported url protocol. Telegram "
                            "doesn't support buttons for some protocols, such as tg://. Please try "
                            "again, or ask in @MarieSupport for help.")
                    elif excp.message == "Reply message not found":
                        bot.send_message(chat.id,
                                         filt.reply,
                                         parse_mode=ParseMode.MARKDOWN,
                                         disable_web_page_preview=True,
                                         reply_markup=keyboard)
                    else:
                        message.reply_text(
                            "This note could not be sent, as it is incorrectly formatted. Ask in "
                            "@MarieSupport if you can't figure out why!")
                        LOGGER.warning("Message %s could not be parsed",
                                       str(filt.reply))
                        LOGGER.exception(
                            "Could not parse filter %s in chat %s",
                            str(filt.keyword), str(chat.id))

            else:
                # LEGACY - all new filters will have has_markdown set to True.
                message.reply_text(ad_filter + "\n" + filt.reply)
            break
Exemplo n.º 19
0
def warn(user: User,
         chat: Chat,
         reason: str,
         message: Message,
         warner: User = None) -> str:
    if is_user_admin(chat, user.id):
        message.reply_text("i can't warn admins. They are good people !")
        return ""

    if warner:
        warner_tag = mention_html(warner.id, warner.first_name)
    else:
        warner_tag = "Automated warn filter."

    limit, soft_warn = sql.get_warn_setting(chat.id)
    num_warns, reasons = sql.warn_user(user.id, chat.id, reason)
    if num_warns >= limit:
        sql.reset_warns(user.id, chat.id)
        if soft_warn:  # kick
            chat.unban_member(user.id)
            reply = "{} warnings, {} has been kicked!".format(
                limit, mention_html(user.id, user.first_name))

        else:  # ban
            chat.kick_member(user.id)
            reply = "{} warnings, {} has been banned!".format(
                limit, mention_html(user.id, user.first_name))

        for warn_reason in reasons:
            reply += "\n - {}".format(html.escape(warn_reason))

        message.bot.send_sticker(chat.id,
                                 BAN_STICKER)  # banhammer marie sticker
        keyboard = []
        log_reason = "<b>{}:</b>" \
                     "\n#WARN_BAN" \
                     "\n<b>Admin:</b> {}" \
                     "\n<b>User:</b> {}" \
                     "\n<b>Reason:</b> {}"\
                     "\n<b>Counts:</b> <code>{}/{}</code>".format(html.escape(chat.title),
                                                                  warner_tag,
                                                                  mention_html(user.id, user.first_name),
                                                                  reason, num_warns, limit)

    else:
        keyboard = InlineKeyboardMarkup([[
            InlineKeyboardButton("Remove warn",
                                 callback_data="rm_warn({})".format(user.id))
        ]])

        reply = "{} has {}/{} warnings... watch out!".format(
            mention_html(user.id, user.first_name), num_warns, limit)
        if reason:
            reply += "\nReason for last warn:\n{}".format(html.escape(reason))

        log_reason = "<b>{}:</b>" \
                     "\n#WARN" \
                     "\n<b>Admin:</b> {}" \
                     "\n<b>User:</b> {}" \
                     "\n<b>Reason:</b> {}"\
                     "\n<b>Counts:</b> <code>{}/{}</code>".format(html.escape(chat.title),
                                                                  warner_tag,
                                                                  mention_html(user.id, user.first_name),
                                                                  reason, num_warns, limit)

    try:
        message.reply_text(reply,
                           reply_markup=keyboard,
                           parse_mode=ParseMode.HTML)
    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(reply,
                               reply_markup=keyboard,
                               parse_mode=ParseMode.HTML,
                               quote=False)
        else:
            raise
    return log_reason
Exemplo n.º 20
0
def subscription(update, context):
    keyboard = [[InlineKeyboardButton("日报提醒", callback_data='1'), InlineKeyboardButton("周报提醒", callback_data='2')]]

    update.message.reply_text('订阅:', reply_markup=InlineKeyboardMarkup(keyboard))
Exemplo n.º 21
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 = "Edward 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")))
Exemplo n.º 22
0
def help(update, context):
    keyboard = [[InlineKeyboardButton("Updates Channel", url="https://t.me/MBNUpdates"),
                 InlineKeyboardButton("Support Chat", url="https://t.me/MBNChat")]]
    reply_markup = InlineKeyboardMarkup(keyboard)

    update.message.reply_text('''<b>Usage:</b>\n/stories username - Download stories from the username’s profile.\n/igtv username - Download IGTV videos from the username’s profile.\n/feed username - Download all posts from the username’s profile as a zip file.\n\n<b>How to find the username?</b>\nOpen Instagram app & then go to a profile that you want to download items. Username must be on the top.\nIn case you are using a browser you can find it in the Address bar.\n<b>Example : </b>Username for instagram.com/rashmika_mandanna & @rashmika_mandanna is 'rashmika_mandanna' 😉''', parse_mode=telegram.ParseMode.HTML, reply_markup=reply_markup)
Exemplo n.º 23
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 your group 🔻",
                            url="t.me/{}?startgroup=true".format(
                                context.bot.username))
                    ],
                     [
                         InlineKeyboardButton(
                             text="🔹Join Our Channel🙂",
                             url=f"https://t.me/telegeekcommunity"),
                         InlineKeyboardButton(
                             text="🔸Join Our Group 🙃",
                             url="https://t.me/telegeekscommunity")
                     ],
                     [
                         InlineKeyboardButton(
                             text="Source Code 🤓",
                             url="https://github.com/Katuriki/Telegeek_Robot")
                     ]]))
    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)
Exemplo n.º 24
0
def reply_filter(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]

    to_match = extract_text(message)
    if not to_match:
        return

    chat_filters = sql.get_chat_triggers(chat.id)
    for keyword in chat_filters:
        pattern = r"( |^|[^\w])" + re.escape(keyword) + r"( |$|[^\w])"
        if re.search(pattern, to_match, flags=re.IGNORECASE):
            filt = sql.get_filter(chat.id, keyword)
            if filt.reply == "there is should be a new reply":
                buttons = sql.get_buttons(chat.id, filt.keyword)
                keyb = build_keyboard_parser(context.bot, chat.id, buttons)
                keyboard = InlineKeyboardMarkup(keyb)

                VALID_WELCOME_FORMATTERS = [
                    "first",
                    "last",
                    "fullname",
                    "username",
                    "id",
                    "chatname",
                    "mention",
                ]
                if filt.reply_text:
                    valid_format = escape_invalid_curly_brackets(
                        filt.reply_text, VALID_WELCOME_FORMATTERS)
                    if valid_format:
                        filtext = valid_format.format(
                            first=escape(message.from_user.first_name),
                            last=escape(message.from_user.last_name
                                        or message.from_user.first_name),
                            fullname=" ".join(
                                [
                                    escape(message.from_user.first_name),
                                    escape(message.from_user.last_name),
                                ] if message.from_user.last_name else
                                [escape(message.from_user.first_name)]),
                            username="******" + escape(message.from_user.username)
                            if message.from_user.username else mention_html(
                                message.from_user.id,
                                message.from_user.first_name),
                            mention=mention_html(message.from_user.id,
                                                 message.from_user.first_name),
                            chatname=escape(message.chat.title)
                            if message.chat.type != "private" else escape(
                                message.from_user.first_name),
                            id=message.from_user.id,
                        )
                    else:
                        filtext = ""
                else:
                    filtext = ""

                if filt.file_type in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        context.bot.send_message(
                            chat.id,
                            markdown_to_html(filtext),
                            reply_to_message_id=message.message_id,
                            parse_mode=ParseMode.HTML,
                            disable_web_page_preview=True,
                            reply_markup=keyboard,
                        )
                    except BadRequest as excp:
                        error_catch = get_exception(excp, filt, chat)
                        if error_catch == "noreply":
                            try:
                                context.bot.send_message(
                                    chat.id,
                                    markdown_to_html(filtext),
                                    parse_mode=ParseMode.HTML,
                                    disable_web_page_preview=True,
                                    reply_markup=keyboard,
                                )
                            except BadRequest as excp:
                                LOGGER.exception("Error in filters: ",
                                                 excp.message)
                                send_message(
                                    update.effective_message,
                                    get_exception(excp, filt, chat),
                                )
                        else:
                            try:
                                send_message(
                                    update.effective_message,
                                    get_exception(excp, filt, chat),
                                )
                            except BadRequest as excp:
                                LOGGER.exception("Failed to send message: ",
                                                 excp.message)
                else:
                    ENUM_FUNC_MAP[filt.file_type](
                        chat.id,
                        filt.file_id,
                        caption=markdown_to_html(filtext),
                        reply_to_message_id=message.message_id,
                        parse_mode=ParseMode.HTML,
                        disable_web_page_preview=True,
                        reply_markup=keyboard,
                    )
                break
            if filt.is_sticker:
                message.reply_sticker(filt.reply)
            elif filt.is_document:
                message.reply_document(filt.reply)
            elif filt.is_image:
                message.reply_photo(filt.reply)
            elif filt.is_audio:
                message.reply_audio(filt.reply)
            elif filt.is_voice:
                message.reply_voice(filt.reply)
            elif filt.is_video:
                message.reply_video(filt.reply)
            elif filt.has_markdown:
                buttons = sql.get_buttons(chat.id, filt.keyword)
                keyb = build_keyboard_parser(context.bot, chat.id, buttons)
                keyboard = InlineKeyboardMarkup(keyb)

                try:
                    send_message(
                        update.effective_message,
                        filt.reply,
                        parse_mode=ParseMode.MARKDOWN,
                        disable_web_page_preview=True,
                        reply_markup=keyboard,
                    )
                except BadRequest as excp:
                    if excp.message == "Unsupported url protocol":
                        try:
                            send_message(
                                update.effective_message,
                                "You seem to be trying to use an unsupported url protocol. "
                                "Telegram doesn't support buttons for some protocols, such as tg://. Please try "
                                "again...",
                            )
                        except BadRequest as excp:
                            LOGGER.exception("Error in filters: ",
                                             excp.message)
                    elif excp.message == "Reply message not found":
                        try:
                            context.bot.send_message(
                                chat.id,
                                filt.reply,
                                parse_mode=ParseMode.MARKDOWN,
                                disable_web_page_preview=True,
                                reply_markup=keyboard,
                            )
                        except BadRequest as excp:
                            LOGGER.exception("Error in filters: ",
                                             excp.message)
                    else:
                        try:
                            send_message(
                                update.effective_message,
                                "This message couldn't be sent as it's incorrectly formatted.",
                            )
                        except BadRequest as excp:
                            LOGGER.exception("Error in filters: ",
                                             excp.message)
                        LOGGER.warning("Message %s could not be parsed",
                                       str(filt.reply))
                        LOGGER.exception(
                            "Could not parse filter %s in chat %s",
                            str(filt.keyword),
                            str(chat.id),
                        )

            else:
                # LEGACY - all new filters will have has_markdown set to True.
                try:
                    send_message(update.effective_message, filt.reply)
                except BadRequest as excp:
                    LOGGER.exception("Error in filters: ", excp.message)
            break
Exemplo n.º 25
0
    def _get_msg_kwargs(self, data):
        """Get parameters in message data kwargs."""
        def _make_row_inline_keyboard(row_keyboard):
            """Make a list of InlineKeyboardButtons.

            It can accept:
              - a list of tuples like:
                `[(text_b1, data_callback_b1),
                (text_b2, data_callback_b2), ...]
              - a string like: `/cmd1, /cmd2, /cmd3`
              - or a string like: `text_b1:/cmd1, text_b2:/cmd2`
            """

            buttons = []
            if isinstance(row_keyboard, str):
                for key in row_keyboard.split(","):
                    if ":/" in key:
                        # commands like: 'Label:/cmd' become ('Label', '/cmd')
                        label = key.split(":/")[0]
                        command = key[len(label) + 1:]
                        buttons.append(
                            InlineKeyboardButton(label, callback_data=command))
                    else:
                        # commands like: '/cmd' become ('CMD', '/cmd')
                        label = key.strip()[1:].upper()
                        buttons.append(
                            InlineKeyboardButton(label, callback_data=key))
            elif isinstance(row_keyboard, list):
                for entry in row_keyboard:
                    text_btn, data_btn = entry
                    buttons.append(
                        InlineKeyboardButton(text_btn, callback_data=data_btn))
            else:
                raise ValueError(str(row_keyboard))
            return buttons

        # Defaults
        params = {
            ATTR_PARSER: self._parse_mode,
            ATTR_DISABLE_NOTIF: False,
            ATTR_DISABLE_WEB_PREV: None,
            ATTR_REPLY_TO_MSGID: None,
            ATTR_REPLYMARKUP: None,
            ATTR_TIMEOUT: None,
            ATTR_MESSAGE_TAG: None,
        }
        if data is not None:
            if ATTR_PARSER in data:
                params[ATTR_PARSER] = self._parsers.get(
                    data[ATTR_PARSER], self._parse_mode)
            if ATTR_TIMEOUT in data:
                params[ATTR_TIMEOUT] = data[ATTR_TIMEOUT]
            if ATTR_DISABLE_NOTIF in data:
                params[ATTR_DISABLE_NOTIF] = data[ATTR_DISABLE_NOTIF]
            if ATTR_DISABLE_WEB_PREV in data:
                params[ATTR_DISABLE_WEB_PREV] = data[ATTR_DISABLE_WEB_PREV]
            if ATTR_REPLY_TO_MSGID in data:
                params[ATTR_REPLY_TO_MSGID] = data[ATTR_REPLY_TO_MSGID]
            if ATTR_MESSAGE_TAG in data:
                params[ATTR_MESSAGE_TAG] = data[ATTR_MESSAGE_TAG]
            # Keyboards:
            if ATTR_KEYBOARD in data:
                keys = data.get(ATTR_KEYBOARD)
                keys = keys if isinstance(keys, list) else [keys]
                if keys:
                    params[ATTR_REPLYMARKUP] = ReplyKeyboardMarkup(
                        [[key.strip() for key in row.split(",")]
                         for row in keys])
                else:
                    params[ATTR_REPLYMARKUP] = ReplyKeyboardRemove(True)

            elif ATTR_KEYBOARD_INLINE in data:
                keys = data.get(ATTR_KEYBOARD_INLINE)
                keys = keys if isinstance(keys, list) else [keys]
                params[ATTR_REPLYMARKUP] = InlineKeyboardMarkup(
                    [_make_row_inline_keyboard(row) for row in keys])
        return params
Exemplo n.º 26
0
		if verbox[1] == x:
			ver1 = True
		else:
			ver1 = False
		for y in range(3):
			y += 1
			if verbox[0] == y and ver1:
				verify_link = real_btn
				linebox.append(InlineKeyboardButton(text=verify_link, callback_data="verify_me(y|{}|{})".format(user_id, chat_id)))
			else:
				verify_link = random.choice(verify_code)
				linebox.append(InlineKeyboardButton(text=verify_link, callback_data="verify_me(n|{}|{})".format(user_id, chat_id)))
				verify_code.remove(verify_emoji)
		buttons.append(linebox)
		linebox = []
	context.bot.send_photo(user_id, photo=verify_code_links[real_btn], caption="Please select matching link below:", parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(buttons))

def verify_button_pressed(update, context):
	chat = update.effective_chat  # type: Optional[Chat]
	user = update.effective_user  # type: Optional[User]
	query = update.callback_query  # type: Optional[CallbackQuery]
	match = re.match(r"verify_me\((.+?)\)", query.data)
	match = match.group(1).split("|")
	is_ok = match[0]
	user_id = match[1]
	chat_id = match[2]
	message = update.effective_message  # type: Optional[Message]
	print("-> {} was clicked welcome verify button".format(user.id))
	if is_ok == "y":
		if context.bot.getChatMember(chat_id, user_id).status in ('left'):
			query.answer(text="Failed: user left chat")
Exemplo n.º 27
0
def new_member(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]

    prev_welc = sql.get_clean_pref(chat.id)
    if prev_welc:
        # Delete the service message as well
        update.effective_message.delete()


    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:
            # Don't welcome yourself
            if 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]

        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)
Exemplo n.º 28
0
from .models import Captcha, orm

db = TinyDB('.userdata')
rules = json.loads(requests.get(RULES_URI).text)

mute_perms = ChatPermissions(can_send_messages=False,
                             can_send_media_messages=False,
                             can_send_polls=False,
                             can_send_other_messages=False)

unmute_perms = ChatPermissions(can_send_messages=True,
                               can_send_media_messages=True,
                               can_send_polls=False,
                               can_send_other_messages=False)

okay_keyboard = InlineKeyboardMarkup(
    [[InlineKeyboardButton(text='Okay', callback_data='self_destruct')]])


def get_mention(user):
    name = user.username if user.username else user.id
    return mention_markdown(user_id=user.id, name=str(name), version=2)


# Check if a database entry  exists with the given
# Group id and user id
# For use with tinydb - will be removed
def user_exists(user_id, group_id):
    User = Query()
    user = db.search((User.group_id == group_id) & (User.user_id == user_id))
    return len(user)
Exemplo n.º 29
0
def makepack_internal(
    update,
    context,
    msg,
    user,
    emoji,
    packname,
    packnum,
    png_sticker=None,
    tgs_sticker=None,
):
    name = user.first_name
    name = name[:50]
    try:
        extra_version = ""
        if packnum > 0:
            extra_version = " " + str(packnum)
        if png_sticker:
            success = context.bot.create_new_sticker_set(
                user.id,
                packname,
                f"{name}s kang pack" + extra_version,
                png_sticker=png_sticker,
                emojis=emoji,
            )
        if tgs_sticker:
            success = context.bot.create_new_sticker_set(
                user.id,
                packname,
                f"{name}s animated kang pack" + extra_version,
                tgs_sticker=tgs_sticker,
                emojis=emoji,
            )

    except TelegramError as e:
        print(e)
        if e.message == "Sticker set name is already occupied":
            msg.reply_text(
                "Your pack can be found [here](t.me/addstickers/%s)" %
                packname,
                parse_mode=ParseMode.MARKDOWN,
            )
        elif e.message in ("Peer_id_invalid", "bot was blocked by the user"):
            msg.reply_text(
                "Contact me in PM first.",
                reply_markup=InlineKeyboardMarkup([[
                    InlineKeyboardButton(text="Start",
                                         url=f"t.me/{context.bot.username}")
                ]]),
            )
        elif e.message == "Internal Server Error: created sticker set not found (500)":
            msg.reply_text(
                "Sticker pack successfully created. Get it [here](t.me/addstickers/%s)"
                % packname,
                parse_mode=ParseMode.MARKDOWN,
            )
        return

    if success:
        msg.reply_text(
            "Sticker pack successfully created. Get it [here](t.me/addstickers/%s)"
            % packname,
            parse_mode=ParseMode.MARKDOWN,
        )
    else:
        msg.reply_text(
            "Failed to create sticker pack. Possibly due to blek mejik.")
Exemplo n.º 30
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))
Exemplo n.º 31
0
def new_member(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]

    should_welc, cust_welcome, cust_content, welc_type = sql.get_welc_pref(
        chat.id)
    cust_welcome = markdown_to_html(cust_welcome)

    if should_welc:
        sent = None
        new_members = update.effective_message.new_chat_members
        for new_mem in new_members:
            # Give start information when add bot to group

            if is_user_gbanned(new_mem.id):
                return

            if new_mem.id == bot.id:
                bot.send_message(
                    MESSAGE_DUMP,
                    "I have been added to {} with ID: <pre>{}</pre>".format(
                        chat.title, chat.id),
                    parse_mode=ParseMode.HTML)
                bot.send_message(
                    chat.id,
                    "Thanks For Adding Me. Contact Me In PM Or Hit /help To Know More About My Full Potential Use!"
                )

            else:
                # If welcome message is media, send with appropriate function
                if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT:
                    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
                    # Formatting text
                    first_name = new_mem.first_name or "PersonWithNoName"  # edge case of empty name - occurs for some bugs.
                    if new_mem.last_name:
                        fullname = "{} {}".format(first_name,
                                                  new_mem.last_name)
                    else:
                        fullname = first_name
                    count = chat.get_members_count()
                    mention = mention_html(new_mem.id, first_name)
                    if new_mem.username:
                        username = "******" + escape(new_mem.username)
                    else:
                        username = mention
                    formatted_text = cust_welcome.format(
                        first=escape(first_name),
                        last=escape(new_mem.last_name or first_name),
                        fullname=escape(fullname),
                        username=username,
                        mention=mention,
                        count=count,
                        chatname=escape(chat.title),
                        id=new_mem.id)
                    # Build keyboard
                    buttons = sql.get_welc_buttons(chat.id)
                    keyb = build_keyboard(buttons)
                    getsec, mutetime, custom_text = sql.welcome_security(
                        chat.id)

                    member = chat.get_member(new_mem.id)
                    # If user ban protected don't apply security on him
                    if is_user_ban_protected(chat, new_mem.id,
                                             chat.get_member(new_mem.id)):
                        pass
                    elif getsec:
                        # If mute time is turned on
                        if mutetime:
                            if mutetime[:1] == "0":
                                if member.can_send_messages is None or member.can_send_messages:
                                    try:
                                        bot.restrict_chat_member(
                                            chat.id,
                                            new_mem.id,
                                            can_send_messages=False)
                                        canrest = True
                                    except BadRequest:
                                        canrest = False
                                else:
                                    canrest = False

                            else:
                                mutetime = extract_time(
                                    update.effective_message, mutetime)

                                if member.can_send_messages is None or member.can_send_messages:
                                    try:
                                        bot.restrict_chat_member(
                                            chat.id,
                                            new_mem.id,
                                            until_date=mutetime,
                                            can_send_messages=False)
                                        canrest = True
                                    except BadRequest:
                                        canrest = False
                                else:
                                    canrest = False

                        # If security welcome is turned on
                        if canrest:
                            sql.add_to_userlist(chat.id, new_mem.id)
                            keyb.append([
                                InlineKeyboardButton(
                                    text=str(custom_text),
                                    callback_data="check_bot_({})".format(
                                        new_mem.id))
                            ])
                    keyboard = InlineKeyboardMarkup(keyb)
                    # Send message
                    ENUM_FUNC_MAP[welc_type](chat.id,
                                             cust_content,
                                             caption=formatted_text,
                                             reply_markup=keyboard,
                                             parse_mode="markdown",
                                             reply_to_message_id=reply)
                    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_html(new_mem.id, first_name)
                    if new_mem.username:
                        username = "******" + escape(new_mem.username)
                    else:
                        username = mention

                    valid_format = escape_invalid_curly_brackets(
                        cust_welcome, VALID_WELCOME_FORMATTERS)
                    res = valid_format.format(first=escape(first_name),
                                              last=escape(new_mem.last_name
                                                          or first_name),
                                              fullname=escape(fullname),
                                              username=username,
                                              mention=mention,
                                              count=count,
                                              chatname=escape(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 = []

                getsec, mutetime, custom_text = sql.welcome_security(chat.id)
                member = chat.get_member(new_mem.id)
                # If user ban protected don't apply security on him
                if is_user_ban_protected(chat, new_mem.id,
                                         chat.get_member(new_mem.id)):
                    pass
                elif getsec:
                    if mutetime:
                        if mutetime[:1] == "0":

                            if member.can_send_messages is None or member.can_send_messages:
                                try:
                                    bot.restrict_chat_member(
                                        chat.id,
                                        new_mem.id,
                                        can_send_messages=False)
                                    canrest = True
                                except BadRequest:
                                    canrest = False
                            else:
                                canrest = False

                        else:
                            mutetime = extract_time(update.effective_message,
                                                    mutetime)

                            if member.can_send_messages is None or member.can_send_messages:
                                try:
                                    bot.restrict_chat_member(
                                        chat.id,
                                        new_mem.id,
                                        until_date=mutetime,
                                        can_send_messages=False)
                                    canrest = True
                                except BadRequest:
                                    canrest = False
                            else:
                                canrest = False

                    if canrest:
                        sql.add_to_userlist(chat.id, new_mem.id)
                        keyb.append([
                            InlineKeyboardButton(
                                text=str(custom_text),
                                callback_data="check_bot_({})".format(
                                    new_mem.id))
                        ])
                keyboard = InlineKeyboardMarkup(keyb)

                sent = send(update, res, keyboard,
                            sql.DEFAULT_WELCOME.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)
    def de_json(data, bot):
        data = super(InlineQueryResultGame, InlineQueryResultGame).de_json(data, bot)

        data['reply_markup'] = InlineKeyboardMarkup.de_json(data.get('reply_markup'), bot)

        return InlineQueryResultGame(**data)
Exemplo n.º 33
0
def new_member(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    bot = context.bot

    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:
                bot.send_message(
                    chat.id,
                    "Ayyyy. My creator just joined the group Boom Boom🤪")
                continue
            # Give the sudo a sweet welcome
            if new_mem.id == 642191066:
                bot.send_message(chat.id,
                                 "Yo,Sir Mayank is just joined this group😎")
                continue

            # Give start information when add bot to group
            elif new_mem.id == bot.id:
                bot.send_message(
                    MESSAGE_DUMP,
                    "I have been added to {} with ID: <pre>{}</pre>".format(
                        chat.title, chat.id),
                    parse_mode=ParseMode.HTML)
                bot.send_message(
                    chat.id,
                    "Thanks for adding me into your group! Checkout our Group!"
                )

            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,
                                               chatname=chat.title))

                #Federations Ban
                if welcome_fed(bot, update) == True:
                    continue

                #Clean service welcome
                if sql.clean_service(chat.id) == True:
                    bot.delete_message(chat.id, update.message.message_id)

                #If user ban protected don't apply security on him
                if is_user_ban_protected(chat, new_mem.id,
                                         chat.get_member(new_mem.id)):
                    continue

                #Security soft mode
                if sql.welcome_security(chat.id) == "soft":
                    bot.restrict_chat_member(chat.id,
                                             new_mem.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)))

                #Add "I'm not bot button if enabled hard security"
                if sql.welcome_security(chat.id) == "hard":
                    update.effective_message.reply_text(
                        "Hi {}, click on button below to prove you not a bot.".
                        format(new_mem.first_name),
                        reply_markup=InlineKeyboardMarkup([[
                            InlineKeyboardButton(
                                text="✅ Click here to talk ✅ ",
                                callback_data="check_bot_({})".format(
                                    new_mem.id))
                        ]]))
                    #Mute user
                    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)

        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)
Exemplo n.º 34
0
def left_member(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    bot = context.bot
    should_goodbye, cust_goodbye, goodbye_type = sql.get_gdbye_pref(chat.id)
    if should_goodbye:
        left_mem = update.effective_message.left_chat_member
        if left_mem:

            # 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("RIP Master")
                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 left_mem.last_name:
                    fullname = "{} {}".format(first_name, left_mem.last_name)
                else:
                    fullname = first_name
                count = chat.get_members_count()
                mention = mention_markdown(left_mem.id,
                                           escape_markdown(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 = sql.DEFAULT_GOODBYE
                keyb = []

            keyboard = InlineKeyboardMarkup(keyb)

            send(update, res, keyboard, sql.DEFAULT_GOODBYE)

            #Clean service goodbye
            if sql.clean_service(chat.id) == True:
                bot.delete_message(chat.id, update.message.message_id)
Exemplo n.º 35
0
from bs4 import BeautifulSoup as bs
from telegram import Bot, InlineKeyboardButton, InlineKeyboardMarkup
# from instaloader import Instaloader, Profile, Post
import sys
import shutil
import glob
import os
import zipfile
import pathlib

bot_token = os.environ.get("BOT_TOKEN", "1814393951:AAFOeXIa_5Lr_94AUvlo6INinJDu4zw0tKo")
bot = Bot(token=bot_token)

help_keyboard = [[InlineKeyboardButton("Updates Channel", url="https://t.me/MBNUpdates"),
                  InlineKeyboardButton("Support Chat", url="https://t.me/MBNChat")]]
help_reply_markup = InlineKeyboardMarkup(help_keyboard)


def start(update, context):
    user = update.message.from_user
    chat_member = context.bot.get_chat_member(
        chat_id='-1001225141087', user_id=update.message.chat_id)
    status = chat_member["status"]
    if(status == 'left'):
        context.bot.send_message(chat_id=update.message.chat_id,
                                 text=f"Hi {user.first_name}, to use me you have to be a member of the updates channel in order to stay updated with the latest developments.\nPlease click below button to join and /start the bot again.", reply_markup=help_reply_markup)
        return
    else:
        context.bot.send_message(chat_id=update.message.chat_id,
                                 text=f"Hi {user.first_name}!\nI'm Instagram Media Downloader Bot. I can help you to download Stories and IGTV Videos from any public instagram account.\nPlease read the /help before using me.", parse_mode=telegram.ParseMode.HTML, reply_markup=help_reply_markup)
Exemplo n.º 36
0
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.

from telegram import InlineKeyboardButton, InlineKeyboardMarkup, ParseMode
from config import Config

#Inline Keyboard Button
keyboard = [[InlineKeyboardButton("🔹OWNER🔹", url=Config.SOURCE)],
            [
                InlineKeyboardButton("🔹Join Group🔹",
                                     url="https://t.me/mpazaanbot")
            ]]

#The Keyboard On Up👆
reply_markup = InlineKeyboardMarkup(keyboard)


#Send Start Message
def startMessage(update, context):
    try:
        update.message.reply_text(Config.START_TEXT.format(
            update.message.from_user.full_name, update.message.chat.id),
                                  reply_markup=reply_markup,
                                  parse_mode=ParseMode.MARKDOWN)
    except Exception as e:
        update.message.reply_text(e)


#Help Message
def helpMessage(update, context):
Exemplo n.º 37
0
def send_start(bot, update):
    #Try to remove old message
    try:
        query = update.callback_query
        query.message.delete()
    except:
        pass

    chat = update.effective_chat  # type: Optional[Chat]
    first_name = update.effective_user.first_name 
    text = PM_START

    keyboard = [[InlineKeyboardButton(text="馃嚠馃嚦 Language", callback_data="set_lang_")]]
    keyboard += [[InlineKeyboardButton(text="馃洜 Reporting", callback_data="cntrl_panel_M"), 
        InlineKeyboardButton(text="鉂� Help", callback_data="help_back")]]

    update.effective_message.reply_text(PM_START.format(escape_markdown(first_name), bot.first_name), reply_markup=InlineKeyboardMarkup(keyboard), disable_web_page_preview=True, parse_mode=ParseMode.MARKDOWN)