Exemplo n.º 1
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_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:
                        filtext = ""
                else:
                    filtext = ""

                if filt.file_type in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        context.bot.send_message(
                            chat.id,
                            filtext,
                            reply_to_message_id=message.message_id,
                            parse_mode="markdown",
                            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,
                                    filtext,
                                    parse_mode="markdown",
                                    disable_web_page_preview=True,
                                    reply_markup=keyboard)
                            except BadRequest as excp:
                                LOGGER.exception("Gagal mengirim pesan: " +
                                                 excp.message)
                                send_message(
                                    update.effective_message,
                                    tl(update.effective_message,
                                       get_exception(excp, filt, chat)))
                                pass
                        else:
                            try:
                                send_message(
                                    update.effective_message,
                                    tl(update.effective_message,
                                       get_exception(excp, filt, chat)))
                            except BadRequest as excp:
                                LOGGER.exception("Gagal mengirim pesan: " +
                                                 excp.message)
                                pass
                else:
                    ENUM_FUNC_MAP[filt.file_type](
                        chat.id,
                        filt.file_id,
                        caption=filtext,
                        reply_to_message_id=message.message_id,
                        parse_mode="markdown",
                        disable_web_page_preview=True,
                        reply_markup=keyboard)
                break
            else:
                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,
                                    tl(
                                        update.effective_message,
                                        "Anda tampaknya mencoba menggunakan protokol url yang tidak didukung. Telegram "
                                        "tidak mendukung tombol untuk beberapa protokol, seperti tg://. Silakan coba "
                                        "lagi."))
                            except BadRequest as excp:
                                LOGGER.exception("Gagal mengirim pesan: " +
                                                 excp.message)
                                pass
                        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("Gagal mengirim pesan: " +
                                                 excp.message)
                                pass
                        else:
                            try:
                                send_message(
                                    update.effective_message,
                                    tl(
                                        update.effective_message,
                                        "Catatan ini tidak dapat dikirim karena formatnya salah."
                                    ))
                            except BadRequest as excp:
                                LOGGER.exception("Gagal mengirim pesan: " +
                                                 excp.message)
                                pass
                            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("Gagal mengirim pesan: " +
                                         excp.message)
                        pass
                break
Exemplo n.º 2
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)
	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 OWNER_SPECIAL and left_mem.id == OWNER_ID:
				send_message(update.effective_message, tl(update.effective_message, "Selamat jalan master 😢"))
				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_markdown(left_mem.id, first_name)
				if left_mem.username:
					username = "******" + escape_markdown(left_mem.username)
				else:
					username = mention
				if cust_goodbye:
					formatted_text = cust_goodbye.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)
				else:
					formatted_text = ""
				# Build keyboard
				buttons = sql.get_gdbye_buttons(chat.id)
				keyb = build_keyboard(buttons)
				keyboard = InlineKeyboardMarkup(keyb)
				# Send message
				try:
					ENUM_FUNC_MAP[goodbye_type](chat.id, cust_content, caption=formatted_text, reply_markup=keyboard, parse_mode="markdown", reply_to_message_id=reply)
				except BadRequest:
					send_message(update.effective_message, tl(update.effective_message, "Catatan: Terjadi kesalahan saat mengirim pesan kustom. Harap perbarui."))
				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, 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)
				if valid_format:
					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)
				else:
					res = ""
				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.º 3
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if conn:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

    if note:
        # 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 MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=MESSAGE_DUMP,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Pesan ini tampaknya telah hilang - saya akan menghapusnya "
                                "dari daftar catatan Anda."))
                        sql.rm_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":
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Sepertinya pengirim asli dari catatan ini telah dihapus "
                                "pesan mereka - maaf! Dapatkan admin bot Anda untuk mulai menggunakan "
                                "pesan dump untuk menghindari ini. Saya akan menghapus catatan ini dari "
                                "catatan tersimpan Anda."))
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
        else:

            VALID_WELCOME_FORMATTERS = [
                'first', 'last', 'fullname', 'username', 'id', 'chatname',
                'mention', 'rules'
            ]
            valid_format = escape_invalid_curly_brackets(
                note.value, VALID_WELCOME_FORMATTERS)
            if valid_format:
                text = valid_format.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,
                    rules="http://t.me/{}?start={}".format(
                        bot.username, chat_id))
            else:
                text = ""

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

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                is_private, is_delete = sql.get_private_note(chat.id)
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        if is_delete:
                            update.effective_message.delete()
                        if is_private:
                            bot.send_message(user.id,
                                             text,
                                             parse_mode=parseMode,
                                             disable_web_page_preview=True,
                                             reply_markup=keyboard)
                        else:
                            bot.send_message(send_id,
                                             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 == "Wrong http url":
                            failtext = tl(
                                update.effective_message,
                                "Kesalahan: URL pada tombol tidak valid! Harap perbaruhi catatan ini."
                            )
                            failtext += "\n\n```\n{}```".format(
                                note.value + revert_buttons(buttons))
                            send_message(update.effective_message,
                                         failtext,
                                         parse_mode="markdown")
                        elif excp.message == "Button_url_invalid":
                            failtext = tl(
                                update.effective_message,
                                "Kesalahan: URL pada tombol tidak valid! Harap perbaruhi catatan ini."
                            )
                            failtext += "\n\n```\n{}```".format(
                                note.value + revert_buttons(buttons))
                            send_message(update.effective_message,
                                         failtext,
                                         parse_mode="markdown")
                        elif excp.message == "Message can't be deleted":
                            pass
                        elif excp.message == "Have no rights to send a message":
                            pass
                    except Unauthorized as excp:
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Hubungi saya di PM dulu untuk mendapatkan catatan ini."
                            ),
                            parse_mode="markdown")
                        pass
                else:
                    try:
                        if is_delete:
                            update.effective_message.delete()
                        if is_private:
                            ENUM_FUNC_MAP[note.msgtype](
                                user.id,
                                note.file,
                                caption=text,
                                parse_mode=parseMode,
                                disable_web_page_preview=True,
                                reply_markup=keyboard)
                        else:
                            ENUM_FUNC_MAP[note.msgtype](
                                send_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 == "Message can't be deleted":
                            pass
                        elif excp.message == "Have no rights to send a message":
                            pass
                    except Unauthorized as excp:
                        send_message(
                            update.effective_message,
                            tl(
                                update.effective_message,
                                "Hubungi saya di PM dulu untuk mendapatkan catatan ini."
                            ),
                            parse_mode="markdown")
                        pass

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "Sepertinya Anda mencoba menyebutkan seseorang yang belum pernah saya lihat sebelumnya. "
                            "Jika kamu benar-benar ingin menyebutkannya, meneruskan salah satu pesan mereka kepada saya, "
                            "dan saya akan dapat untuk menandai mereka!"))
                elif FILE_MATCHER.match(note.value):
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "Catatan ini adalah file yang salah diimpor dari bot lain - saya tidak bisa menggunakan "
                            "ini. Jika Anda benar-benar membutuhkannya, Anda harus menyimpannya lagi. "
                            "Sementara itu, saya akan menghapusnya dari daftar catatan Anda."
                        ))
                    sql.rm_note(chat_id, notename)
                else:
                    send_message(
                        update.effective_message,
                        tl(
                            update.effective_message,
                            "Catatan ini tidak dapat dikirim karena formatnya salah."
                        ))
                    LOGGER.exception(
                        "Tidak dapat menguraikan pesan #%s di obrolan %s",
                        notename, str(chat_id))
                    LOGGER.warning("Pesan itu: %s", str(note.value))
        return
    elif show_none:
        send_message(update.effective_message,
                     tl(update.effective_message, "Catatan ini tidak ada"))
Exemplo n.º 4
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)
	cleanserv = sql.clean_service(chat.id)
	if cleanserv:
		new_members = update.effective_message.new_chat_members
		for new_mem in new_members:
			try:
				dispatcher.bot.delete_message(chat.id, update.message.message_id)
			except BadRequest:
				pass
	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 OWNER_SPECIAL and new_mem.id == OWNER_ID:
				if cleanserv:
					bot.send_message(chat.id, tl(update.effective_message, "Master telah pulang! Mari kita mulai pesta ini! 😆"))
				else:
					send_message(update.effective_message, tl(update.effective_message, "Master telah pulang! Mari kita mulai pesta ini! 😆"))
				continue

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

			else:
				# If welcome message is media, send with appropriate function
				if welc_type != sql.Types.TEXT and welc_type != sql.Types.BUTTON_TEXT:
					reply = update.message.message_id
					# Clean service welcome
					if cleanserv:
						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_markdown(new_mem.id, first_name)
					if new_mem.username:
						username = "******" + escape_markdown(new_mem.username)
					else:
						username = mention
					if cust_welcome:
						formatted_text = cust_welcome.format(first=escape_markdown(first_name),
											  last=escape_markdown(new_mem.last_name or first_name),
											  fullname=escape_markdown(fullname), username=username, mention=mention,
											  count=count, chatname=escape_markdown(chat.title), id=new_mem.id)
					else:
						formatted_text = ""
					# Build keyboard
					buttons = sql.get_welc_buttons(chat.id)
					keyb = build_keyboard(buttons)
					getsec, mutetime, custom_text = sql.welcome_security(chat.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":
								try:
									bot.restrict_chat_member(chat.id, new_mem.id, can_send_messages=False)
									canrest = True
								except BadRequest:
									canrest = False
							else:
								mutetime = extract_time(update.effective_message, mutetime)
								try:
									bot.restrict_chat_member(chat.id, new_mem.id, until_date=mutetime, can_send_messages=False)
									canrest = True
								except BadRequest:
									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
					try:
						sent = ENUM_FUNC_MAP[welc_type](chat.id, cust_content, caption=formatted_text, reply_markup=keyboard, parse_mode="markdown", reply_to_message_id=reply)
					except BadRequest:
						sent = send_message(update.effective_message, tl(update.effective_message, "Catatan: Terjadi kesalahan saat mengirim pesan kustom. Harap perbarui."))
					return
				else:
					# 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)
						if valid_format:
							res = valid_format.format(first=escape_markdown(first_name),
												  last=escape_markdown(new_mem.last_name or first_name),
												  fullname=escape_markdown(fullname), username=username, mention=mention,
												  count=count, chatname=escape_markdown(chat.title), id=new_mem.id)
						else:
							res = ""
						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)
					
					# 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":
								try:
									bot.restrict_chat_member(chat.id, new_mem.id, can_send_messages=False)
									canrest = True
								except BadRequest:
									canrest = False
							else:
								mutetime = extract_time(update.effective_message, mutetime)
								try:
									bot.restrict_chat_member(chat.id, new_mem.id, until_date=mutetime, can_send_messages=False)
									canrest = True
								except BadRequest:
									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:
					if int(prev_welc) != 1:
						bot.delete_message(chat.id, prev_welc)
				except BadRequest as excp:
				   pass

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

	fed_id = fedsql.get_fed_id(chat.id)
	if fed_id == "TeamNusantaraDevs":
		new_members = update.effective_message.new_chat_members
		for new_mem in new_members:
			# CAS Security thread
			t = threading.Thread(target=check_cas, args=(bot, new_mem.id, new_mem, update.effective_message,))
			t.start()