Example #1
0
def adminlist(bot, update):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if not conn == False:
        chatP = dispatcher.bot.getChat(conn)
    else:
        chatP = update.effective_chat
        if chat.type == "private":
            exit(1)

    administrators = chatP.get_administrators()

    text = tld(chat.id, "Admins in") + " *{}*:".format(
        chatP.title or tld(chat.id, "this chat"))
    for admin in administrators:
        user = admin.user
        status = admin.status
        if status == "creator":
            name = user.first_name + (user.last_name or "") + tld(
                chat.id, " (Creator)")
        else:
            name = user.first_name + (user.last_name or "")
        text += f"\nā€¢ `{name}`"

    update.effective_message.reply_text(text, parse_mode=ParseMode.MARKDOWN)
Example #2
0
def invite(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if not conn == False:
        chatP = dispatcher.bot.getChat(conn)
    else:
        chatP = update.effective_chat
        if chat.type == "private":
            exit(1)

    if chatP.username:
        update.effective_message.reply_text(chatP.username)
    elif chatP.type == chatP.SUPERGROUP or chatP.type == chatP.CHANNEL:
        bot_member = chatP.get_member(bot.id)
        if bot_member.can_invite_users:
            invitelink = chatP.invite_link
            #print(invitelink)
            if not invitelink:
                invitelink = bot.exportChatInviteLink(chatP.id)

            update.effective_message.reply_text(invitelink)
        else:
            update.effective_message.reply_text(
                tld(
                    chat.id,
                    "I don't have access to the invite link, try changing my permissions!"
                ))
    else:
        update.effective_message.reply_text(
            tld(
                chat.id,
                "I can only give you invite links for supergroups and channels, sorry!"
            ))
Example #3
0
def promote(bot: Bot, update: Update, args: List[str]) -> str:
    message = update.effective_message  # type: Optional[Message]
    user = update.effective_user  # type: Optional[User]
    chat = update.effective_chat  # type: Optional[Chat]
    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        chatD = update.effective_chat
        if chat.type == "private":
            exit(1)

    if not chatD.get_member(bot.id).can_promote_members:
        update.effective_message.reply_text(
            "I can't promote/demote people here! "
            "Make sure I'm admin and can appoint new admins.")
        exit(1)

    user_id = extract_user(message, args)
    if not user_id:
        message.reply_text(
            tld(chat.id, "You don't seem to be referring to a user."))
        return ""

    user_member = chatD.get_member(user_id)
    if user_member.status == 'administrator' or user_member.status == 'creator':
        message.reply_text(
            tld(chat.id,
                "How am I meant to promote someone that's already an admin?"))
        return ""

    if user_id == bot.id:
        message.reply_text(
            tld(chat.id,
                "I can't promote myself! Get an admin to do it for me."))
        return ""

    # set same perms as bot - bot can't assign higher perms than itself!
    bot_member = chatD.get_member(bot.id)

    bot.promoteChatMember(
        chatD.id,
        user_id,
        can_change_info=bot_member.can_change_info,
        can_post_messages=bot_member.can_post_messages,
        can_edit_messages=bot_member.can_edit_messages,
        can_delete_messages=bot_member.can_delete_messages,
        #can_invite_users=bot_member.can_invite_users,
        can_restrict_members=bot_member.can_restrict_members,
        can_pin_messages=bot_member.can_pin_messages,
        can_promote_members=bot_member.can_promote_members)

    message.reply_text(tld(chat.id,
                           f"Successfully promoted in *{chatD.title}*!"),
                       parse_mode=ParseMode.MARKDOWN)
    return f"<b>{html.escape(chatD.title)}:</b>" \
            "\n#PROMOTED" \
           f"\n<b>Admin:</b> {mention_html(user.id, user.first_name)}" \
           f"\n<b>User:</b> {mention_html(user_member.user.id, user_member.user.first_name)}"
Example #4
0
def locale_button(bot, update):
    chat = update.effective_chat
    user = update.effective_user  # type: Optional[User]
    query = update.callback_query
    lang_match = re.findall(r"en|ru|ua|es|tr|id", query.data)
    if lang_match:
        if lang_match[0]:
            switch_to_locale(chat.id, lang_match[0])
            query.answer(text="Language changed!")
        else:
            query.answer(text="Error!", show_alert=True)

    try:
        LANGUAGE = prev_locale(chat.id)
        locale = LANGUAGE.locale_name
        curr_lang = list_locales[locale]
    except:
        curr_lang = "English"

    text = "*Select language* \n"
    text += "User language : `{}`".format(curr_lang)

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

    if not conn == False:
        try:
            chatlng = prev_locale(conn).locale_name
            chatlng = list_locales[chatlng]
            text += "\nConnected chat language : `{}`".format(chatlng)
        except:
            chatlng = "English"

    text += "*\n\nSelect new user language:*"

    query.message.reply_text(
        text,
        parse_mode=ParseMode.MARKDOWN,
        reply_markup=InlineKeyboardMarkup([[
            InlineKeyboardButton("English šŸ‡ŗšŸ‡ø", callback_data="set_lang_en")
        ]] + [[
            InlineKeyboardButton("Russian šŸ‡·šŸ‡ŗ", callback_data="set_lang_ru"),
            InlineKeyboardButton("Ukrainian šŸ‡ŗšŸ‡¦", callback_data="set_lang_ua")
        ]] + [[
            InlineKeyboardButton("Spanish šŸ‡ŖšŸ‡ø", callback_data="set_lang_es"),
            InlineKeyboardButton("Turkish šŸ‡¹šŸ‡·", callback_data="set_lang_tr")
        ]] + [[
            InlineKeyboardButton("Indonesian šŸ‡®šŸ‡©", callback_data="set_lang_id")
        ]] + [[InlineKeyboardButton("ā¬…ļø Back", callback_data="bot_start")]]))

    print(lang_match)
    query.message.delete()
    bot.answer_callback_query(query.id)
Example #5
0
def save(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id)
    if conn:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
    else:
        chat_id = update.effective_chat.id
        if chat.type == "private":
            chat_name = "local notes"
        else:
            chat_name = chat.title

    msg = update.effective_message  # type: Optional[Message]

    note_name, text, data_type, content, buttons = get_note_type(msg)

    if data_type is None:
        msg.reply_text("Dude, there's no note!")
        return

    if len(text.strip()) == 0:
        text = note_name

    if not sql.get_note(chat_id, note_name):
        sql.add_note_to_db(chat_id,
                           note_name,
                           text,
                           data_type,
                           buttons=buttons,
                           file=content)
        msg.reply_text(
            "Ok, added `{note_name}` note in *{chat_name}*.\nGet it with `/get {note_name}`, or `#{note_name}`"
            .format(note_name=note_name, chat_name=chat_name),
            parse_mode=ParseMode.MARKDOWN)
    else:
        sql.add_note_to_db(chat_id,
                           note_name,
                           text,
                           data_type,
                           buttons=buttons,
                           file=content)
        msg.reply_text(
            "Ok, Note `{note_name}` in *{chat_name}* have been updated!.\nGet it with `/get {note_name}`, or `#{note_name}`"
            .format(note_name=note_name, chat_name=chat_name),
            parse_mode=ParseMode.MARKDOWN)
Example #6
0
def add_blacklist(bot: Bot, update: Update):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    words = msg.text.split(None, 1)

    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":
            exit(1)
        else:
            chat_name = chat.title

    if len(words) > 1:
        text = words[1]
        to_blacklist = list(
            set(trigger.strip() for trigger in text.split("\n")
                if trigger.strip()))
        for trigger in to_blacklist:
            sql.add_to_blacklist(chat_id, trigger.lower())

        if len(to_blacklist) == 1:
            msg.reply_text(tld(
                chat.id,
                "Added <code>{}</code> to the blacklist in <b>{}</b>!").format(
                    html.escape(to_blacklist[0]), chat_name),
                           parse_mode=ParseMode.HTML)

        else:
            msg.reply_text(tld(
                chat.id,
                "Added <code>{}</code> to the blacklist in <b>{}</b>!").format(
                    len(to_blacklist)),
                           chat_name,
                           parse_mode=ParseMode.HTML)

    else:
        msg.reply_text(
            tld(chat.id,
                "Tell me what words you would like to add to the blacklist."))
Example #7
0
def blacklist(bot: Bot, update: Update, args: List[str]):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]

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

    filter_list = tld(
        chat.id, "<b>Current blacklisted words in {}:</b>\n").format(chat_name)

    all_blacklisted = sql.get_chat_blacklist(chat_id)

    if len(args) > 0 and args[0].lower() == 'copy':
        for trigger in all_blacklisted:
            filter_list += "<code>{}</code>\n".format(html.escape(trigger))
    else:
        for trigger in all_blacklisted:
            filter_list += " ā€¢ <code>{}</code>\n".format(html.escape(trigger))

    split_text = split_message(filter_list)
    for text in split_text:
        if filter_list == tld(
                chat.id, "<b>Current blacklisted words in {}:</b>\n").format(
                    chat_name):  #We need to translate
            msg.reply_text(tld(
                chat.id,
                "There are no blacklisted messages in <b>{}</b>!").format(
                    chat_name),
                           parse_mode=ParseMode.HTML)
            return
        msg.reply_text(text, parse_mode=ParseMode.HTML)
Example #8
0
def list_notes(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if not conn == False:
        chat_id = conn
        chat_name = dispatcher.bot.getChat(conn).title
        msg = "*Notes in {}:*\n"
    else:
        chat_id = update.effective_chat.id
        if chat.type == "private":
            chat_name = ""
            msg = "*Local Notes:*\n"
        else:
            chat_name = chat.title
            msg = "*Notes in {}:*\n"

    note_list = sql.get_all_chat_notes(chat_id)

    for note in note_list:
        note_name = " ā€¢ `#{}`\n".format(note.name)
        if len(msg) + len(note_name) > MAX_MESSAGE_LENGTH:
            update.effective_message.reply_text(msg,
                                                parse_mode=ParseMode.MARKDOWN)
            msg = ""
        msg += note_name

    if not note_list:
        update.effective_message.reply_text(
            "No notes in *{}*!".format(chat_name),
            parse_mode=ParseMode.MARKDOWN)

    elif len(msg) != 0:
        msg += "\nYou can retrieve these notes by using `/get notename`, or `#notename`"
        update.effective_message.reply_text(msg.format(chat_name),
                                            parse_mode=ParseMode.MARKDOWN)
Example #9
0
def clear(bot: Bot, update: Update, args: List[str]):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    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 = "local notes"
        else:
            chat_name = chat.title

    if len(args) >= 1:
        notename = args[0]

        if sql.rm_note(chat_id, notename):
            update.effective_message.reply_text(
                "Note succesfully removed from *{}*.".format(chat_name),
                parse_mode=ParseMode.MARKDOWN)
        else:
            update.effective_message.reply_text(
                "That's not a note in my database!")
Example #10
0
def unblacklist(bot: Bot, update: Update):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    words = msg.text.split(None, 1)

    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":
            exit(1)
        else:
            chat_name = chat.title

    if len(words) > 1:
        text = words[1]
        to_unblacklist = list(
            set(trigger.strip() for trigger in text.split("\n")
                if trigger.strip()))
        successful = 0
        for trigger in to_unblacklist:
            success = sql.rm_from_blacklist(chat_id, trigger.lower())
            if success:
                successful += 1

        if len(to_unblacklist) == 1:
            if successful:
                msg.reply_text(tld(
                    chat.id,
                    "Removed <code>{}</code> from the blacklist in <b>{}</b>!"
                ).format(html.escape(to_unblacklist[0]), chat_name),
                               parse_mode=ParseMode.HTML)
            else:
                msg.reply_text(
                    tld(chat.id, "This isn't a blacklisted trigger...!"))

        elif successful == len(to_unblacklist):
            msg.reply_text(tld(
                chat.id,
                "Removed <code>{}</code> triggers from the blacklist in <b>{}</b>!"
            ).format(successful, chat_name),
                           parse_mode=ParseMode.HTML)

        elif not successful:
            msg.reply_text(tld(
                chat.id,
                "None of these triggers were exist, so they weren't removed.").
                           format(successful,
                                  len(to_unblacklist) - successful),
                           parse_mode=ParseMode.HTML)

        else:
            msg.reply_text(tld(
                chat.id,
                "Removed <code>{}</code> triggers from the blacklist in <b>{}</b>! {} did not exist, "
                "so were not removed.").format(
                    successful, chat_name,
                    len(to_unblacklist) - successful),
                           parse_mode=ParseMode.HTML)
    else:
        msg.reply_text(
            tld(
                chat.id,
                "Tell me what words you would like to remove from the blacklist."
            ))
Example #11
0
def set_blue_text_must_click(bot: Bot, update: Update, args):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]
    spam = spamfilters(update.effective_message.text,
                       update.effective_message.from_user.id,
                       update.effective_chat.id, update.effective_message)
    if spam == True:
        return

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

    if len(args) >= 1:
        val = args[0].lower()
        if val == "off" or val == "no":
            sql.set_cleanbt(chat_id, False)
            if conn:
                text = tld(
                    update.effective_message,
                    "The blue message eraser has been *deactivated* in *{}*."
                ).format(chat_name)
            else:
                text = tld(update.effective_message,
                           "The blue message eraser has been *deactivated*.")
            send_message(update.effective_message, text, parse_mode="markdown")

        elif val == "yes" or val == "ya" or val == "on":
            sql.set_cleanbt(chat_id, True)
            if conn:
                text = tld(
                    update.effective_message,
                    "The blue message eraser has been *activated* in *{}*."
                ).format(chat_name)
            else:
                text = tld(update.effective_message,
                           "The blue message eraser has been *activated*.")
            send_message(update.effective_message, text, parse_mode="markdown")

        else:
            send_message(
                update.effective_message,
                tld(update.effective_message,
                    "Unknown argument - please use 'yes', or 'no'."))
    else:
        send_message(
            update.effective_message,
            tld(
                update.effective_message,
                "The setting for the blue message eraser is currently on {}: *{}*"
            ).format(chat_name,
                     "Enabled" if sql.is_enable(chat_id) else "Disabled"),
            parse_mode="markdown")
Example #12
0
def import_data(bot: Bot, update):
	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(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":
			update.effective_message.reply_text("This command can only be runned on group, 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:
		try:
			file_info = bot.get_file(msg.reply_to_message.document.file_id)
		except BadRequest:
			msg.reply_text("Try downloading and uploading the file yourself again, This one seem broken!")
			return

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

		# only import one group
		if len(data) > 1 and str(chat.id) not in data:
			msg.reply_text("There are more than one group in this file and the chat.id is not same! How am i supposed to import it?")
			return

		# Check if backup is this chat
		try:
			if data.get(str(chat.id)) == None:
				if conn:
					text = "Backup comes from another chat, I can't return another chat to chat *{}*".format(chat_name)
				else:
					text = "Backup comes from another chat, I can't return another chat to this chat"
				return msg.reply_text(text, parse_mode="markdown")
		except:
			return msg.reply_text("There is problem while importing the data! Please ask in @AssassinRobotSupport about why this happened.")
		# Check if backup is from self
		try:
			if str(bot.id) != str(data[str(chat.id)]['bot']):
				return msg.reply_text("Backup from another bot that is not suggested might cause the problem, documents, photos, videos, audios, records might not work as it should be. However, You can still request a feature regarding this in @AssassinRobotSupport !")
		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:
			msg.reply_text("An error occurred while recovering your data. The process failed. If you experience a problem with this, please ask in @assassinAyaGroup . My owner and community will be happy to help. Also, bugs report makes me even better!\nThank you!")

			LOGGER.exception("Imprt for the chat %s with the name %s failed.", str(chat.id), str(chat.title))
			return

		# TODO: some of that link logic
		# NOTE: consider default permissions stuff?
		if conn:


			text = "Backup fully restored on *{}*.".format(chat_name)
		else:
			text = "Backup fully restored"
		msg.reply_text(text, parse_mode="markdown")
Example #13
0
def media(bot: Bot, update: Update, args: List[str]) -> str:
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        if chat.type == "private":
            exit(1)
        else:
            chatD = chat

    user_id = extract_user(message, args)
    if not user_id:
        message.reply_text(
            tld(
                chat.id,
                "You'll need to either give me a username to unrestrict, or reply to someone to be unrestricted."
            ))
        return ""

    member = chatD.get_member(int(user_id))

    if member.status != 'kicked' and member.status != 'left':
        if member.can_send_messages and member.can_send_media_messages \
                and member.can_send_other_messages and member.can_add_web_page_previews:
            message.reply_text(
                tld(
                    chat.id,
                    "This user already has the rights to send anything in {}."
                ).format(chatD.title))
        else:
            bot.restrict_chat_member(chatD.id,
                                     int(user_id),
                                     can_send_messages=True,
                                     can_send_media_messages=True,
                                     can_send_other_messages=True,
                                     can_add_web_page_previews=True)
            keyboard = []
            reply = tld(chat.id, "Yep, {} can send media again in {}!").format(
                mention_html(member.user.id, member.user.first_name),
                chatD.title)
            message.reply_text(reply,
                               reply_markup=keyboard,
                               parse_mode=ParseMode.HTML)
            return "<b>{}:</b>" \
                   "\n#UNRESTRICTED" \
                   "\n<b>ā€¢ Admin:</b> {}" \
                   "\n<b>ā€¢ User:</b> {}" \
                   "\n<b>ā€¢ ID:</b> <code>{}</code>".format(html.escape(chatD.title),
                                                           mention_html(user.id, user.first_name),
                                                           mention_html(member.user.id, member.user.first_name), user_id)
    else:
        message.reply_text(
            tld(
                chat.id,
                "This user isn't even in the chat, unrestricting them won't make them send anything than they "
                "already do!"))

    return ""
Example #14
0
def get(bot, update, notename, show_none=True, no_format=False):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id, need_admin=False)
    if conn:
        chat_id = conn
        send_id = user.id
    else:
        chat_id = update.effective_chat.id
        send_id = chat_id

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

    if note:
        # If we're replying to a message, reply to that message (unless it's an error)
        if message.reply_to_message:
            reply_id = message.reply_to_message.message_id
        else:
            reply_id = message.message_id

        if note.is_reply:
            if MESSAGE_DUMP:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=MESSAGE_DUMP,
                                        message_id=note.value)
                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "This message seems to have been lost - I'll remove it "
                            "from your notes list.")
                        sql.rm_note(chat_id, notename)
                    else:
                        raise
            else:
                try:
                    bot.forward_message(chat_id=chat_id,
                                        from_chat_id=chat_id,
                                        message_id=note.value)

                except BadRequest as excp:
                    if excp.message == "Message to forward not found":
                        message.reply_text(
                            "Looks like the original sender of this note has deleted "
                            "their message - sorry! Get your bot admin to start using a "
                            "message dump to avoid this. I'll remove this note from "
                            "your saved notes.")
                    sql.rm_note(chat_id, notename)

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

            keyboard = InlineKeyboardMarkup(keyb)

            try:
                if note.msgtype in (sql.Types.BUTTON_TEXT, sql.Types.TEXT):
                    try:
                        bot.send_message(send_id,
                                         text,
                                         reply_to_message_id=reply_id,
                                         parse_mode=parseMode,
                                         disable_web_page_preview=True,
                                         reply_markup=keyboard)
                    except BadRequest as excp:
                        if excp.message == "Wrong http url":
                            failtext = "The URL on the button is invalid! Please update this note!"
                            failtext += "\n\n```\n{}```".format(
                                note.value + revert_buttons(buttons))
                            message.reply_text(failtext, parse_mode="markdown")
                        print("Gagal mengirim catatan: " + excp.message)
                        pass
                else:
                    ENUM_FUNC_MAP[note.msgtype](send_id,
                                                note.file,
                                                caption=text,
                                                reply_to_message_id=reply_id,
                                                parse_mode=parseMode,
                                                disable_web_page_preview=True,
                                                reply_markup=keyboard)

            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        "Looks like you tried to mention someone I've never seen before. If you really "
                        "want to mention them, forward one of their messages to me, and I'll be able "
                        "to tag them!")

                elif FILE_MATCHER.match(note.value):
                    message.reply_text(
                        "This note was an incorrectly imported file from another bot - I can't use "
                        "it. If you really need it, you'll have to save it again. In "
                        "the meantime, I'll remove it from your notes list.")
                    sql.rm_note(chat_id, notename)
                else:
                    message.reply_text(
                        "This note could not be sent, as it is incorrectly formatted, Please ask in @assassinAyaGroup if you can't figure out why!"
                    )
                    LOGGER.exception("Could not parse message #%s in chat %s",
                                     notename, str(chat_id))
                    LOGGER.warning("Message was: %s", str(note.value))

        return
    elif show_none:
        message.reply_text("This note doesn't exist")
Example #15
0
def demote(bot: Bot, update: Update, args: List[str]) -> str:
    chat = update.effective_chat  # type: Optional[Chat]
    message = update.effective_message  # type: Optional[Message]
    user = update.effective_user  # type: Optional[User]
    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        chatD = update.effective_chat
        if chat.type == "private":
            exit(1)

    if not chatD.get_member(bot.id).can_promote_members:
        update.effective_message.reply_text(
            "I can't promote/demote people here! "
            "Make sure I'm admin and can appoint new admins.")
        exit(1)

    user_id = extract_user(message, args)
    if not user_id:
        message.reply_text(
            tld(chat.id, "You don't seem to be referring to a user."))
        return ""

    user_member = chatD.get_member(user_id)
    if user_member.status == 'creator':
        message.reply_text(
            tld(chat.id,
                "This person CREATED the chat, how would I demote them?"))
        return ""

    if not user_member.status == 'administrator':
        message.reply_text(tld(chat.id, "Can't demote what wasn't promoted!"))
        return ""

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "I can't demote myself!"))
        return ""

    try:
        bot.promoteChatMember(int(chatD.id),
                              int(user_id),
                              can_change_info=False,
                              can_post_messages=False,
                              can_edit_messages=False,
                              can_delete_messages=False,
                              can_invite_users=False,
                              can_restrict_members=False,
                              can_pin_messages=False,
                              can_promote_members=False)
        message.reply_text(tld(chat.id,
                               f"Successfully demoted in *{chatD.title}*!"),
                           parse_mode=ParseMode.MARKDOWN)
        return f"<b>{html.escape(chatD.title)}:</b>" \
                "\n#DEMOTED" \
               f"\n<b>Admin:</b> {mention_html(user.id, user.first_name)}" \
               f"\n<b>User:</b> {mention_html(user_member.user.id, user_member.user.first_name)}"

    except BadRequest:
        message.reply_text(
            tld(
                chat.id,
                "Could not demote. I might not be admin, or the admin status was appointed by another user, so I can't act upon them!"
            ))
        return ""
Example #16
0
def mute(bot: Bot, update: Update, args: List[str]) -> str:
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        if chat.type == "private":
            exit(1)
        else:
            chatD = chat

    user_id = extract_user(message, args)
    if not user_id:
        message.reply_text(
            tld(
                chat.id,
                "You'll need to either give me a username to mute, or reply to someone to be muted."
            ))
        return ""

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "I'm not muting myself!"))
        return ""

    member = chatD.get_member(int(user_id))

    if member:

        if user_id in SUDO_USERS:
            message.reply_text(
                tld(
                    chat.id,
                    "No! I'm not muting bot sudoers! That would be a pretty dumb idea."
                ))

        elif is_user_admin(chatD, user_id, member=member):
            message.reply_text(
                tld(
                    chat.id,
                    "No! I'm not muting chat administrator! That would be a pretty dumb idea."
                ))

        elif member.can_send_messages is None or member.can_send_messages:
            bot.restrict_chat_member(chatD.id,
                                     user_id,
                                     can_send_messages=False)
            keyboard = []
            reply = tld(chat.id, "{} is muted in {}!").format(
                mention_html(member.user.id, member.user.first_name),
                chatD.title)
            message.reply_text(reply,
                               reply_markup=keyboard,
                               parse_mode=ParseMode.HTML)
            return "<b>{}:</b>" \
                   "\n#MUTE" \
                   "\n<b>Admin:</b> {}" \
                   "\n<b>User:</b> {}".format(html.escape(chatD.title),
                                              mention_html(user.id, user.first_name),
                                              mention_html(member.user.id, member.user.first_name))

        else:
            message.reply_text(
                tld(chat.id,
                    "This user is already muted in {}!").format(chatD.title))
    else:
        message.reply_text(
            tld(chat.id, "This user isn't in the {}!").format(chatD.title))

    return ""
Example #17
0
def nomedia(bot: Bot, update: Update, args: List[str]) -> str:
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        if chat.type == "private":
            exit(1)
        else:
            chatD = chat

    user_id = extract_user(message, args)
    if not user_id:
        message.reply_text(
            tld(
                chat.id,
                "You'll need to either give me a username to restrict, or reply to someone to be restricted."
            ))
        return ""

    if user_id == bot.id:
        message.reply_text(tld(chat.id, "I'm not restricting myself!"))
        return ""

    member = chatD.get_member(int(user_id))

    if member:
        if is_user_admin(chatD, user_id, member=member):
            message.reply_text(tld(chat.id, "Afraid I can't restrict admins!"))

        elif member.can_send_messages is None or member.can_send_messages:
            bot.restrict_chat_member(chatD.id,
                                     user_id,
                                     can_send_messages=True,
                                     can_send_media_messages=False,
                                     can_send_other_messages=False,
                                     can_add_web_page_previews=False)
            keyboard = []
            reply = tld(chat.id,
                        "{} is restricted from sending media in {}!").format(
                            mention_html(member.user.id,
                                         member.user.first_name), chatD.title)
            message.reply_text(reply,
                               reply_markup=keyboard,
                               parse_mode=ParseMode.HTML)
            return "<b>{}:</b>" \
                   "\n#RESTRICTED" \
                   "\n<b>ā€¢ Admin:</b> {}" \
                   "\n<b>ā€¢ User:</b> {}" \
                   "\n<b>ā€¢ ID:</b> <code>{}</code>".format(html.escape(chatD.title),
                                              mention_html(user.id, user.first_name),
                                              mention_html(member.user.id, member.user.first_name), user_id)

        else:
            message.reply_text(
                tld(chat.id, "This user is already restricted in {}!"))
    else:
        message.reply_text(
            tld(chat.id, "This user isn't in the {}!").format(chatD.title))

    return ""
Example #18
0
def control_panel(bot, update):
    chat = update.effective_chat
    user = update.effective_user

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

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

    #Support to run from command handler
    query = update.callback_query
    if query:

        try:
           query.message.delete()
        except BadRequest as ee:
           update.effective_message.reply_text(f"Failed to delete query, {ee}")

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

    else:
        M_match = "Assassin is the best bot" #LMAO, don't uncomment

    if M_match:
        text = "*Control panel* šŸ› "

        keyboard = [[InlineKeyboardButton(text="šŸ‘¤ My settings", callback_data="cntrl_panel_U(1)")]]

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

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

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

        keyboard += [[InlineKeyboardButton(text="ā¬…ļø Back", callback_data="bot_start")]]

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

    elif U_match:

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

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

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

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

            keyboard = R[1]
            keyboard += [[InlineKeyboardButton(text="ā¬…ļø Back", callback_data="cntrl_panel_U(1)")]]
                
            query.message.reply_text(text=text, arse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard))

        elif back_match:
            text = "*User control panel* šŸ› "
            
            query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN,
                    reply_markup=InlineKeyboardMarkup(paginate_modules(user.id, 0, USER_SETTINGS, "cntrl_panel_U")))

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

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

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

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

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

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

            keyboard += [[InlineKeyboardButton(text="Back", callback_data="cntrl_panel_G_back")]]
                
            query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN, reply_markup=InlineKeyboardMarkup(keyboard))

        elif prev_match:
            chat_id = prev_match.group(1)
            curr_page = int(prev_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text(tld(user.id, "send-group-settings").format(chat.title),
                                    reply_markup=InlineKeyboardMarkup(
                                        paginate_modules(curr_page - 1, 0, CHAT_SETTINGS, "cntrl_panel_G",
                                                        chat=chat_id)))

        elif next_match:
            chat_id = next_match.group(1)
            next_page = int(next_match.group(2))
            chat = bot.get_chat(chat_id)
            query.message.reply_text(tld(user.id, "send-group-settings").format(chat.title),
                                    reply_markup=InlineKeyboardMarkup(
                                        paginate_modules(next_page + 1, 0, CHAT_SETTINGS, "cntrl_panel_G",
                                                        chat=chat_id)))

        elif back_match:
            text = "Control Panel :3"
            query.message.reply_text(text=text, parse_mode=ParseMode.MARKDOWN,
                reply_markup=InlineKeyboardMarkup(paginate_modules(user.id, 0, CHAT_SETTINGS, "cntrl_panel_G")))
Example #19
0
def temp_nomedia(bot: Bot, update: Update, args: List[str]) -> str:
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    message = update.effective_message  # type: Optional[Message]

    conn = connected(bot, update, chat, user.id)
    if not conn == False:
        chatD = dispatcher.bot.getChat(conn)
    else:
        if chat.type == "private":
            exit(1)
        else:
            chatD = chat

    user_id, reason = extract_user_and_text(message, args)

    if not user_id:
        message.reply_text(
            tld(chat.id, "You don't seem to be referring to a user."))
        return ""

    try:
        member = chat.get_member(user_id)
    except BadRequest as excp:
        if excp.message == "User not found":
            message.reply_text(tld(chat.id, "I can't seem to find this user"))
            return ""
        else:
            raise

    if is_user_admin(chat, user_id, member):
        message.reply_text(
            tld(chat.id, "I really wish I could restrict admins..."))
        return ""

    if user_id == bot.id:
        message.reply_text(
            tld(chat.id, "I'm not gonna RESTRICT myself, are you crazy?"))
        return ""

    if not reason:
        message.reply_text(
            tld(chat.id,
                "You haven't specified a time to restrict this user for!"))
        return ""

    split_reason = reason.split(None, 1)

    time_val = split_reason[0].lower()
    if len(split_reason) > 1:
        reason = split_reason[1]
    else:
        reason = ""

    mutetime = extract_time(message, time_val)

    if not mutetime:
        return ""

    log = "<b>{}:</b>" \
          "\n#TEMP RESTRICTED" \
          "\n<b>ā€¢ Admin:</b> {}" \
          "\n<b>ā€¢ User:</b> {}" \
          "\n<b>ā€¢ ID:</b> <code>{}</code>" \
          "\n<b>ā€¢ Time:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name),
                                       mention_html(member.user.id, member.user.first_name), user_id, time_val)
    if reason:
        log += "\n<b>ā€¢ Reason:</b> {}".format(reason)

    try:
        if member.can_send_messages is None or member.can_send_messages:
            bot.restrict_chat_member(chat.id,
                                     user_id,
                                     until_date=mutetime,
                                     can_send_messages=True,
                                     can_send_media_messages=False,
                                     can_send_other_messages=False,
                                     can_add_web_page_previews=False)
            message.reply_text(
                tld(chat.id,
                    "Restricted from sending media for {} in {}!").format(
                        time_val, chatD.title))
            return log
        else:
            message.reply_text(
                tld(chat.id, "This user is already restricted in {}.").format(
                    chatD.title))

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(tld(chat.id, "Restricted for {} in {}!").format(
                time_val, chatD.title),
                               quote=False)
            return log
        else:
            LOGGER.warning(update)
            LOGGER.exception("ERROR muting user %s in chat %s (%s) due to %s",
                             user_id, chat.title, chat.id, excp.message)
            message.reply_text(
                tld(chat.id, "Well damn, I can't restrict that user."))

    return ""
Example #20
0
def export_data(bot: Bot, update: Update, chat_data):
	msg = update.effective_message  # type: Optional[Message]
	user = update.effective_user  # type: Optional[User]

	chat_id = update.effective_chat.id
	chat = update.effective_chat
	current_chat_id = update.effective_chat.id

	conn = connected(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":
			update.effective_message.reply_text("This command can only be used on group, not PM")
			return ""
		chat = update.effective_chat
		chat_id = update.effective_chat.id
		chat_name = update.effective_message.chat.title

	jam = time.time()
	new_jam = jam + 10800
	checkchat = get_chat(chat_id, chat_data)
	if checkchat.get('status'):
		if jam <= int(checkchat.get('value')):
			timeformatt = time.strftime("%H:%M:%S %d/%m/%Y", time.localtime(checkchat.get('value')))
			update.effective_message.reply_text("You can only backup once a day!\nYou can backup again in about `{}`".format(timeformatt), parse_mode=ParseMode.MARKDOWN)
			return
		else:
			if user.id != 925710749:
				put_chat(chat_id, new_jam, chat_data)
	else:
		if user.id != 925710749:
			put_chat(chat_id, new_jam, chat_data)

	note_list = sql.get_all_chat_notes(chat_id)
	backup = {}
	notes = {}
	button = ""
	buttonlist = []
	namacat = ""
	isicat = ""
	rules = ""
	count = 0
	countbtn = 0
	# Notes
	for note in note_list:
		count += 1
		getnote = sql.get_note(chat_id, note.name)
		namacat += '{}<###splitter###>'.format(note.name)
		if note.msgtype == 1:
			tombol = sql.get_buttons(chat_id, note.name)
			keyb = []
			for btn in tombol:
				countbtn += 1
				if btn.same_line:
					buttonlist.append(('{}'.format(btn.name), '{}'.format(btn.url), True))
				else:
					buttonlist.append(('{}'.format(btn.name), '{}'.format(btn.url), False))
			isicat += '###button###: {}<###button###>{}<###splitter###>'.format(note.value,str(buttonlist))
			buttonlist.clear()
		elif note.msgtype == 2:
			isicat += '###sticker###:{}<###splitter###>'.format(note.file)
		elif note.msgtype == 3:
			isicat += '###file###:{}<###TYPESPLIT###>{}<###splitter###>'.format(note.file, note.value)
		elif note.msgtype == 4:
			isicat += '###photo###:{}<###TYPESPLIT###>{}<###splitter###>'.format(note.file, note.value)
		elif note.msgtype == 5:
			isicat += '###audio###:{}<###TYPESPLIT###>{}<###splitter###>'.format(note.file, note.value)
		elif note.msgtype == 6:
			isicat += '###voice###:{}<###TYPESPLIT###>{}<###splitter###>'.format(note.file, note.value)
		elif note.msgtype == 7:
			isicat += '###video###:{}<###TYPESPLIT###>{}<###splitter###>'.format(note.file, note.value)
		elif note.msgtype == 8:
			isicat += '###video_note###:{}<###TYPESPLIT###>{}<###splitter###>'.format(note.file, note.value)
		else:
			isicat += '{}<###splitter###>'.format(note.value)
	for x in range(count):
		notes['#{}'.format(namacat.split("<###splitter###>")[x])] = '{}'.format(isicat.split("<###splitter###>")[x])
	# Rules
	rules = rulessql.get_rules(chat_id)
	# Blacklist
	bl = list(blacklistsql.get_chat_blacklist(chat_id))
	# Disabled command
	disabledcmd = list(disabledsql.get_all_disabled(chat_id))
	# Filters (TODO)
	"""
	all_filters = list(filtersql.get_chat_triggers(chat_id))
	export_filters = {}
	for filters in all_filters:
		filt = filtersql.get_filter(chat_id, filters)
		# print(vars(filt))
		if filt.is_sticker:
			tipefilt = "sticker"
		elif filt.is_document:
			tipefilt = "doc"
		elif filt.is_image:
			tipefilt = "img"
		elif filt.is_audio:
			tipefilt = "audio"
		elif filt.is_voice:
			tipefilt = "voice"
		elif filt.is_video:
			tipefilt = "video"
		elif filt.has_buttons:
			tipefilt = "button"
			buttons = filtersql.get_buttons(chat.id, filt.keyword)
			print(vars(buttons))
		elif filt.has_markdown:
			tipefilt = "text"
		if tipefilt == "button":
			content = "{}#=#{}|btn|{}".format(tipefilt, filt.reply, buttons)
		else:
			content = "{}#=#{}".format(tipefilt, filt.reply)
		print(content)
		export_filters[filters] = content
	print(export_filters)
	"""
	# Welcome (TODO)
	# welc = welcsql.get_welc_pref(chat_id)
	# Locked
	locks = locksql.get_locks(chat_id)
	locked = []
	if locks:
		if locks.sticker:
			locked.append('sticker')
		if locks.document:
			locked.append('document')
		if locks.contact:
			locked.append('contact')
		if locks.audio:
			locked.append('audio')
		if locks.game:
			locked.append('game')
		if locks.bots:
			locked.append('bots')
		if locks.gif:
			locked.append('gif')
		if locks.photo:
			locked.append('photo')
		if locks.video:
			locked.append('video')
		if locks.voice:
			locked.append('voice')
		if locks.location:
			locked.append('location')
		if locks.forward:
			locked.append('forward')
		if locks.url:
			locked.append('url')
		restr = locksql.get_restr(chat_id)
		if restr.other:
			locked.append('other')
		if restr.messages:
			locked.append('messages')
		if restr.preview:
			locked.append('preview')
		if restr.media:
			locked.append('media')
	# Warns (TODO)
	# warns = warnssql.get_warns(chat_id)
	# Backing up
	backup[chat_id] = {'bot': bot.id, 'hashes': {'info': {'rules': rules}, 'extra': notes, 'blacklist': bl, 'disabled': disabledcmd, 'locks': locked}}
	baccinfo = json.dumps(backup, indent=4)
	f=open("assassinb{}.backup".format(chat_id), "w")
	f.write(str(baccinfo))
	f.close()
	bot.sendChatAction(current_chat_id, "upload_document")
	tgl = time.strftime("%H:%M:%S - %d/%m/%Y", time.localtime(time.time()))
	try:
		bot.sendMessage(MESSAGE_DUMP, "*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`".format(chat.title, chat_id, tgl), parse_mode=ParseMode.MARKDOWN)
	except BadRequest:
		pass
	bot.sendDocument(current_chat_id, document=open('backup{}.backup'.format(chat_id), 'rb'), caption="*Successfully imported backup:*\nChat: `{}`\nChat ID: `{}`\nOn: `{}`\n\nNote: This `backup` is specially made for notes.".format(chat.title, chat_id, tgl), timeout=360, reply_to_message_id=msg.message_id, parse_mode=ParseMode.MARKDOWN)
	os.remove("backup{}.backup".format(chat_id)) # Cleaning file