Exemplo n.º 1
0
def send_rules(update, chat_id, from_pm=False):
    bot = dispatcher.bot
    user = update.effective_user  # type: Optional[User]
    try:
        chat = bot.get_chat(chat_id)
    except BadRequest as excp:
        if excp.message == "Chat not found" and from_pm:
            bot.send_message(user.id, tl(update.effective_message, "Pintasan aturan untuk obrolan ini belum diatur dengan benar! Mintalah admin untuk "
                                      "perbaiki ini."))
            return
        else:
            raise

    conn = connected(bot, update, chat, user.id, need_admin=False)
    if conn:
        chat = dispatcher.bot.getChat(conn)
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title

    rules, buttons = button_markdown_parser(sql.get_rules(chat_id))
    try:
        text = tl(update.effective_message, "Peraturan untuk *{}* adalah:\n\n{}").format(escape_markdown(chat.title), rules)
    except TypeError:
        send_message(update.effective_message, tl(update.effective_message, "Anda bisa lakukan command ini pada grup, bukan pada PM"))
        return ""

    is_private = sql.get_private_rules(chat_id)

    if from_pm and rules:
        bot.send_message(user.id, text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(build_keyboard_alternate(buttons)))
    elif from_pm:
        if conn:
            bot.send_message(user.id, tl(update.effective_message, "Admin grup belum menetapkan aturan apa pun untuk *{}*. "
                                      "Bukan berarti obrolan ini tanpa hukum...!").format(chat_name), parse_mode="markdown")
        else:
            bot.send_message(user.id, tl(update.effective_message, "Admin grup belum menetapkan aturan apa pun untuk obrolan ini. "
                                      "Bukan berarti obrolan ini tanpa hukum...!"))
    elif rules:
        if (update.effective_message.chat.type == "private" or not is_private) and rules:
            if not is_private:
                send_message(update.effective_message, text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(build_keyboard_alternate(buttons)))
            else:
                bot.send_message(user.id, text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(build_keyboard_alternate(buttons)))
        else:
            send_message(update.effective_message, tl(update.effective_message, "Hubungi saya di PM untuk mendapatkan aturan grup ini"),
                                                reply_markup=InlineKeyboardMarkup(
                                                    [[InlineKeyboardButton(text=tl(update.effective_message, "Peraturan"),
                                                                           url="t.me/{}?start={}".format(bot.username,
                                                                                                         chat_id))]]))
    else:
        if conn:
            send_message(update.effective_message, tl(update.effective_message, "Admin grup belum menetapkan aturan apa pun untuk *{}*. "
                                                "Bukan berarti obrolan ini tanpa hukum...!").format(chat_name), parse_mode="markdown")
        else:
            send_message(update.effective_message, tl(update.effective_message, "Admin grup belum menetapkan aturan apa pun untuk obrolan ini. "
                                                "Bukan berarti obrolan ini tanpa hukum...!"))
Exemplo n.º 2
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")
Exemplo n.º 3
0
def get_welcome_type(msg: Message):
    data_type = None
    content = None
    text = ""

    try:
        if msg.reply_to_message:
            if msg.reply_to_message.text:
                args = msg.reply_to_message.text
            else:
                args = msg.reply_to_message.caption
        else:
            args = msg.text.split(None, 1)  # use python's maxsplit to separate cmd and args
    except AttributeError:
        args = False

    buttons = []
    # determine what the contents of the filter are - text, image, sticker, etc
    if args:
        if msg.reply_to_message:
            if msg.reply_to_message.caption:
                argumen = msg.reply_to_message.caption
            elif msg.reply_to_message.text:
                argumen = msg.reply_to_message.text
        else:
            argumen = args[1]
        offset = len(argumen) - len(msg.text)  # set correct offset relative to command + notename
        text, buttons = button_markdown_parser(argumen, entities=msg.parse_entities(), offset=offset)
        if buttons:
            data_type = Types.BUTTON_TEXT
        else:
            data_type = Types.TEXT

    if msg.reply_to_message and msg.reply_to_message.sticker:
        content = msg.reply_to_message.sticker.file_id
        text = None
        data_type = Types.STICKER

    elif msg.reply_to_message and msg.reply_to_message.document:
        content = msg.reply_to_message.document.file_id
        # text = msg.reply_to_message.caption
        data_type = Types.DOCUMENT

    elif msg.reply_to_message and msg.reply_to_message.photo:
        content = msg.reply_to_message.photo[-1].file_id  # last elem = best quality
        # text = msg.reply_to_message.caption
        data_type = Types.PHOTO

    elif msg.reply_to_message and msg.reply_to_message.audio:
        content = msg.reply_to_message.audio.file_id
        # text = msg.reply_to_message.caption
        data_type = Types.AUDIO

    elif msg.reply_to_message and msg.reply_to_message.voice:
        content = msg.reply_to_message.voice.file_id
        text = None
        data_type = Types.VOICE

    elif msg.reply_to_message and msg.reply_to_message.video:
        content = msg.reply_to_message.video.file_id
        # text = msg.reply_to_message.caption
        data_type = Types.VIDEO

    elif msg.reply_to_message and msg.reply_to_message.video_note:
        content = msg.reply_to_message.video_note.file_id
        text = None
        data_type = Types.VIDEO_NOTE

    return text, data_type, content, buttons
Exemplo n.º 4
0
def get_note_type(msg: Message):
    data_type = None
    content = None
    text = ""
    raw_text = msg.text or msg.caption
    args = raw_text.split(None, 2)  # use python's maxsplit to separate cmd and args
    note_name = args[1]

    buttons = []
    # determine what the contents of the filter are - text, image, sticker, etc
    if len(args) >= 3:
        offset = len(args[2]) - len(raw_text)  # set correct offset relative to command + notename
        text, buttons = button_markdown_parser(args[2], entities=msg.parse_entities() or msg.parse_caption_entities(),
                                               offset=offset)
        if buttons:
            data_type = Types.BUTTON_TEXT
        else:
            data_type = Types.TEXT

    elif msg.reply_to_message:
        entities = msg.reply_to_message.parse_entities()
        msgtext = msg.reply_to_message.text or msg.reply_to_message.caption
        if len(args) >= 2 and msg.reply_to_message.text:  # not caption, text
            text, buttons = button_markdown_parser(msgtext,
                                                   entities=entities)
            if buttons:
                data_type = Types.BUTTON_TEXT
            else:
                data_type = Types.TEXT

        elif msg.reply_to_message.sticker:
            content = msg.reply_to_message.sticker.file_id
            data_type = Types.STICKER

        elif msg.reply_to_message.document:
            content = msg.reply_to_message.document.file_id
            text, buttons = button_markdown_parser(msgtext, entities=entities)
            data_type = Types.DOCUMENT

        elif msg.reply_to_message.photo:
            content = msg.reply_to_message.photo[-1].file_id  # last elem = best quality
            text, buttons = button_markdown_parser(msgtext, entities=entities)
            data_type = Types.PHOTO

        elif msg.reply_to_message.audio:
            content = msg.reply_to_message.audio.file_id
            text, buttons = button_markdown_parser(msgtext, entities=entities)
            data_type = Types.AUDIO

        elif msg.reply_to_message.voice:
            content = msg.reply_to_message.voice.file_id
            text, buttons = button_markdown_parser(msgtext, entities=entities)
            data_type = Types.VOICE

        elif msg.reply_to_message.video:
            content = msg.reply_to_message.video.file_id
            text, buttons = button_markdown_parser(msgtext, entities=entities)
            data_type = Types.VIDEO

        elif msg.reply_to_message.video_note:
            content = msg.reply_to_message.video_note.file_id
            text, buttons = button_markdown_parser(msgtext, entities=entities)
            data_type = Types.VIDEO_NOTE

    return note_name, text, data_type, content, buttons
Exemplo n.º 5
0
def filters(update, context):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    msg = update.effective_message  # type: Optional[Message]
    args = msg.text.split(
        None,
        1)  # use python's maxsplit to separate Cmd, keyword, and reply_text

    conn = connected(context.bot, update, chat, user.id)
    if not conn == False:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        chat_id = update.effective_chat.id
        if chat.type == "private":
            chat_name = tl(update.effective_message, "catatan lokal")
        else:
            chat_name = chat.title

    if not msg.reply_to_message and len(args) < 2:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Anda harus memberi nama untuk filter ini!"))
        return

    if msg.reply_to_message:
        if len(args) < 2:
            send_message(
                update.effective_message,
                tl(update.effective_message,
                   "Anda harus memberi nama untuk filter ini!"))
            return
        else:
            keyword = args[1]
    else:
        extracted = split_quotes(args[1])
        if len(extracted) < 1:
            return
        # set trigger -> lower, so as to avoid adding duplicate filters with different cases
        keyword = extracted[0].lower()

    # Add the filter
    # Note: perhaps handlers can be removed somehow using sql.get_chat_filters
    for handler in dispatcher.handlers.get(HANDLER_GROUP, []):
        if handler.filters == (keyword, chat_id):
            dispatcher.remove_handler(handler, HANDLER_GROUP)

    text, file_type, file_id = get_filter_type(msg)
    if not msg.reply_to_message and len(extracted) >= 2:
        offset = len(extracted[1]) - len(
            msg.text)  # set correct offset relative to command + notename
        text, buttons = button_markdown_parser(extracted[1],
                                               entities=msg.parse_entities(),
                                               offset=offset)
        text = text.strip()
        if not text:
            send_message(
                update.effective_message,
                tl(
                    update.effective_message,
                    "Tidak ada pesan catatan - Anda tidak bisa HANYA menekan tombol, Anda perlu pesan untuk melakukannya!"
                ))
            return

    elif msg.reply_to_message and len(args) >= 2:
        if msg.reply_to_message.text:
            text_to_parsing = msg.reply_to_message.text
        elif msg.reply_to_message.caption:
            text_to_parsing = msg.reply_to_message.caption
        else:
            text_to_parsing = ""
        offset = len(text_to_parsing
                     )  # set correct offset relative to command + notename
        text, buttons = button_markdown_parser(text_to_parsing,
                                               entities=msg.parse_entities(),
                                               offset=offset)
        text = text.strip()

    elif not text and not file_type:
        send_message(
            update.effective_message,
            tl(update.effective_message,
               "Anda harus memberi nama untuk filter ini!"))
        return

    elif msg.reply_to_message:
        if msg.reply_to_message.text:
            text_to_parsing = msg.reply_to_message.text
        elif msg.reply_to_message.caption:
            text_to_parsing = msg.reply_to_message.caption
        else:
            text_to_parsing = ""
        offset = len(text_to_parsing
                     )  # set correct offset relative to command + notename
        text, buttons = button_markdown_parser(text_to_parsing,
                                               entities=msg.parse_entities(),
                                               offset=offset)
        text = text.strip()
        if (msg.reply_to_message.text
                or msg.reply_to_message.caption) and not text:
            send_message(
                update.effective_message,
                tl(
                    update.effective_message,
                    "Tidak ada pesan catatan - Anda tidak bisa HANYA menekan tombol, Anda perlu pesan untuk melakukannya!"
                ))
            return

    else:
        send_message(update.effective_message,
                     tl(update.effective_message, "Invalid filter!"))
        return

    sql.new_add_filter(chat_id, keyword, text, file_type, file_id, buttons)
    # This is an old method
    # sql.add_filter(chat_id, keyword, content, is_sticker, is_document, is_image, is_audio, is_voice, is_video, buttons)

    send_message(update.effective_message,
                 tl(update.effective_message,
                    "Handler '{}' ditambahkan di *{}*!").format(
                        keyword, chat_name),
                 parse_mode=telegram.ParseMode.MARKDOWN)
    raise DispatcherHandlerStop
Exemplo n.º 6
0
def filters(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    msg = update.effective_message  # type: Optional[Message]
    args = msg.text.split(
        None,
        1)  # use python's maxsplit to separate Cmd, keyword, and reply_text

    spam = spamfilters(update.effective_message.text,
                       update.effective_message.from_user.id,
                       update.effective_chat.id)
    if spam == True:
        return update.effective_message.reply_text(
            "Saya kecewa dengan anda, saya tidak akan mendengar kata-kata anda sekarang!"
        )

    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        chat_id = update.effective_chat.id
        if chat.type == "private":
            chat_name = "catatan lokal"
        else:
            chat_name = chat.title

    if len(args) < 2:
        return

    extracted = split_quotes(args[1])
    if len(extracted) < 1:
        return
    # set trigger -> lower, so as to avoid adding duplicate filters with different cases
    keyword = extracted[0].lower()

    is_sticker = False
    is_document = False
    is_image = False
    is_voice = False
    is_audio = False
    is_video = False
    buttons = []

    # determine what the contents of the filter are - text, image, sticker, etc
    if len(extracted) >= 2:
        offset = len(extracted[1]) - len(
            msg.text)  # set correct offset relative to command + notename
        content, buttons = button_markdown_parser(
            extracted[1], entities=msg.parse_entities(), offset=offset)
        content = content.strip()
        if not content:
            msg.reply_text(
                "Tidak ada pesan catatan - Anda tidak bisa HANYA menekan tombol, Anda perlu pesan untuk melakukannya!"
            )
            return

    elif msg.reply_to_message and msg.reply_to_message.sticker:
        content = msg.reply_to_message.sticker.file_id
        is_sticker = True

    elif msg.reply_to_message and msg.reply_to_message.document:
        content = msg.reply_to_message.document.file_id
        is_document = True

    elif msg.reply_to_message and msg.reply_to_message.photo:
        content = msg.reply_to_message.photo[
            -1].file_id  # last elem = best quality
        is_image = True

    elif msg.reply_to_message and msg.reply_to_message.audio:
        content = msg.reply_to_message.audio.file_id
        is_audio = True

    elif msg.reply_to_message and msg.reply_to_message.voice:
        content = msg.reply_to_message.voice.file_id
        is_voice = True

    elif msg.reply_to_message and msg.reply_to_message.video:
        content = msg.reply_to_message.video.file_id
        is_video = True

    else:
        msg.reply_text("Anda tidak menentukan apa yang harus dibalas!")
        return

    # Add the filter
    # Note: perhaps handlers can be removed somehow using sql.get_chat_filters
    for handler in dispatcher.handlers.get(HANDLER_GROUP, []):
        if handler.filters == (keyword, chat_id):
            dispatcher.remove_handler(handler, HANDLER_GROUP)

    sql.add_filter(chat_id, keyword, content, is_sticker, is_document,
                   is_image, is_audio, is_voice, is_video, buttons)

    msg.reply_text("Handler '{}' ditambahkan di *{}*!".format(
        keyword, chat_name),
                   parse_mode=telegram.ParseMode.MARKDOWN)
    raise DispatcherHandlerStop