예제 #1
0
def set_verify_welcome(update, context):
	args = context.args
	chat = update.effective_chat  # type: Optional[Chat]
	getcur, extra_verify, cur_value, timeout, timeout_mode, cust_text = sql.welcome_security(chat.id)
	if len(args) >= 1:
		var = args[0].lower()
		if (var == "yes" or var == "ya" or var == "on"):
			check = context.bot.getChatMember(chat.id, context.bot.id)
			if check.status == 'member' or check['can_restrict_members'] == False:
				text = tl(update.effective_message, "Saya tidak bisa membatasi orang di sini! Pastikan saya admin agar bisa membisukan seseorang!")
				send_message(update.effective_message, text, parse_mode="markdown")
				return ""
			sql.set_welcome_security(chat.id, getcur, True, str(cur_value), str(timeout), int(timeout_mode), cust_text)
			send_message(update.effective_message, tl(update.effective_message, "Keamanan untuk member baru di aktifkan! Pengguna baru di wajibkan harus menyelesaikan verifikasi untuk chat"))
		elif (var == "no" or var == "ga" or var == "off"):
			sql.set_welcome_security(chat.id, getcur, False, str(cur_value), str(timeout), int(timeout_mode), cust_text)
			send_message(update.effective_message, tl(update.effective_message, "Di nonaktifkan, pengguna dapat mengklik tombol untuk langsung chat"))
		else:
			send_message(update.effective_message, tl(update.effective_message, "Silakan tulis `on`/`ya`/`off`/`ga`!"), parse_mode=ParseMode.MARKDOWN)
	else:
		getcur, extra_verify, cur_value, timeout, timeout_mode, cust_text = sql.welcome_security(chat.id)
		if cur_value[:1] == "0":
			cur_value = tl(update.effective_message, "Selamanya")
		text = tl(update.effective_message, "Pengaturan saat ini adalah:\nWelcome security: `{}`\nVerify security: `{}`\nMember akan di mute selama: `{}`\nWaktu verifikasi timeout: `{}`\nTombol unmute custom: `{}`").format(getcur, extra_verify, cur_value, make_time(int(timeout)), cust_text)
		send_message(update.effective_message, text, parse_mode="markdown")
예제 #2
0
def security_mute(bot: Bot, update: Update, args: List[str]) -> str:
	spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id, update.effective_message)
	if spam == True:
		return
	chat = update.effective_chat  # type: Optional[Chat]
	message = update.effective_message  # type: Optional[Message]
	getcur, cur_value, cust_text = sql.welcome_security(chat.id)
	if len(args) >= 1:
		var = args[0]
		if var[:1] == "0":
			mutetime = "0"
			sql.set_welcome_security(chat.id, getcur, "0", cust_text)
			text = tl(update.effective_message, "Setiap member baru akan di bisukan selamanya sampai dia menekan tombol selamat datang!")
		else:
			mutetime = extract_time(message, var)
			if mutetime == "":
				return
			sql.set_welcome_security(chat.id, getcur, str(var), cust_text)
			text = tl(update.effective_message, "Setiap member baru akan di bisukan selama {} sampai dia menekan tombol selamat datang!").format(var)
		send_message(update.effective_message, text)
	else:
		if str(cur_value) == "0":
			send_message(update.effective_message, tl(update.effective_message, "Pengaturan saat ini: member baru akan di bisukan selamanya sampai dia menekan tombol selamat datang!"))
		else:
			send_message(update.effective_message, tl(update.effective_message, "Pengaturan saat ini: member baru akan di bisukan selama {} sampai dia menekan tombol selamat datang!").format(cur_value))
예제 #3
0
def security(bot: Bot, update: Update, args: List[str]) -> str:
	spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id, update.effective_message)
	if spam == True:
		return
	chat = update.effective_chat  # type: Optional[Chat]
	getcur, cur_value, cust_text = sql.welcome_security(chat.id)
	if len(args) >= 1:
		var = args[0].lower()
		if (var == "yes" or var == "ya" or var == "on"):
			check = bot.getChatMember(chat.id, bot.id)
			if check.status == 'member' or check['can_restrict_members'] == False:
				text = tl(update.effective_message, "Saya tidak bisa membatasi orang di sini! Pastikan saya admin agar bisa membisukan seseorang!")
				send_message(update.effective_message, text, parse_mode="markdown")
				return ""
			sql.set_welcome_security(chat.id, True, str(cur_value), cust_text)
			send_message(update.effective_message, tl(update.effective_message, "Keamanan untuk member baru di aktifkan!"))
		elif (var == "no" or var == "ga" or var == "off"):
			sql.set_welcome_security(chat.id, False, str(cur_value), cust_text)
			send_message(update.effective_message, tl(update.effective_message, "Di nonaktifkan, saya tidak akan membisukan member masuk lagi"))
		else:
			send_message(update.effective_message, tl(update.effective_message, "Silakan tulis `on`/`ya`/`off`/`ga`!"), parse_mode=ParseMode.MARKDOWN)
	else:
		getcur, cur_value, cust_text = sql.welcome_security(chat.id)
		if cur_value[:1] == "0":
			cur_value = tl(update.effective_message, "Selamanya")
		text = tl(update.effective_message, "Pengaturan saat ini adalah:\nWelcome security: `{}`\nMember akan di mute selama: `{}`\nTombol unmute custom: `{}`").format(getcur, cur_value, cust_text)
		send_message(update.effective_message, text, parse_mode="markdown")
예제 #4
0
def security_text_reset(bot: Bot, update: Update):
	spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id, update.effective_message)
	if spam == True:
		return
	chat = update.effective_chat  # type: Optional[Chat]
	message = update.effective_message  # type: Optional[Message]
	getcur, cur_value, cust_text = sql.welcome_security(chat.id)
	sql.set_welcome_security(chat.id, getcur, cur_value, tl(update.effective_message, "Klik disini untuk mensuarakan"))
	send_message(update.effective_message, tl(update.effective_message, "Tombol custom teks security telah di reset menjadi: `Klik disini untuk mensuarakan`"), parse_mode="markdown")
예제 #5
0
def set_verify_welcome(update, context):
    args = context.args
    chat = update.effective_chat  # type: Optional[Chat]
    getcur, extra_verify, cur_value, timeout, timeout_mode, cust_text = sql.welcome_security(
        chat.id)
    if len(args) >= 1:
        var = args[0].lower()
        if (var == "yes" or var == "ya" or var == "on"):
            check = context.bot.getChatMember(chat.id, context.bot.id)
            if check.status == 'member' or check[
                    'can_restrict_members'] == False:
                text = tl(
                    update.effective_message,
                    "I can't limit people here! Make sure I'm the admin so I can mute someone!"
                )
                send_message(update.effective_message,
                             text,
                             parse_mode="markdown")
                return ""
            sql.set_welcome_security(chat.id, getcur, True, str(cur_value),
                                     str(timeout), int(timeout_mode),
                                     cust_text)
            send_message(
                update.effective_message,
                tl(
                    update.effective_message,
                    "Security for new members is activated! New users are required to complete verification to chat"
                ))
        elif (var == "no" or var == "ga" or var == "off"):
            sql.set_welcome_security(chat.id, getcur, False, str(cur_value),
                                     str(timeout), int(timeout_mode),
                                     cust_text)
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Disabled, users can click a button to chat directly"))
        else:
            send_message(update.effective_message,
                         tl(update.effective_message,
                            "Please write `on`/`ya`/`off`/`ga`!"),
                         parse_mode=ParseMode.MARKDOWN)
    else:
        getcur, extra_verify, cur_value, timeout, timeout_mode, cust_text = sql.welcome_security(
            chat.id)
        if cur_value[:1] == "0":
            cur_value = tl(update.effective_message, "Selamanya")
        text = tl(
            update.effective_message,
            "The current setting is:\nWelcome security: `{}`\nVerify security: `{}`\nMember will be muted for: `{}`\nTimeout verification time: `{}`\nCustom unmute button: `{}`"
        ).format(getcur, extra_verify, cur_value, make_time(int(timeout)),
                 cust_text)
        send_message(update.effective_message, text, parse_mode="markdown")
예제 #6
0
def security_text(bot: Bot, update: Update, args: List[str]) -> str:
	spam = spamfilters(update.effective_message.text, update.effective_message.from_user.id, update.effective_chat.id, update.effective_message)
	if spam == True:
		return
	chat = update.effective_chat  # type: Optional[Chat]
	message = update.effective_message  # type: Optional[Message]
	getcur, cur_value, cust_text = sql.welcome_security(chat.id)
	if len(args) >= 1:
		text = " ".join(args)
		sql.set_welcome_security(chat.id, getcur, cur_value, text)
		text = tl(update.effective_message, "Tombol custom teks telah di ubah menjadi: `{}`").format(text)
		send_message(update.effective_message, text, parse_mode="markdown")
	else:
		send_message(update.effective_message, tl(update.effective_message, "Tombol teks security saat ini adalah: `{}`").format(cust_text), parse_mode="markdown")
예제 #7
0
def timeout_mode(update, context):
	chat = update.effective_chat  # type: Optional[Chat]
	user = update.effective_user  # type: Optional[User]
	msg = update.effective_message  # type: Optional[Message]
	args = context.args

	conn = connected(context.bot, update, chat, user.id, need_admin=True)
	if conn:
		chat = dispatcher.bot.getChat(conn)
		chat_id = conn
		chat_name = dispatcher.bot.getChat(conn).title
	else:
		if update.effective_message.chat.type == "private":
			send_message(update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM"))
			return ""
		chat = update.effective_chat
		chat_id = update.effective_chat.id
		chat_name = update.effective_message.chat.title

	getcur, extra_verify, cur_value, timeout, timeout_mode, cust_text = sql.welcome_security(chat.id)

	if args:
		if args[0].lower() == 'kick' or args[0].lower() == 'tendang' or args[0].lower() == 'leave':
			settypeblacklist = tl(update.effective_message, 'kick')
			sql.set_welcome_security(chat.id, getcur, extra_verify, cur_value, timeout, 1, cust_text)
		elif args[0].lower() == 'ban' or args[0].lower() == 'banned':
			settypeblacklist = tl(update.effective_message, 'banned')
			sql.set_welcome_security(chat.id, getcur, extra_verify, cur_value, timeout, 2, cust_text)
		else:
			send_message(update.effective_message, tl(update.effective_message, "Saya hanya mengerti kick/banned!"))
			return
		if conn:
			text = tl(update.effective_message, "Mode timeout diubah, Pengguna akan di `{}` pada *{}*!").format(settypeblacklist, chat_name)
		else:
			text = tl(update.effective_message, "Mode timeout diubah, Pengguna akan di `{}`!").format(settypeblacklist)
		send_message(update.effective_message, text, parse_mode="markdown")
	else:
		if timeout_mode == 1:
			settypeblacklist = tl(update.effective_message, "kick")
		elif timeout_mode == 2:
			settypeblacklist = tl(update.effective_message, "banned")
		if conn:
			text = tl(update.effective_message, "Mode timeout saat ini disetel ke *{}* pada *{}*.").format(settypeblacklist, chat_name)
		else:
			text = tl(update.effective_message, "Mode timeout saat ini disetel ke *{}*.").format(settypeblacklist)
		send_message(update.effective_message, text, parse_mode=ParseMode.MARKDOWN)
	return
예제 #8
0
def set_welctimeout(update, context):
    args = context.args
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    getcur, extra_verify, cur_value, timeout, timeout_mode, cust_text = sql.welcome_security(
        chat.id)
    if len(args) >= 1:
        var = args[0]
        if var[:1] == "0":
            mutetime = "0"
            sql.set_welcome_security(chat.id, getcur, extra_verify, cur_value,
                                     "0", timeout_mode, cust_text)
            text = tl(update.effective_message,
                      "The verification deadline has been disabled!")
        else:
            mutetime = extract_time_int(message, var)
            if mutetime == "":
                return
            sql.set_welcome_security(chat.id, getcur, extra_verify, cur_value,
                                     str(mutetime), timeout_mode, cust_text)
            text = tl(
                update.effective_message,
                "If new members don't verify during *{}* then he / she will be on *{}*"
            ).format(var, "Kick" if timeout_mode == 1 else "Banned")
        send_message(update.effective_message, text, parse_mode="markdown")
    else:
        if timeout == "0":
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Time limit setting when joining: *{}*").format("Disabled"),
                parse_mode="markdown")
        else:
            send_message(update.effective_message,
                         tl(update.effective_message,
                            "Time limit setting when joining: *{}*").format(
                                make_time(int(timeout))),
                         parse_mode="markdown")
예제 #9
0
def set_welctimeout(update, context):
    args = context.args
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    getcur, extra_verify, cur_value, timeout, timeout_mode, cust_text = sql.welcome_security(
        chat.id)
    if len(args) >= 1:
        var = args[0]
        if var[:1] == "0":
            mutetime = "0"
            sql.set_welcome_security(chat.id, getcur, extra_verify, cur_value,
                                     "0", timeout_mode, cust_text)
            text = tl(update.effective_message,
                      "Batas waktu verifikasi telah di nonaktifkan!")
        else:
            mutetime = extract_time_int(message, var)
            if mutetime == "":
                return
            sql.set_welcome_security(chat.id, getcur, extra_verify, cur_value,
                                     str(mutetime), timeout_mode, cust_text)
            text = tl(
                update.effective_message,
                "Jika member baru tidak memverifikasi selama *{}* maka dia akan di *{}*"
            ).format(var, "Kick" if timeout_mode == 1 else "Banned")
        send_message(update.effective_message, text, parse_mode="markdown")
    else:
        if timeout == "0":
            send_message(update.effective_message,
                         tl(update.effective_message,
                            "Pengaturan batas waktu ketika join: *{}*").format(
                                "Disabled"),
                         parse_mode="markdown")
        else:
            send_message(update.effective_message,
                         tl(update.effective_message,
                            "Pengaturan batas waktu ketika join: *{}*").format(
                                make_time(int(timeout))),
                         parse_mode="markdown")
예제 #10
0
def import_data(update, context):
	msg = update.effective_message  # type: Optional[Message]
	chat = update.effective_chat  # type: Optional[Chat]
	user = update.effective_user  # type: Optional[User]
	# TODO: allow uploading doc with command, not just as reply
	# only work with a doc

	conn = connected(context.bot, update, chat, user.id, need_admin=True)
	if conn:
		chat = dispatcher.bot.getChat(conn)
		chat_id = conn
		chat_name = dispatcher.bot.getChat(conn).title
	else:
		if update.effective_message.chat.type == "private":
			send_message(update.effective_message, tl(update.effective_message, "You can do this command in groups, not PM"))
			return ""
		chat = update.effective_chat
		chat_id = update.effective_chat.id
		chat_name = update.effective_message.chat.title

	if msg.reply_to_message and msg.reply_to_message.document:
		filetype = msg.reply_to_message.document.file_name
		if filetype.split('.')[-1] not in ("backup", "json", "txt"):
			send_message(update.effective_message, tl(update.effective_message, "Invalid backup file!"))
			return
		try:
			file_info = context.bot.get_file(msg.reply_to_message.document.file_id)
		except BadRequest:
			send_message(update.effective_message, tl(update.effective_message, "Try downloading and reuploading the file as yourself before importing - this one seems to be iffy!"))
			return

		with BytesIO() as file:
			file_info.download(out=file)
			file.seek(0)
			data = json.load(file)

		try:
			# If backup is from Emilia
			if data.get('bot_base') == "Emilia":
				imp_antiflood = False
				imp_blacklist = False
				imp_blacklist_count = 0
				imp_blsticker = False
				imp_blsticker_count = 0
				imp_disabled_count = 0
				imp_filters_count = 0
				imp_greet = False
				imp_gdbye = False
				imp_greet_pref = False
				imp_locks = False
				imp_notes = 0
				imp_report = False
				imp_rules = False
				imp_lang = False
				imp_warn = False
				imp_warn_chat = 0
				imp_warn_filter = 0
				NOT_IMPORTED = "This cannot be imported because from other bot."
				NOT_IMPORTED_INT = 0
				# If backup is from this bot, import all files
				if data.get('bot_id') == context.bot.id:
					is_self = True
				else:
					is_self = False
				if data.get('bot_base') == "Emilia":
					is_emilia = True
				else:
					is_emilia = False
				# Import antiflood
				if data.get('antiflood'):
					imp_antiflood = True
					flood_limit = data['antiflood'].get('flood_limit')
					flood_mode = data['antiflood'].get('flood_mode')
					flood_duration = data['antiflood'].get('flood_duration')

					# Add to db
					antifloodsql.set_flood(chat_id, int(flood_limit))
					antifloodsql.set_flood_strength(chat_id, flood_mode, flood_duration)

				# Import blacklist
				if data.get('blacklists'):
					imp_blacklist = True
					blacklist_mode = data['blacklists'].get('blacklist_mode')
					blacklist_duration = data['blacklists'].get('blacklist_duration')
					blacklisted = data['blacklists'].get('blacklists')

					# Add to db
					blacklistsql.set_blacklist_strength(chat_id, blacklist_mode, blacklist_duration)
					if blacklisted:
						for x in blacklisted:
							blacklistsql.add_to_blacklist(chat_id, x.lower())
							imp_blacklist_count += 1

				# Import blacklist sticker
				if data.get('blstickers'):
					imp_blsticker = True
					blsticker_mode = data['blstickers'].get('blsticker_mode')
					blsticker_duration = data['blstickers'].get('blsticker_duration')
					blstickers = data['blstickers'].get('blstickers')

					# Add to db
					blackliststksql.set_blacklist_strength(chat_id, blsticker_mode, blsticker_duration)
					if blstickers:
						for x in blstickers:
							blackliststksql.add_to_stickers(chat_id, x.lower())
							imp_blsticker_count += 1

				# Import disabled
				if data.get('disabled'):
					candisable = disabledsql.get_disableable()
					if data['disabled'].get('disabled'):
						for listdisabled in data['disabled'].get('disabled'):
							if listdisabled in candisable:
								disabledsql.disable_command(chat_id, listdisabled)
								imp_disabled_count += 1

				# Import filters
				if data.get('filters'):
					NOT_IMPORTED += "\n\nFilters:\n"
					for x in data['filters'].get('filters'):
						# If from self, import all
						if is_self:
							is_sticker = False
							is_document = False
							is_image = False
							is_audio = False
							is_voice = False
							is_video = False
							has_markdown = False
							universal = False
							if x['type'] == 1:
								is_sticker = True
							elif x['type'] == 2:
								is_document = True
							elif x['type'] == 3:
								is_image = True
							elif x['type'] == 4:
								is_audio = True
							elif x['type'] == 5:
								is_voice = True
							elif x['type'] == 6:
								is_video = True
							elif x['type'] == 0:
								has_markdown = True
							note_data, buttons = button_markdown_parser(x['reply'], entities=0)
							filtersql.add_filter(chat_id, x['name'], note_data, is_sticker, is_document, is_image, is_audio, is_voice, is_video, buttons)
							imp_filters_count += 1
						elif is_emilia:
							is_sticker = False
							is_document = False
							is_image = False
							is_audio = False
							is_voice = False
							is_video = False
							has_markdown = False
							universal = False
							if x['type'] == 0:
								has_markdown = True
							else:
								NOT_IMPORTED += "- {}\n".format(x['name'])
								NOT_IMPORTED_INT += 1
								continue
							note_data, buttons = button_markdown_parser(x['reply'], entities=0)
							filtersql.add_filter(chat_id, x['name'], note_data, is_sticker, is_document, is_image, is_audio, is_voice, is_video, buttons)
							imp_filters_count += 1
						else:
							if x['has_markdown']:
								note_data, buttons = button_markdown_parser(x['reply'], entities=0)
								filtersql.add_filter(chat_id, x['name'], note_data, False, False, False, False, False, False, buttons)
								imp_filters_count += 1
							else:
								NOT_IMPORTED += "- {}\n".format(x['name'])
								NOT_IMPORTED_INT += 1

				# Import greetings
				if data.get('greetings'):
					if data['greetings'].get('welcome'):
						welcenable = data['greetings']['welcome'].get('enable')
						welcsql.set_welc_preference(str(chat_id), bool(welcenable))

						welctext = data['greetings']['welcome'].get('text')
						welctype = data['greetings']['welcome'].get('type')
						if welctype == 0:
							welctype = Types.TEXT
						elif welctype == 1:
							welctype = Types.BUTTON_TEXT
						elif welctype == 2:
							welctype = Types.STICKER
						elif welctype == 3:
							welctype = Types.DOCUMENT
						elif welctype == 4:
							welctype = Types.PHOTO
						elif welctype == 5:
							welctype = Types.AUDIO
						elif welctype == 6:
							welctype = Types.VOICE
						elif welctype == 7:
							welctype = Types.VIDEO
						elif welctype == 8:
							welctype = Types.VIDEO_NOTE
						else:
							welctype = None
						welccontent = data['greetings']['welcome'].get('content')
						if welctext and welctype:
							note_data, buttons = button_markdown_parser(welctext, entities=0)
							welcsql.set_custom_welcome(chat_id, welccontent, note_data, welctype, buttons)
							imp_greet = True
					if data['greetings'].get('goodbye'):
						gdbyenable = data['greetings']['goodbye'].get('enable')
						welcsql.set_gdbye_preference(str(chat_id), bool(gdbyenable))

						gdbytext = data['greetings']['goodbye'].get('text')
						gdbytype = data['greetings']['goodbye'].get('type')
						if gdbytype == 0:
							gdbytype = Types.TEXT
						elif gdbytype == 1:
							gdbytype = Types.BUTTON_TEXT
						elif gdbytype == 2:
							gdbytype = Types.STICKER
						elif gdbytype == 3:
							gdbytype = Types.DOCUMENT
						elif gdbytype == 4:
							gdbytype = Types.PHOTO
						elif gdbytype == 5:
							gdbytype = Types.AUDIO
						elif gdbytype == 6:
							gdbytype = Types.VOICE
						elif gdbytype == 7:
							gdbytype = Types.VIDEO
						elif gdbytype == 8:
							gdbytype = Types.VIDEO_NOTE
						else:
							gdbytype = None
						gdbycontent = data['greetings']['goodbye'].get('content')
						if welctext and gdbytype:
							note_data, buttons = button_markdown_parser(gdbytext, entities=0)
							welcsql.set_custom_gdbye(chat_id, gdbycontent, note_data, gdbytype, buttons)
							imp_gdbye = True

				# clean service
				cleanserv = data['greetings'].get('clean_service')
				welcsql.set_clean_service(chat_id, bool(cleanserv))

				# security welcome
				if data['greetings'].get('security'):
					secenable = data['greetings']['security'].get('enable')
					secbtn = data['greetings']['security'].get('text')
					sectime = data['greetings']['security'].get('time')
					extra_verify = data['greetings']['security'].get('extra_verify')
					if not extra_verify:
						extra_verify = False
					timeout = data['greetings']['security'].get('timeout')
					if not timeout:
						timeout = "0"
					timeout_mode = data['greetings']['security'].get('timeout_mode')
					if not timeout_mode:
						timeout_mode = 1
					welcsql.set_welcome_security(chat_id, extra_verify, bool(secenable), str(sectime), str(timeout), int(timeout_mode), str(secbtn))
					imp_greet_pref = True

				# Import language
				if data['greetings'].get('language'):
					lang = data['language'].get('language')
					if lang:
						if lang in ('en', 'id'):
							langsql.set_lang(chat_id, lang)
							imp_lang = True

				# Import Locks
				if data.get('locks'):
					if data['locks'].get('lock_warn'):
						locksql.set_lockconf(chat_id, True)
					else:
						locksql.set_lockconf(chat_id, False)
					if data['locks'].get('locks'):
						for x in list(data['locks'].get('locks')):
							if x in LOCK_TYPES:
								is_locked = data['locks']['locks'].get('x')
								locksql.update_lock(chat_id, x, locked=is_locked)
								imp_locks = True

				# Import notes
				if data.get('notes'):
					allnotes = data['notes']
					NOT_IMPORTED += "\n\nNotes:\n"
					for x in allnotes:
						# If from self, import all
						if is_self:
							note_data, buttons = button_markdown_parser(x['note_data'], entities=0)
							note_name = x['note_tag']
							note_file = None
							note_type = x['note_type']
							if x['note_file']:
								note_file = x['note_file']
							if note_type == 0:
								note_type = Types.TEXT
							elif note_type == 1:
								note_type = Types.BUTTON_TEXT
							elif note_type == 2:
								note_type = Types.STICKER
							elif note_type == 3:
								note_type = Types.DOCUMENT
							elif note_type == 4:
								note_type = Types.PHOTO
							elif note_type == 5:
								note_type = Types.AUDIO
							elif note_type == 6:
								note_type = Types.VOICE
							elif note_type == 7:
								note_type = Types.VIDEO
							elif note_type == 8:
								note_type = Types.VIDEO_NOTE
							else:
								note_type = None
							if note_type <= 8:
								notesql.add_note_to_db(chat_id, note_name, note_data, note_type, buttons, note_file)
								imp_notes += 1
						elif is_emilia:
							note_data, buttons = button_markdown_parser(x['note_data'], entities=0)
							note_name = x['note_tag']
							note_file = None
							note_type = x['note_type']
							if x['note_file']:
								note_file = x['note_file']
							if note_type == 0:
								note_type = Types.TEXT
							elif note_type == 1:
								note_type = Types.BUTTON_TEXT
							else:
								NOT_IMPORTED += "- {}\n".format(x['note_tag'])
								NOT_IMPORTED_INT += 1
								continue
							if note_type <= 8:
								notesql.add_note_to_db(chat_id, note_name, note_data, note_type, buttons, note_file)
								imp_notes += 1
						else:
							# If this text
							if x['note_type'] == 0:
								note_data, buttons = button_markdown_parser(x['text'].replace("\\", ""), entities=0)
								note_name = x['name']
								notesql.add_note_to_db(chat_id, note_name, note_data, Types.TEXT, buttons, None)
								imp_notes += 1
							else:
								NOT_IMPORTED += "- {}\n".format(x['name'])
								NOT_IMPORTED_INT += 1

				# Import reports
				if data.get('report'):
					reporting = data['report'].get('report')
					reportsql.set_chat_setting(chat_id, bool(reporting))
					imp_report = True

				# Import rules
				if data.get('rules'):
					contrules = data['rules'].get('rules')
					if contrules:
						rulessql.set_rules(chat_id, contrules)
						imp_rules = True

				# Import warn config
				if data.get('warns'):
					warn_limit = data['warns'].get('warn_limit')
					if warn_limit >= 3:
						warnssql.set_warn_limit(chat_id, int(warn_limit))

					warn_mode = data['warns'].get('warn_mode')
					if warn_mode:
						if warn_mode <= 3:
							warnssql.set_warn_mode(chat_id, int(warn_mode))
							imp_warn = True

					# Import all warn filters
					if data['warns'].get('warn_filters'):
						for x in data['warns'].get('warn_filters'):
							warnssql.add_warn_filter(chat_id, x['name'], x['reason'])
							imp_warn_filter += 1

					# Import all warn from backup chat, reset first for prevent overwarn
					if data['warns'].get('chat_warns'):
						for x in data['warns'].get('chat_warns'):
							# If this invaild
							if x['warns'] > warn_limit:
								break
							warnssql.reset_warns(x['user_id'], chat_id)
							warnssql.import_warns(x['user_id'], chat_id, int(x['warns']), x['reasons'])
							imp_warn_chat += 1

				if conn:
					text = tl(update.effective_message, "Backup fully imported in *{}*. Welcome back! 😀").format(chat_name)
				else:
					text = tl(update.effective_message, "Backup fully imported. Welcome back! 😀").format(chat_name)
				text += tl(update.effective_message, "\n\nRestored:\n")
				if imp_antiflood:
					text += tl(update.effective_message, "- Antiflood Settings\n")
				if imp_blacklist:
					text += tl(update.effective_message, "- Blacklist Settings\n")
				if imp_blacklist_count:
					text += tl(update.effective_message, "- {} blacklists\n").format(imp_blacklist_count)
				if imp_blsticker:
					text += tl(update.effective_message, "- {} blacklisted stickers\n").format(imp_blsticker_count)
				if imp_disabled_count:
					text += tl(update.effective_message, "- {} cmd disabled\n").format(imp_disabled_count)
				if imp_filters_count:
					text += tl(update.effective_message, "- {} filters\n").format(imp_filters_count)
				if imp_greet_pref:
					text += tl(update.effective_message, "- Greeting settings\n")
				if imp_greet:
					text += tl(update.effective_message, "- Greetings message\n")
				if imp_gdbye:
					text += tl(update.effective_message, "- Goodbye message\n")
				if imp_locks:
					text += tl(update.effective_message, "- Locked\n")
				if imp_notes:
					text += tl(update.effective_message, "- {} Notes\n").format(imp_notes)
				if imp_report:
					text += tl(update.effective_message, "- Reporting settings\n")
				if imp_rules:
					text += tl(update.effective_message, "- Group rules\n")
				if imp_lang:
					text += tl(update.effective_message, "- Language settings\n")
				if imp_warn:
					text += tl(update.effective_message, "- Warn settings\n")
				if imp_warn_chat:
					text += tl(update.effective_message, "- {} user warnings\n").format(imp_warn_chat)
				if imp_warn_filter:
					text += tl(update.effective_message, "- {} warning filters\n").format(imp_warn_filter)
				try:
					send_message(update.effective_message, text, parse_mode="markdown")
				except BadRequest:
					send_message(update.effective_message, text, parse_mode="markdown", quote=False)
				if NOT_IMPORTED_INT:
					f = open("{}-notimported.txt".format(chat_id), "w")
					f.write(str(NOT_IMPORTED))
					f.close()
					context.bot.sendDocument(chat_id, document=open('{}-notimported.txt'.format(chat_id), 'rb'), caption=tl(update.effective_message, "*Data yang tidak dapat di import*"), timeout=360, parse_mode=ParseMode.MARKDOWN)
					os.remove("{}-notimported.txt".format(chat_id))
				return
		except Exception as err:
			send_message(update.effective_message, tl(update.effective_message, "An exception occured while restoring your data from Emilia backup!\n\nSorry."), parse_mode="markdown")
			LOGGER.exception("An error when importing from Emilia base!")
			return

		try:
			# If backup is from rose
			# doing manual lol
			if data.get('bot_id') == 609517172:
				imp_antiflood = False
				imp_blacklist = False
				imp_blacklist_count = 0
				imp_disabled_count = 0
				imp_filters_count = 0
				imp_greet = False
				imp_gdbye = False
				imp_greet_pref = False
				imp_notes = 0
				imp_report = False
				imp_rules = False
				imp_lang = False
				imp_warn = False
				NOT_IMPORTED = "This cannot be imported because from other bot."
				NOT_IMPORTED_INT = 0
				if data.get('data'):
					# Import antiflood
					if data['data'].get('antiflood'):
						floodlimit = data['data']['antiflood'].get('flood_limit')
						action = data['data']['antiflood'].get('action')
						actionduration = data['data']['antiflood'].get('action_duration')
						act_dur = make_time(int(actionduration))
						antifloodsql.set_flood(chat_id, int(floodlimit))
						if action == "ban":
							antifloodsql.set_flood_strength(chat_id, 1, str(act_dur))
							imp_antiflood = True
						elif action == "kick":
							antifloodsql.set_flood_strength(chat_id, 2, str(act_dur))
							imp_antiflood = True
						elif action == "mute":
							antifloodsql.set_flood_strength(chat_id, 3, str(act_dur))
							imp_antiflood = True
					# Import blacklist
					if data['data'].get('blacklists'):
						action = data['data']['blacklists'].get('action')
						actionduration = data['data']['blacklists'].get('action_duration')
						act_dur = make_time(int(actionduration))
						strengthdone = False
						if action == "del":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 1, str(act_dur))
							imp_blacklist = True
						elif action == "warn":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 2, str(act_dur))
							imp_blacklist = True
						elif action == "mute":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 3, str(act_dur))
							imp_blacklist = True
						elif action == "kick":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 4, str(act_dur))
							imp_blacklist = True
						elif action == "ban":
							strengthdone = True
							blacklistsql.set_blacklist_strength(chat_id, 5, str(act_dur))
							imp_blacklist = True
						else:
							if not strengthdone:
								action = data['data']['blacklists'].get('should_delete')
								if action:
									blacklistsql.set_blacklist_strength(chat_id, 1, "0")
									imp_blacklist = True
						blacklisted = data['data']['blacklists'].get('filters')
						if blacklisted:
							for x in blacklisted:
								blacklistsql.add_to_blacklist(chat_id, x['name'].lower())
								imp_blacklist_count += 1
					# Import disabled
					if data['data'].get('disabled'):
						if data['data']['disabled'].get('disabled'):
							candisable = disabledsql.get_disableable()
							for listdisabled in data['data']['disabled'].get('disabled'):
								if listdisabled in candisable:
									disabledsql.disable_command(chat_id, listdisabled)
									imp_disabled_count += 1
					# Import filters
					if data['data'].get('filters'):
						NOT_IMPORTED += "\n\nFilters:\n"
						if data['data']['filters'].get('filters'):
							for x in data['data']['filters'].get('filters'):
								if x['type'] == 0:
									note_data, buttons = button_markdown_parser(x['text'].replace("\\", ""), entities=0)
									filtersql.add_filter(chat_id, x['name'], note_data, False, False, False, False, False, False, buttons)
									imp_filters_count += 1
								else:
									NOT_IMPORTED += "- {}\n".format(x['name'])
									NOT_IMPORTED_INT += 1
					# Import greetings
					if data['data'].get('greetings'):
						if data['data']['greetings'].get('welcome'):
							welctext = data['data']['greetings']['welcome'].get('text')
							if welctext:
								note_data, buttons = button_markdown_parser(welctext.replace("\\", ""), entities=0)
								welcsql.set_custom_welcome(chat_id, None, note_data, Types.TEXT, buttons)
								imp_greet = True
						if data['data']['greetings'].get('goodbye'):
							gdbytext = data['data']['greetings']['goodbye'].get('text')
							if welctext:
								note_data, buttons = button_markdown_parser(gdbytext.replace("\\", ""), entities=0)
								welcsql.set_custom_gdbye(chat_id, None, note_data, Types.TEXT, buttons)
								imp_gdbye = True
						# Welcome config
						if data['data']['greetings'].get('should_welcome'):
							welcsql.set_welc_preference(str(chat_id), True)
						else:
							welcsql.set_welc_preference(str(chat_id), False)
						# Goodbye config
						if data['data']['greetings'].get('should_goodbye'):
							welcsql.set_gdbye_preference(str(chat_id), True)
						else:
							welcsql.set_gdbye_preference(str(chat_id), False)
						# clean service
						if data['data']['greetings'].get('should_delete_service'):
							welcsql.set_clean_service(chat_id, True)
						else:
							welcsql.set_clean_service(chat_id, False)
						# custom mute btn
						if data['data']['greetings'].get('mute_text'):
							getcur, cur_value, extra_verify, timeout, timeout_mode, cust_text = welcsql.welcome_security(chat_id)
							welcsql.set_welcome_security(chat_id, getcur, extra_verify, cur_value, timeout, timeout_mode, data['data']['greetings'].get('mute_text'))
						imp_greet_pref = True
						# TODO parsing unix time and import that
					# TODO Locks
					# Import notes
					if data['data'].get('notes'):
						NOT_IMPORTED += "\n\nNotes:\n"
						allnotes = data['data']['notes']['notes']
						for x in allnotes:
							# If this text
							if x['type'] == 0:
								note_data, buttons = button_markdown_parser(x['text'].replace("\\", ""), entities=0)
								note_name = x['name']
								notesql.add_note_to_db(chat_id, note_name, note_data, Types.TEXT, buttons, None)
								imp_notes += 1
							else:
								NOT_IMPORTED += "- {}\n".format(x['name'])
								NOT_IMPORTED_INT += 1
					# Import reports
					if data['data'].get('reports'):
						if data['data']['reports'].get('disable_reports'):
							reporting = False
						else:
							reporting = True
						reportsql.set_chat_setting(chat_id, reporting)
						imp_report = True
					# Import rules
					if data['data'].get('rules'):
						contrules = data['data']['rules'].get('content')
						if contrules:
							rulessql.set_rules(chat_id, contrules.replace("\\", ""))
							imp_rules = True
					# Import current lang
					if data['data'].get('translations'):
						lang = data['data']['translations'].get('lang')
						if lang:
							if lang in ('en', 'id'):
								langsql.set_lang(chat_id, lang)
								imp_lang = True
					# Import warn
					if data['data'].get('warns'):
						action = data['data']['warns'].get('action')
						# actionduration = data['data']['warns'].get('action_duration')
						# act_dur = make_time(int(actionduration))
						if action == "kick":
							warnssql.set_warn_mode(chat_id, 1)
							imp_warn = True
						elif action == "ban":
							warnssql.set_warn_mode(chat_id, 2)
							imp_warn = True
						elif action == "mute":
							warnssql.set_warn_mode(chat_id, 3)
							imp_warn = True
					if conn:
						text = tl(update.effective_message, "Cadangan sepenuhnya dikembalikan pada *{}*. Selamat datang kembali! 😀").format(chat_name)
					else:
						text = tl(update.effective_message, "Cadangan sepenuhnya dikembalikan. Selamat datang kembali! 😀").format(chat_name)
					text += tl(update.effective_message, "\n\nYang saya kembalikan:\n")
					if imp_antiflood:
						text += tl(update.effective_message, "- Pengaturan Antiflood\n")
					if imp_blacklist:
						text += tl(update.effective_message, "- Pengaturan Blacklist\n")
					if imp_blacklist_count:
						text += tl(update.effective_message, "- {} blacklists\n").format(imp_blacklist_count)
					if imp_disabled_count:
						text += tl(update.effective_message, "- {} cmd disabled\n").format(imp_disabled_count)
					if imp_filters_count:
						text += tl(update.effective_message, "- {} filters\n").format(imp_filters_count)
					if imp_greet_pref:
						text += tl(update.effective_message, "- Pengaturan salam\n")
					if imp_greet:
						text += tl(update.effective_message, "- Pesan salam\n")
					if imp_gdbye:
						text += tl(update.effective_message, "- Pesan selamat tinggal\n")
					if imp_notes:
						text += tl(update.effective_message, "- {} catatan\n").format(imp_notes)
					if imp_report:
						text += tl(update.effective_message, "- Pengaturan pelaporan\n")
					if imp_rules:
						text += tl(update.effective_message, "- Pesan peraturan grup\n")
					if imp_lang:
						text += tl(update.effective_message, "- Pengaturan bahasa\n")
					if imp_warn:
						text += tl(update.effective_message, "- Pengaturan peringatan\n")
					try:
						send_message(update.effective_message, text, parse_mode="markdown")
					except BadRequest:
						send_message(update.effective_message, text, parse_mode="markdown", quote=False)
					if NOT_IMPORTED_INT:
						f = open("{}-notimported.txt".format(chat_id), "w")
						f.write(str(NOT_IMPORTED))
						f.close()
						context.bot.sendDocument(chat_id, document=open('{}-notimported.txt'.format(chat_id), 'rb'), caption=tl(update.effective_message, "*Data yang tidak dapat di import*"), timeout=360, parse_mode=ParseMode.MARKDOWN)
						os.remove("{}-notimported.txt".format(chat_id))
					return
		except Exception as err:
			send_message(update.effective_message, tl(update.effective_message, "Telah terjadi kesalahan dalam import backup Rose!\nGabung ke [Grup support](https://t.me/joinchat/Fykz0VTMpqZvlkb8S0JevQ) kami untuk melaporkan dan mengatasi masalah ini!\n\nTerima kasih"), parse_mode="markdown")
			LOGGER.exception("An error when importing from Rose base!")
			return

		# only import one group
		if len(data) > 1 and str(chat_id) not in data:
			send_message(update.effective_message, tl(update.effective_message, "Ada lebih dari satu grup di file ini, dan tidak ada yang memiliki id obrolan yang sama dengan"
						   "grup ini - bagaimana cara memilih apa yang akan diimpor?"))
			return

		# Check if backup is this chat
		try:
			if data.get(str(chat_id)) == None:
				if conn:
					text = tl(update.effective_message, "Backup berasal chat lain, Saya tidak bisa mengembalikan chat lain kedalam chat *{}*").format(chat_name)
				else:
					text = tl(update.effective_message, "Backup berasal chat lain, Saya tidak bisa mengembalikan chat lain kedalam chat ini")
				return send_message(update.effective_message, text, parse_mode="markdown")
		except:
			return send_message(update.effective_message, tl(update.effective_message, "Telah terjadi error dalam pengecekan data, silahkan laporkan kepada pembuat saya "
								  "untuk masalah ini untuk membuat saya lebih baik! Terima kasih! 🙂"))
		# Check if backup is from self
		try:
			if str(bot.id) != str(data[str(chat_id)]['bot']):
				return send_message(update.effective_message, tl(update.effective_message, "Backup berasal dari bot lain, dokumen, foto, video, audio, suara tidak akan "
							   "bekerja, jika file anda tidak ingin hilang, import dari bot yang dicadangkan."
							   "jika masih tidak bekerja, laporkan pada pembuat bot tersebut untuk "
							   "membuat saya lebih baik! Terima kasih! 🙂"))
		except:
			pass
		# Select data source
		if str(chat_id) in data:
			data = data[str(chat_id)]['hashes']
		else:
			data = data[list(data.keys())[0]]['hashes']

		try:
			for mod in DATA_IMPORT:
				mod.__import_data__(str(chat_id), data)
		except Exception:
			send_message(update.effective_message, tl(update.effective_message, "Kesalahan terjadi saat memulihkan data Anda. Prosesnya mungkin tidak lengkap. Jika "
						   "Anda mengalami masalah dengan ini, pesan @AyraHikari dengan file cadangan Anda, jadi "
						   "masalah bisa di-debug. Pemilik saya akan dengan senang hati membantu, dan setiap bug "
						   "dilaporkan membuat saya lebih baik! Terima kasih! 🙂"))
			LOGGER.exception("Impor untuk id chat %s dengan nama %s gagal.", str(chat_id), str(chat.title))
			return

		# TODO: some of that link logic
		# NOTE: consider default permissions stuff?
		if conn:
			text = tl(update.effective_message, "Cadangan sepenuhnya dikembalikan pada *{}*. Selamat datang kembali! 😀").format(chat_name)
		else:
			text = tl(update.effective_message, "Cadangan sepenuhnya dikembalikan. Selamat datang kembali! 😀").format(chat_name)
		send_message(update.effective_message, text, parse_mode="markdown")
예제 #11
0
def timeout_mode(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    msg = update.effective_message  # type: Optional[Message]
    args = context.args

    conn = connected(context.bot, update, chat, user.id, need_admin=True)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        if update.effective_message.chat.type == "private":
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "You can do this command on a group, not on PM"))
            return ""
        chat = update.effective_chat
        chat_id = update.effective_chat.id
        chat_name = update.effective_message.chat.title

    getcur, extra_verify, cur_value, timeout, timeout_mode, cust_text = sql.welcome_security(
        chat.id)

    if args:
        if args[0].lower() == 'kick' or args[0].lower(
        ) == 'tendang' or args[0].lower() == 'leave':
            settypeblacklist = tl(update.effective_message, 'kick')
            sql.set_welcome_security(chat.id, getcur, extra_verify, cur_value,
                                     timeout, 1, cust_text)
        elif args[0].lower() == 'ban' or args[0].lower() == 'banned':
            settypeblacklist = tl(update.effective_message, 'banned')
            sql.set_welcome_security(chat.id, getcur, extra_verify, cur_value,
                                     timeout, 2, cust_text)
        else:
            send_message(
                update.effective_message,
                tl(update.effective_message, "I only understand kick/banned!"))
            return
        if conn:
            text = tl(
                update.effective_message,
                "Timeout mode is changed, User will be on `{}` on *{}*!"
            ).format(settypeblacklist, chat_name)
        else:
            text = tl(update.effective_message,
                      "Timeout mode is changed, User will be on `{}`!").format(
                          settypeblacklist)
        send_message(update.effective_message, text, parse_mode="markdown")
    else:
        if timeout_mode == 1:
            settypeblacklist = tl(update.effective_message, "kick")
        elif timeout_mode == 2:
            settypeblacklist = tl(update.effective_message, "banned")
        if conn:
            text = tl(
                update.effective_message,
                "The timeout mode is currently set to *{}* on *{}*.").format(
                    settypeblacklist, chat_name)
        else:
            text = tl(update.effective_message,
                      "The timeout mode is currently set to *{}*.").format(
                          settypeblacklist)
        send_message(update.effective_message,
                     text,
                     parse_mode=ParseMode.MARKDOWN)
    return