Ejemplo n.º 1
0
def invite(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    if chat.username:
        update.effective_message.reply_text(chat.username)
    elif chat.type == chat.SUPERGROUP or chat.type == chat.CHANNEL:
        bot_member = chat.get_member(bot.id)
        if bot_member.can_invite_users:
            invitelink = bot.exportChatInviteLink(chat.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!"
            ))
Ejemplo n.º 2
0
def save(bot: Bot, update: Update):
    chat_id = update.effective_chat.id
    msg = update.effective_message  # type: Optional[Message]
    raw_text = msg.text
    args = raw_text.split(
        None, 2)  # use python's maxsplit to separate Cmd, note_name, and data

    if len(args) >= 3:
        note_name = args[1]
        note = args[2]

        offset = len(note) - len(
            raw_text)  # set correct offset relative to command + notename
        markdown_note, buttons = button_markdown_parser(
            note, entities=msg.parse_entities(), offset=offset)

        note_data = markdown_note.strip()
        if not note_data:
            msg.reply_text(
                tld(
                    chat_id,
                    "You can't save an empty message! If you added a button, you MUST "
                    "have some text in the message too."))
            return

        sql.add_note_to_db(chat_id,
                           note_name,
                           note_data,
                           is_reply=False,
                           buttons=buttons)

        msg.reply_text(
            tld(
                chat_id,
                "Yas! Added {note_name}.\nGet it with /get {note_name}, or #{note_name}"
            ).format(note_name=note_name))

    else:
        msg.reply_text(tld(chat_id, "Dude, there's no note"))
Ejemplo n.º 3
0
def set_flood(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]

    if len(args) >= 1:
        val = args[0].lower()
        if val == "off" or val == "no" or val == "0":
            sql.set_flood(chat.id, 0)
            message.reply_text(tld(chat.id, "Antiflood has been disabled."))

        elif val.isdigit():
            amount = int(val)
            if amount <= 0:
                sql.set_flood(chat.id, 0)
                message.reply_text(tld(chat.id, "Antiflood has been disabled."))
                return "<b>{}:</b>" \
                       "\n#SETFLOOD" \
                       "\n<b>Admin:</b> {}" \
                       "\nDisabled antiflood.".format(html.escape(chat.title), mention_html(user.id, user.first_name))

            elif amount < 3:
                message.reply_text(tld(chat.id, "Antiflood has to be either 0 (disabled), or a number bigger than 3!"))
                return ""

            else:
                sql.set_flood(chat.id, amount)
                message.reply_text(tld(chat.id, "Antiflood has been updated and set to {}").format(amount))
                return "<b>{}:</b>" \
                       "\n#SETFLOOD" \
                       "\n<b>Admin:</b> {}" \
                       "\nSet antiflood to <code>{}</code>.".format(html.escape(chat.title),
                                                                    mention_html(user.id, user.first_name), amount)

        else:
            message.reply_text(tld(chat.id, "Unrecognised argument - please use a number, 'off', or 'no'."))

    return ""
Ejemplo n.º 4
0
def ban(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]

    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_ban_protected(chat, user_id, member):
        message.reply_text(tld(chat.id, "I really wish I could ban admins..."))
        return ""

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

    log = "<b>{}:</b>" \
          "\n#BANNED" \
          "\n<b>Admin:</b> {}" \
          "\n<b>User:</b> {}".format(html.escape(chat.title), mention_html(user.id, user.first_name),
                                     mention_html(member.user.id, member.user.first_name))
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        update.effective_chat.kick_member(user_id)
        bot.send_sticker(update.effective_chat.id,
                         BAN_STICKER)  # banhammer marie sticker
        message.reply_text(tld(chat.id, "Banned!"))
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text('Banned!', quote=False)
            return log
        else:
            LOGGER.warning(update)
            LOGGER.exception("ERROR banning 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 ban that user."))

    return ""
Ejemplo n.º 5
0
def warns(bot: Bot, update: Update, args: List[str]):
    message = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    user_id = extract_user(message, args) or update.effective_user.id
    result = sql.get_warns(user_id, chat.id)

    if result and result[0] != 0:
        num_warns, reasons = result
        limit, soft_warn = sql.get_warn_setting(chat.id)

        if reasons:
            text = tld(chat.id, "This user has {}/{} warnings, for the following reasons:").format(num_warns, limit)
            for reason in reasons:
                text += "\n - {}".format(reason)

            msgs = split_message(text)
            for msg in msgs:
                update.effective_message.reply_text(msg)
        else:
            update.effective_message.reply_text(
                tld(chat.id, "User has {}/{} warnings, but no reasons for any of them.").format(num_warns, limit))
    else:
        update.effective_message.reply_text(tld(chat.id, "This user hasn't got any warnings!"))
Ejemplo n.º 6
0
def set_warn_limit(bot: Bot, update: Update, args: List[str]) -> str:
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    msg = update.effective_message  # type: Optional[Message]

    if args:
        if args[0].isdigit():
            if int(args[0]) < 3:
                msg.reply_text(tld(chat.id, "The minimum warn limit is 3!"))
            else:
                sql.set_warn_limit(chat.id, int(args[0]))
                msg.reply_text(tld(chat.id, "Updated the warn limit to {}").format(args[0]))
                return "<b>{}:</b>" \
                       "\n#SET_WARN_LIMIT" \
                       "\n<b>Admin:</b> {}" \
                       "\nSet the warn limit to <code>{}</code>".format(html.escape(chat.title),
                                                                        mention_html(user.id, user.first_name), args[0])
        else:
            msg.reply_text(tld(chat.id, "Give me a number as an arg!"))
    else:
        limit, soft_warn = sql.get_warn_setting(chat.id)

        msg.reply_text(tld(chat.id, "The current warn limit is {}").format(limit))
    return ""
Ejemplo n.º 7
0
def warn_user(bot: Bot, update: Update, args: List[str]) -> str:
    message = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    warner = update.effective_user  # type: Optional[User]

    user_id, reason = extract_user_and_text(message, args)

    if user_id:
        if message.reply_to_message and message.reply_to_message.from_user.id == user_id:
            return warn(message.reply_to_message.from_user, chat, reason, message.reply_to_message, warner)
        else:
            return warn(chat.get_member(user_id).user, chat, reason, message, warner)
    else:
        message.reply_text(tld(chat.id, "No user was designated!"))
    return ""
Ejemplo n.º 8
0
def remove_warn_filter(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    msg = update.effective_message  # type: Optional[Message]

    args = msg.text.split(
        None,
        1)  # use python's maxsplit to separate Cmd, keyword, and reply_text

    if len(args) < 2:
        return

    extracted = split_quotes(args[1])

    if len(extracted) < 1:
        return

    to_remove = extracted[0]

    chat_filters = sql.get_chat_warn_triggers(chat.id)

    if not chat_filters:
        msg.reply_text(tld(chat.id, "No warning filters are active here!"))
        return

    for filt in chat_filters:
        if filt == to_remove:
            sql.remove_warn_filter(chat.id, to_remove)
            msg.reply_text(
                tld(chat.id, "Yep, I'll stop warning people for that."))
            raise DispatcherHandlerStop

    msg.reply_text(
        tld(
            chat.id,
            "That's not a current warning filter - run /warnlist for all active warning filters."
        ))
Ejemplo n.º 9
0
def del_message(bot: Bot, update: Update) -> str:
    if update.effective_message.reply_to_message:
        user = update.effective_user  # type: Optional[User]
        chat = update.effective_chat  # type: Optional[Chat]
        if can_delete(chat, bot.id):
            update.effective_message.reply_to_message.delete()
            update.effective_message.delete()
            return "<b>{}:</b>" \
                   "\n#DEL" \
                   "\n<b>Admin:</b> {}" \
                   "\nMessage deleted.".format(html.escape(chat.title),
                                               mention_html(user.id, user.first_name))
    else:
        update.effective_message.reply_text(tld(update.effective_chat.id, "Whadya want to delete?"))

    return ""
Ejemplo n.º 10
0
def unblacklist(bot: Bot, update: Update):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]
    words = msg.text.split(None, 1)
    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!").format(
                        html.escape(to_unblacklist[0])),
                               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.").format(
                    successful),
                           parse_mode=ParseMode.HTML)

        elif not successful:
            msg.reply_text(tld(
                chat.id,
                "None of these triggers 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. {} did not exist, so were not removed."
            ).format(successful,
                     len(to_unblacklist) - successful),
                           parse_mode=ParseMode.HTML)
    else:
        msg.reply_text(
            tld(
                chat.id,
                "Tell me which words you would like to remove from the blacklist."
            ))
Ejemplo n.º 11
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]

    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 = chat.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! Get an admin to do it for me."))
        return ""

    try:
        bot.promoteChatMember(int(chat.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, "Successfully demoted!"))
        return "<b>{}:</b>" \
               "\n#DEMOTED" \
               "\n<b>Admin:</b> {}" \
               "\n<b>User:</b> {}".format(html.escape(chat.title),
                                          mention_html(user.id, user.first_name),
                                          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 ""
Ejemplo n.º 12
0
def get_time(bot: Bot, update: Update, args: List[str]):
    location = " ".join(args)
    if location.lower() == bot.first_name.lower():
        update.effective_message.reply_text(
            tld(update.effective_chat.id, "Its always banhammer time for me!"))
        bot.send_sticker(update.effective_chat.id, BAN_STICKER)
        return

    res = requests.get(GMAPS_LOC, params=dict(address=location))

    if res.status_code == 200:
        loc = json.loads(res.text)
        if loc.get('status') == 'OK':
            lat = loc['results'][0]['geometry']['location']['lat']
            long = loc['results'][0]['geometry']['location']['lng']

            country = None
            city = None

            address_parts = loc['results'][0]['address_components']
            for part in address_parts:
                if 'country' in part['types']:
                    country = part.get('long_name')
                if 'administrative_area_level_1' in part['types'] and not city:
                    city = part.get('long_name')
                if 'locality' in part['types']:
                    city = part.get('long_name')

            if city and country:
                location = "{}, {}".format(city, country)
            elif country:
                location = country

            timenow = int(datetime.utcnow().strftime("%s"))
            res = requests.get(GMAPS_TIME,
                               params=dict(location="{},{}".format(lat, long),
                                           timestamp=timenow))
            if res.status_code == 200:
                offset = json.loads(res.text)['dstOffset']
                timestamp = json.loads(res.text)['rawOffset']
                time_there = datetime.fromtimestamp(timenow + timestamp +
                                                    offset).strftime(
                                                        "%H:%M:%S on %A %d %B")
                update.message.reply_text("It's {} in {}".format(
                    time_there, location))
Ejemplo n.º 13
0
def change_locale(bot, update, args):
    chat = update.effective_chat
    if len(args) > 0:
        locale = args[0].lower()
        if locale in list_locales:
            if locale in ('en', 'de', 'nl', 'id', 'fi'):
                switch_to_locale(chat.id, locale)
                update.message.reply_text(
                    tld(chat.id, 'Switched to {} successfully!').format(
                        list_locales[locale]))
            else:
                update.message.reply_text("{} not supported yet!".format(
                    list_locales[locale]))
        else:
            update.message.reply_text("Is this even a language?")
    else:
        update.message.reply_text(
            "You haven't give me a locale to begin with!")
Ejemplo n.º 14
0
def list_warn_filters(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    all_handlers = sql.get_chat_warn_triggers(chat.id)

    if not all_handlers:
        update.effective_message.reply_text(tld(chat.id, "No warning filters are active here!"))
        return

    filter_list = CURRENT_WARNING_FILTER_STRING
    for keyword in all_handlers:
        entry = " - {}\n".format(html.escape(keyword))
        if len(entry) + len(filter_list) > telegram.MAX_MESSAGE_LENGTH:
            update.effective_message.reply_text(filter_list, parse_mode=ParseMode.HTML)
            filter_list = entry
        else:
            filter_list += entry

    if not filter_list == CURRENT_WARNING_FILTER_STRING:
        update.effective_message.reply_text(filter_list, parse_mode=ParseMode.HTML)
Ejemplo n.º 15
0
def list_handlers(bot: Bot, update: Update):
    chat = update.effective_chat  # type: Optional[Chat]
    all_handlers = sql.get_chat_triggers(chat.id)

    if not all_handlers:
        update.effective_message.reply_text(tld(chat.id, "No filters are active here!"))
        return

    filter_list = BASIC_FILTER_STRING
    for keyword in all_handlers:
        entry = " - {}\n".format(escape_markdown(keyword))
        if len(entry) + len(filter_list) > telegram.MAX_MESSAGE_LENGTH:
            update.effective_message.reply_text(filter_list, parse_mode=telegram.ParseMode.MARKDOWN)
            filter_list = entry
        else:
            filter_list += entry

    if not filter_list == BASIC_FILTER_STRING:
        update.effective_message.reply_text(filter_list, parse_mode=telegram.ParseMode.MARKDOWN)
Ejemplo n.º 16
0
def set_warn_strength(bot: Bot, update: Update, args: List[str]):
    chat = update.effective_chat  # type: Optional[Chat]
    user = update.effective_user  # type: Optional[User]
    msg = update.effective_message  # type: Optional[Message]

    if args:
        if args[0].lower() in ("on", "yes"):
            sql.set_warn_strength(chat.id, False)
            msg.reply_text(
                tld(chat.id, "Too many warns will now result in a ban!"))
            return tld(chat.id, "<b>{}:</b>\n" \
                   "<b>Admin:</b> {}\n" \
                   "Has enabled strong warns. Users will be banned.").format(html.escape(chat.title),
                                                                            mention_html(user.id, user.first_name))

        elif args[0].lower() in ("off", "no"):
            sql.set_warn_strength(chat.id, True)
            msg.reply_text(
                tld(
                    chat.id,
                    "Too many warns will now result in a kick! Users will be able to join again after."
                ))
            return tld(chat.id, "<b>{}:</b>\n" \
                   "<b>Admin:</b> {}\n" \
                   "Has disabled strong warns. Users will only be kicked.").format(html.escape(chat.title),
                                                                                  mention_html(user.id,
                                                                                               user.first_name))

        else:
            msg.reply_text(tld(chat.id, "I only understand on/yes/no/off!"))
    else:
        limit, soft_warn = sql.get_warn_setting(chat.id)
        if soft_warn:
            msg.reply_text(tld(
                chat.id,
                "Warns are currently set to *kick* users when they exceed the limits."
            ),
                           parse_mode=ParseMode.MARKDOWN)
        else:
            msg.reply_text(tld(
                chat.id,
                "Warns are currently set to *ban* users when they exceed the limits."
            ),
                           parse_mode=ParseMode.MARKDOWN)
    return ""
Ejemplo n.º 17
0
def report_setting(bot: Bot, update: Update, args: List[str]):
    chat = update.effective_chat  # type: Optional[Chat]
    msg = update.effective_message  # type: Optional[Message]

    if chat.type == chat.PRIVATE:
        if len(args) >= 1:
            if args[0] in ("yes", "on"):
                sql.set_user_setting(chat.id, True)
                msg.reply_text(
                    tld(
                        chat.id,
                        "Turned on reporting! You'll be notified whenever anyone reports something."
                    ))

            elif args[0] in ("no", "off"):
                sql.set_user_setting(chat.id, False)
                msg.reply_text(
                    tld(chat.id,
                        "Turned off reporting! You wont get any reports."))
        else:
            msg.reply_text(tld(
                chat.id, "Your current report preference is: `{}`").format(
                    sql.user_should_report(chat.id)),
                           parse_mode=ParseMode.MARKDOWN)

    else:
        if len(args) >= 1:
            if args[0] in ("yes", "on"):
                sql.set_chat_setting(chat.id, True)
                msg.reply_text(
                    tld(
                        chat.id,
                        "Turned on reporting! Admins who have turned on reports will be notified when /report "
                        "or @admin are called."))

            elif args[0] in ("no", "off"):
                sql.set_chat_setting(chat.id, False)
                msg.reply_text(
                    tld(
                        chat.id,
                        "Turned off reporting! No admins will be notified on /report or @admin."
                    ))
        else:
            msg.reply_text(tld(chat.id,
                               "This chat's current setting is: `{}`").format(
                                   sql.chat_should_report(chat.id)),
                           parse_mode=ParseMode.MARKDOWN)
Ejemplo n.º 18
0
def blacklist(bot: Bot, update: Update, args: List[str]):
    msg = update.effective_message  # type: Optional[Message]
    chat = update.effective_chat  # type: Optional[Chat]

    all_blacklisted = sql.get_chat_blacklist(chat.id)

    filter_list = BASE_BLACKLIST_STRING

    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 text == BASE_BLACKLIST_STRING:
            msg.reply_text(
                tld(chat.id, "There are no blacklisted messages here!"))
            return
        msg.reply_text(text, parse_mode=ParseMode.HTML)
Ejemplo n.º 19
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]

    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 = chat.get_member(int(user_id))

    if member:
        if is_user_admin(chat, user_id, member=member):
            message.reply_text(tld(chat.id, "Afraid I can't stop an admin from talking!"))

        elif member.can_send_messages is None or member.can_send_messages:
            bot.restrict_chat_member(chat.id, user_id, can_send_messages=False)
            message.reply_text(tld(chat.id, "Muted!"))
            return "<b>{}:</b>" \
                   "\n#MUTE" \
                   "\n<b>Admin:</b> {}" \
                   "\n<b>User:</b> {}".format(html.escape(chat.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!"))
    else:
        message.reply_text(tld(chat.id, "This user isn't in the chat!"))

    return ""
Ejemplo n.º 20
0
def __chat_settings__(chat_id, user_id):
    num_warn_filters = sql.num_warn_chat_filters(chat_id)
    limit, soft_warn = sql.get_warn_setting(chat_id)
    return tld(chat_id, "This chat has `{}` warn filters. It takes `{}` warns " \
           "before the user gets *{}*.").format(num_warn_filters, limit, "kicked" if soft_warn else "banned")
Ejemplo n.º 21
0
def warn(user: User,
         chat: Chat,
         reason: str,
         message: Message,
         warner: User = None) -> str:
    if is_user_admin(chat, user.id):
        message.reply_text(tld(chat.id, "Damn admins, can't even be warned!"))
        return ""

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

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

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

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

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

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

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

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

    try:
        message.reply_text(reply,
                           reply_markup=keyboard,
                           parse_mode=ParseMode.HTML)
    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(reply,
                               reply_markup=keyboard,
                               parse_mode=ParseMode.HTML,
                               quote=False)
        else:
            raise
    return log_reason
Ejemplo n.º 22
0
def unlock(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]
    if is_user_admin(chat, message.from_user.id):
        if len(args) >= 1:
            if args[0] in LOCK_TYPES:
                sql.update_lock(chat.id, args[0], locked=False)
                message.reply_text(
                    tld(chat.id, "Unlocked {} for everyone!").format(args[0]))
                return "<b>{}:</b>" \
                       "\n#UNLOCK" \
                       "\n<b>Admin:</b> {}" \
                       "\nUnlocked <code>{}</code>.".format(html.escape(chat.title),
                                                            mention_html(user.id, user.first_name), args[0])

            elif args[0] in RESTRICTION_TYPES:
                sql.update_restriction(chat.id, args[0], locked=False)
                """
                members = users_sql.get_chat_members(chat.id)
                if args[0] == "messages":
                    unrestr_members(bot, chat.id, members, media=False, other=False, previews=False)

                elif args[0] == "media":
                    unrestr_members(bot, chat.id, members, other=False, previews=False)

                elif args[0] == "other":
                    unrestr_members(bot, chat.id, members, previews=False)

                elif args[0] == "previews":
                    unrestr_members(bot, chat.id, members)

                elif args[0] == "all":
                    unrestr_members(bot, chat.id, members, True, True, True, True)
                """
                message.reply_text(
                    tld(chat.id, "Unlocked {} for everyone!").format(args[0]))
                message.reply_text(
                    tld(
                        chat.id,
                        "NOTE: due to a recent abuse of locking, {} will now only be deleting messages, and not "
                        "restricting users via the tg api. This shouldn't affect all you users though, so dont worry! "
                        "Just means that any restricted users should be manually unrestricted from the chat "
                        "admin pannel.").format(bot.first_name))

                return "<b>{}:</b>" \
                       "\n#UNLOCK" \
                       "\n<b>Admin:</b> {}" \
                       "\nUnlocked <code>{}</code>.".format(html.escape(chat.title),
                                                            mention_html(user.id, user.first_name), args[0])
            else:
                message.reply_text(
                    tld(
                        chat.id,
                        "What are you trying to unlock...? Try /locktypes for the list of lockables"
                    ))

        else:
            bot.sendMessage(chat.id,
                            tld(chat.id, "What are you trying to unlock...?"))

    return ""
Ejemplo n.º 23
0
def __chat_settings__(chat_id, user_id):
    return tld(chat_id, "You are *admin*: `{}`").format(
        dispatcher.bot.get_chat_member(chat_id, user_id).status in (
            tld(chat_id, "administrator", "creator")))
Ejemplo n.º 24
0
def __chat_settings__(chat_id, user_id):
    notes = sql.get_all_chat_notes(chat_id)
    return tld(chat_id,
               "There are `{}` notes in this chat.").format(len(notes))
Ejemplo n.º 25
0
def get(bot, update, notename, show_none=True):
    chat_id = update.effective_chat.id
    note = sql.get_note(chat_id, notename)
    message = update.effective_message  # type: Optional[Message]

    if note:
        # If not is replying to a message, reply to that message (unless its an error)
        if message.reply_to_message:
            reply_text = message.reply_to_message.reply_text
        else:
            reply_text = message.reply_text

        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(
                            tld(
                                chat_id,
                                "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(
                            tld(
                                chat_id,
                                "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:
            keyb = []
            if note.has_buttons:
                buttons = sql.get_buttons(chat_id, notename)
                keyb = build_keyboard(buttons)

            keyboard = InlineKeyboardMarkup(keyb)
            try:
                reply_text(note.value,
                           parse_mode=ParseMode.MARKDOWN,
                           disable_web_page_preview=True,
                           reply_markup=keyboard)
            except BadRequest as excp:
                if excp.message == "Entity_mention_user_invalid":
                    message.reply_text(
                        tld(
                            chat_id,
                            "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(
                        tld(
                            chat_id,
                            "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(
                        tld(
                            chat_id,
                            "This note could not be sent, as it is incorrectly formatted. Ask in "
                            "@MarieSupport 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(tld(chat_id, "This note doesn't exist"))
Ejemplo n.º 26
0
def __chat_settings__(chat_id, user_id):
    return tld(chat_id, "This chat has had it's rules set: `{}`").format(bool(sql.get_rules(chat_id)))
Ejemplo n.º 27
0
def __chat_settings__(chat_id, user_id):
    blacklisted = sql.num_blacklist_chat_filters(chat_id)
    return tld(chat_id, "There are {} blacklisted words.").format(blacklisted)
Ejemplo n.º 28
0
def info(bot: Bot, update: Update, args: List[str]):
    msg = update.effective_message  # type: Optional[Message]
    user_id = extract_user(update.effective_message, args)
    chat = update.effective_chat

    if user_id:
        user = bot.get_chat(user_id)

    elif not msg.reply_to_message and not args:
        user = msg.from_user

    elif not msg.reply_to_message and (
            not args or
        (len(args) >= 1 and not args[0].startswith("@")
         and not args[0].isdigit()
         and not msg.parse_entities([MessageEntity.TEXT_MENTION]))):
        msg.reply_text(tld(chat.id, "I can't extract a user from this."))
        return

    else:
        return

    text = tld(chat.id, "<b>User info</b>:" \
           "\nID: <code>{}</code>" \
           "\nFirst Name: {}").format(user.id, html.escape(user.first_name))

    if user.last_name:
        text += tld(chat.id,
                    "\nLast Name: {}").format(html.escape(user.last_name))

    if user.username:
        text += tld(chat.id,
                    "\nUsername: @{}").format(html.escape(user.username))

    text += tld(chat.id, "\nPermanent user link: {}").format(
        mention_html(user.id, "link"))

    if user.id == OWNER_ID:
        text += tld(
            chat.id,
            "\n\nThis person is my owner - I would never do anything against them!"
        )
    else:
        if user.id in SUDO_USERS:
            text += tld(chat.id, "\nThis person is one of my sudo users! " \
                    "Nearly as powerful as my owner - so watch it.")
        else:
            if user.id in SUPPORT_USERS:
                text += tld(chat.id, "\nThis person is one of my support users! " \
                        "Not quite a sudo user, but can still gban you off the map.")

            if user.id in WHITELIST_USERS:
                text += tld(chat.id, "\nThis person has been whitelisted! " \
                        "That means I'm not allowed to ban/kick them.")

    for mod in USER_INFO:
        mod_info = mod.__user_info__(user.id).strip()
        if mod_info:
            text += "\n\n" + mod_info

    update.effective_message.reply_text(text, parse_mode=ParseMode.HTML)
Ejemplo n.º 29
0
def temp_ban(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]

    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_ban_protected(chat, user_id, member):
        message.reply_text(tld(chat.id, "I really wish I could ban admins..."))
        return ""

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

    split_reason = reason.split(None, 1)
    if not reason:
        message.reply_text(
            tld(chat.id, "You haven't specified a time to ban this user for!"))
        return ""

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

    if any(time_val.endswith(unit) for unit in ('m', 'h', 'd')):
        unit = time_val[-1]
        time_num = time_val[:-1]  # type: str
        if not time_num.isdigit():
            message.reply_text(tld(chat.id, "Invalid time amount specified."))
            return ""

        if unit == 'm':
            bantime = int(time.time() + int(time_num) * 60)
        elif unit == 'h':
            bantime = int(time.time() + int(time_num) * 60 * 60)
        elif unit == 'd':
            bantime = int(time.time() + int(time_num) * 24 * 60 * 60)
        else:
            # how even...?
            return ""

    else:
        message.reply_text(
            tld(chat.id,
                "Invalid time type specified. Expected m,h, or d, got: {}").
            format(time_val[-1]))
        return ""

    log = "<b>{}:</b>" \
          "\n#TEMP BANNED" \
          "\n<b>Admin:</b> {}" \
          "\n<b>User:</b> {}" \
          "\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), time_val)
    if reason:
        log += "\n<b>Reason:</b> {}".format(reason)

    try:
        update.effective_chat.kick_member(user_id, until_date=bantime)
        bot.send_sticker(update.effective_chat.id,
                         BAN_STICKER)  # banhammer marie sticker
        message.reply_text(
            tld(chat.id,
                "Banned! User will be banned for {}.").format(time_val))
        return log

    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text(
                tld(chat.id,
                    "Banned!User will be banned for {}.").format(time_val),
                quote=False)
            return log
        else:
            LOGGER.warning(update)
            LOGGER.exception("ERROR banning 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 ban that user."))

    return ""
Ejemplo n.º 30
0
def rban(bot: Bot, update: Update, args: List[str]):
    message = update.effective_message

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

    user_id, chat_id = 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
    elif not chat_id:
        message.reply_text(
            tld(chat.id, "You don't seem to be referring to a chat."))
        return

    try:
        chat = bot.get_chat(chat_id)
    except BadRequest as excp:
        if excp.message == "Chat not found":
            message.reply_text(
                tld(
                    chat.id,
                    "Chat not found! Make sure you entered a valid chat ID and I'm part of that chat."
                ))
            return
        else:
            raise

    if chat.type == 'private':
        message.reply_text(
            tld(chat.id, "I'm sorry, but that's a private chat!"))
        return

    if not is_bot_admin(chat, bot.id) and not chat.get_member(
            bot.id).can_restrict_members:
        message.reply_text(
            tld(
                chat.id,
                "I can't restrict people there! Make sure I'm admin and can ban users."
            ))
        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_ban_protected(chat, user_id, member):
        message.reply_text(tld(chat.id, "I really wish I could ban admins..."))
        return

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

    try:
        chat.kick_member(user_id)
        message.reply_text(tld(chat.id, "Banned!"))
    except BadRequest as excp:
        if excp.message == "Reply message not found":
            # Do not reply
            message.reply_text('Banned!', quote=False)
        elif excp.message == "User_not_participant":
            message.reply_text("This user is not a participant of the chat!")
        elif excp.message == "Group chat was deactivated":
            message.reply_text("This group chat was deactivated!")
        elif excp.message == "Need to be inviter of a user to kick it from a basic group":
            message.reply_text(excp.message)
        elif excp.message == "Only the creator of a basic group can kick group administrators":
            message.reply_text(excp.message)
        elif excp.message == "Peer_id_invalid":
            message.reply_text(
                "Could not ban user. Perhaps the group has been suspended by Telegram."
            )
        else:
            LOGGER.warning(update)
            LOGGER.exception("ERROR banning user %s in chat %s (%s) due to %s",
                             user_id, chat.title, chat.id, excp.message)
            message.reply_text("Well damn, I can't ban that user.")