Esempio n. 1
0
def bang(bot, update):
    '''
    - kick
    - forward
    - delete
    - send report
    '''
    i18n(update).loads.install(True)

    try:
        update.message.delete()
    except BaseException:
        pass

    # right check
    if sage.is_sage(update.message.from_user.id):
        pass
    else:
        if is_admin(bot, update):
            pass
        else:
            return

    sent = bot.forward_message(config.getint('admin',
                                             'elf'), update.message.chat.id,
                               update.message.reply_to_message.message_id)

    try:
        bot.delete_message(update.message.chat.id,
                           update.message.reply_to_message.message_id)
    except BaseException:
        pass

    try:
        bot.kick_chat_member(update.message.chat_id,
                             update.message.reply_to_message.from_user.id)
    except BadRequest as e:
        if e.message == 'User is an administrator of the chat':
            update.message.reply_text(_(
                f'目標 {update.message.reply_to_message.from_user.mention_html()} 為管理員。'
            ),
                                      parse_mode='html')
        elif e.message == 'Not enough rights to restrict/unrestrict chat member':
            update.message.reply_text(_('指令處理失敗\n原因:<code>權限不足</code>'),
                                      parse_mode='html')
        else:
            update.message.reply_text(
                _(f'指令處理失敗\n原因:<code>{escape(e.message)}</code>'),
                parse_mode='html')

    # report to elf 鍵盤
    text = '#banglog #report\n' + info(bot, update, gettext=True).result()
    keyboard = quickban(bot, update, update.message.message_id)

    bot.send_message(config.getint('admin', 'elf'),
                     text,
                     reply_markup=keyboard,
                     reply_to_message_id=sent.message_id,
                     parse_mode='html')
Esempio n. 2
0
def admins(bot, update):
    mongo = db_tools.use_mongo()
    query_group = mongo.group.find_one({'chat.id': update.message.chat.id})
    if query_group == []:
        update.message.reply_text(_('請先執行設定,請在群組內發送 <code>!hex config</code>'))
        return
    group = db_parse.group()
    group.parse(query_group)
    if group.config.admin:
        admin_ = admins_text(bot, update)
        update.message.reply_html(admin_)
        if Filters.reply(update.message):
            text = '#report\n' + info(bot, update, gettext=True).result()
            sent = bot.forward_message(
                config.getint('admin', 'elf'), update.message.chat.id,
                update.message.reply_to_message.message_id)
            keyboard = quickban(bot, update, sent.message_id)
            bot.send_message(config.getint('admin', 'elf'),
                             text,
                             reply_to_message_id=sent.message_id,
                             reply_markup=keyboard,
                             parse_mode='html')
Esempio n. 3
0
def inherit_excalibur(bot, update, inherit_from: db_parse.user):
    '''
    inherit_from: db_parse.user
    inherit_to: user obj

    轉傳訊息
    '''
    mongo = db_tools.use_mongo()
    query_user = mongo.user.find_one({'chat.id': update.message.from_user.id})
    if query_user is None:
        user_update = {'chat': update.message.from_userto_dict()}
        mongo.user.insert(user_update)
        query_user = mongo.user.find_one(
            {'chat.id': update.message.from_user.id})

    user_ = db_parse.user()
    user_.parse(query_user)

    channel = config.getint('log', 'evidence')
    try:
        evidence = update.message.forward(channel).message_id
    except BaseException:
        evidence = 2

    current = inherit_from.current_raw
    update_user = {'inherit': {
        'id': inherit_from.id,
        'chat': {
            'id': update.message.chat.id
        },
        'evidence': inherit_from.current.evidence
    }}
    current['evidence'] = evidence
    current.update(update_user)
    logger.info(current)

    if user_.current:
        # 新增 current, 舊的移動到 history array
        user_update = {'$push': {'history': user_.current_raw},
                       '$set': {'current': current}}
        mongo.user.find_one_and_update(
            {'chat.id': update.message.from_user.id}, user_update)

    elif user_.current is None:
        # 不是拉 警察這是我第一次拉
        # : 欸 我也是第一次開罰單啊 Q_Q
        # 辣我可以順便要你的電話嘛? OS: 好 好...好可愛
        # : Q_Q 不要投訴我啦
        user_update = {'$set': {'current': current}}
        mongo.user.find_one_and_update(
            {'chat.id': update.message.from_user.id}, user_update)
Esempio n. 4
0
def quickban(bot, update):
    query = update.callback_query
    i18n(update).loads.install(True)
    callback = callabck_parse.callback_parse(query.data)
    user_id, msg_id = callback.qact.split(':')
    tags = callback.qdata

    if sage.michael(query.from_user.id) == False and sage.lucifer(
            query.from_user.id) == False:
        query.answer('權限不夠。')
        return
    if sage.in_shield(int(user_id)):
        text = query.message.text_html + '\n被保護ㄉ狀態。'
        query.edit_message_text(text, parse_mode='html')
        return
    try:
        sent = update.message.forward(config.getint('log', 'evidence'))
    except BaseException:
        sent = 2

    days = druation([tags])
    if days != 0:
        until = int(
            (datetime.now(taiwan_country) + timedelta(days=days)).timestamp())
    else:
        until = 0
    excalibur(bot,
              update,
              int(user_id), [tags],
              query.from_user.id,
              until=until,
              reason=tags)
    text = query.message.text_html + \
        f'\n{"="*23}' + \
        _(f'\n處刑人:{query.from_user.mention_html()}\n') + \
        _(f'標籤:<code>{tags}</code>')
    query.edit_message_text(text, parse_mode='html')
Esempio n. 5
0
def new_chat_members(bot, update):
    i18n(update).loads.install(True)
    mongo = db_tools.use_mongo()
    redis = db_tools.use_redis()

    # bot got invite
    if len(update.message.new_chat_members
           ) == 1 and update.message.new_chat_members[0].id == bot.id:
        # 處理紀錄
        if update.message.chat.type == 'group':
            update.message.reply_text(_('多比只為住在大房子(supergroup)的主人服務')).result()
            bot.leave_chat(update.message.chat.id)
            return
        from_user = update.message.from_user
        count = bot.get_chat_members_count(update.message.chat.id)
        tmp = '<b>Invited</b>\n' \
            f'Group Name: <code>{escape(update.message.chat.title)}</code> \n' \
            f'Group ID: <code>{update.message.chat.id}</code> \n' \
            f'Group Members Counts: {count}\n\n' \
            f'<b>Invited By</b>\n' \
            f'Name: {from_user.mention_html()}\n' \
            f'Username: @{from_user.username}\n' \
            f'UID: <code>{from_user.id}</code>\n' \
            f'lang_code: <code>{from_user.language_code}</code>'
        if str(from_user.id).encode() in redis.lrange('ban_cache', 0, -1):
            tmp = '<b>已退出></b>\n' + tmp
            bot.send_message(config.getint('log', 'invitelog'),
                             tmp,
                             parse_mode='html')
            bot.leave_chat(update.message.chat.id)
            return

        keyboard = [[
            InlineKeyboardButton(
                '報警', callback_data=f'bot leave {update.message.chat.id}'
            ),  # leave group
            InlineKeyboardButton(
                '舔舔', callback_data=f'bot pass {update.message.chat.id}')
        ]]  # keep in group
        keyboard = InlineKeyboardMarkup(keyboard)
        bot.send_message(config.getint('log', 'invitelog'),
                         tmp,
                         parse_mode='html',
                         reply_markup=keyboard)

        # 安裝指南
        guide(bot, update)

        # 記錄低逼
        group = {
            'chat': {
                'title': f'{update.message.chat.title}',
                'id': update.message.chat.id,
                'config': {
                    'sub_ban_list': ['👶'],
                    'ml_nsfw': False,
                    'lang_code': None,
                    'admins': True
                }
            }
        }
        # 重新邀請會導致group資料洗掉ㄛ
        mongo.group.find_one_and_update({'chat.id': update.message.chat_id},
                                        {'$set': group},
                                        upsert=True)

    else:
        '''
        new chat member flow
        - 檢查白名單 & 群組白名單
        - 檢查紀錄
        - 檢查名稱
        - ads, halal name
            - kick, return
        - sent to abyss channel and record
        '''
        for new_member in update.message.new_chat_members:
            border_keeper = gatejieitai(
                bot, update, (update.message.chat.id, new_member.id))
            if border_keeper:
                if border_keeper.current.evidence:
                    evidence = border_keeper.current.evidence
                else:
                    evidence = 2
                text = _('名稱:{fullname}\n'
                         'UID:<code>{user_id}</code>\n'
                         '證據:https://t.me/hexevidence/{evidence}\n'
                         '標籤:<code>{tags}</code>\n').format(
                             fullname=new_member.mention_html(),
                             user_id=new_member.id,
                             evidence=evidence,
                             tags=border_keeper.current.tags_text)
                if border_keeper.current.reason:
                    reason = border_keeper.current.reason
                else:
                    reason = border_keeper.current.tags_text
                if border_keeper.current.until == 0:
                    text += _(banyourwords.forever.format(reason=reason))
                else:
                    text += _(
                        banyourwords.temp.format(
                            reason=reason,
                            date=border_keeper.current.date_text))
                text += _('\n處刑人:<code>{uid}</code>\n'
                          '有任何問題請至 @hexjudge 詢問').format(
                              uid=border_keeper.current.opid)
                try:
                    update.message.delete()
                except BaseException:
                    pass
                try:
                    bot.restrict_chat_member(update.message.chat.id,
                                             new_member.id)
                except BadRequest as e:
                    if e.message == 'Not enough rights to restrict/unrestrict chat member':
                        text = _('⚠️為bot正常運作,請給予admin權限⚠️\n') + \
                            text + \
                            _('\n⚠️為bot正常運作,請給予admin權限⚠️')
                        bot.send_message(update.message.chat.id,
                                         text,
                                         parse_mode='html')
                else:
                    try:
                        sent = bot.send_message(update.message.chat.id,
                                                text,
                                                parse_mode='html')
                    except BaseException:
                        pass
                    time.sleep(15)
                    try:
                        bot.kick_chat_member(update.message.chat.id,
                                             new_member.id)
                    except BaseException:
                        pass
                    bot.delete_message(update.message.chat.id,
                                       sent.result().message_id)

            else:
                checker(bot, update, new_member)

            from_user = update.message.from_user
            tmp = '<b>New</b>\n' \
                f'Group ID:<code>{update.message.chat_id}</code>\n' \
                f'Group Name:{escape(update.message.chat.title)}\n' \
                f'Group Username:{f"@{update.message.chat.username}" if update.message.chat.username else None}\n' \
                f'Name:{new_member.mention_html()}\n' \
                f'Username:@{new_member.username}\n' \
                f'UID:<code>{new_member.id}</code>\n' \
                f'lang_code:<code>{new_member.language_code}</code>\n' \
                f'Profile Pic:{profile_pic(new_member)}\n' \
                '=======================\n'
            keyboard = [[
                InlineKeyboardButton(
                    '炸他全家',
                    callback_data=
                    f'user bypass {update.message.chat_id}:-{new_member.id}'
                ),  # kick new member
                InlineKeyboardButton(
                    '他還只是個孩子啊',
                    callback_data=
                    f'user bypass {update.message.chat.id}:+{new_member.id}')
            ]]  # keep new member
            if from_user.id != new_member.id:
                tmp += '<b>Invite By</b>\n' \
                    f'Name:{from_user.mention_html()}\n' \
                    f'Username:@{from_user.username}\n' \
                    f'UID:<code>{from_user.id}</code>\n' \
                    f'lang_code:<code>{from_user.language_code}</code>\n' \
                    f'Profile Pic:{profile_pic(from_user)}\n' \
                    '=======================\n'
                keyboard = [
                    [
                        InlineKeyboardButton(
                            "掐死被邀人",
                            callback_data=
                            f'user bypass {update.message.chat.id}:+{from_user.id}:-{new_member.id}'
                        ),  # kick from_user group
                        InlineKeyboardButton(
                            "掐死邀請人",
                            callback_data=
                            f'user bypass {update.message.chat.id}:-{from_user.id}:+{new_member.id}'
                        )
                    ],  # kick new_member group
                    [
                        InlineKeyboardButton(
                            "先放過",
                            callback_data=
                            f'user bypass {update.message.chat.id}:+{from_user.id}:+{new_member.id}'
                        ),  # keep both
                        InlineKeyboardButton(
                            "殉情",
                            callback_data=
                            f'user bypass {update.message.chat.id}:-{from_user.id}:-{new_member.id}'
                        )
                    ]
                ]  # kick both]

            # update participate group
            query_participate = mongo.user.find_one({'chat.id': new_member.id})
            part = db_parse.user()
            part.parse(query_participate)
            if part.participate:
                participate = part.participate
                if update.message.chat.id not in participate:
                    participate.append(update.message.chat.id)
            else:
                participate = [update.message.chat_id]

            update_user = {'$set': {'chat': {**new_member.to_dict()}}}
            update_user['$set']['chat'].update({'participate': participate})
            mongo.user.find_one_and_update({'chat.id': new_member.id},
                                           update_user,
                                           upsert=True)

            keyboard = InlineKeyboardMarkup(keyboard)
            bot.send_message(config.getint('log', 'namecheck'),
                             tmp,
                             parse_mode='html',
                             reply_markup=keyboard)
Esempio n. 6
0
def checker(bot, update, new_member):
    # halal 合併 /name
    locales.i18n(update).loads.install(True)
    mongo = db_tools.use_mongo()
    user = db_parse.user()
    group = db_parse.group()
    query_user = mongo.user.find_one({'chat.id': new_member.id})
    query_group = mongo.group.find_one({'chat.id': update.message.chat.id})
    user.parse(query_user)
    group.parse(query_group)
    for check in checker_list:
        do_check = check()
        checker_result, checker_name, checker_match = do_check.detect(
            new_member.full_name.lower())
        if group.config is None:
            # 無心市政
            # 城市不築 敗事有瑜
            return

        tags_result = bool(
            set(group.config.sub_ban_list).intersection(to_emoji(
                do_check.tags)))

        if checker_result and tags_result:
            # halal 先上標籤啦
            if checker_name in ['halal_arabic', 'halal_cyrillic']:
                excalibur(bot,
                          update,
                          new_member.id,
                          tags=['halal'],
                          opid=bot.id,
                          reason='花瓜 呱呱呱')

            try:
                update.message.delete()
            except BaseException:
                pass
            try:
                bot.restrict_chat_member(update.message.chat_id,
                                         new_member.id,
                                         until_date=None,
                                         can_send_messages=None,
                                         can_send_media_messages=None,
                                         can_send_other_messages=None)
            except BadRequest:
                text = _('海克斯希貝兒先知系統偵測到一個<code>心靈指數過高用戶</code>,請給予相應權限作出處理。\n') + \
                    _(f'名稱:{new_member.mention_html()}\n') + \
                    _(f'UID:<code>{new_member.id}</code>\n') + \
                    _(f'偵查:<code>{checker_name}</code>')
                update.message.reply_text(text, parse_mode='html')
                break
            else:
                '''
                Name: 虎虎
                UID: 123123
                因為 {checker name} 導致 心靈指數 指數過高,主宰者 切換至 摧毀分解 模式。
                若有誤判請至 @hexjudge 報告 希貝兒先知系統 存在問題
                案件追蹤 ID:update_id
                '''
                record_msg = f'Name:{new_member.mention_html()}\n' \
                    f'UID:<code>{new_member.id}</code>\n' \
                    f'Checker:{checker_name}\n' \
                    f'Group Name:<code>{update.message.chat.title}</code>\n' \
                    f'Group ID:<code>{update.message.chat.id}</code>\n' \
                    f'Group Username:{"@{update.message.chat.username}" if update.message.chat.username else None}\n' \
                    f'#{checker_name} #tracker_{update.update_id}'
                bot.send_message(config.getint('log', 'abyss'),
                                 record_msg,
                                 parse_mode='html')

                tmp = _(f'名稱:{new_member.mention_html()}\n') + \
                    _(f'UID:<code>{new_member.id}</code>\n') + \
                    _(f'因為 <code>{checker_name}</code> 導致<code>心靈指數</code>過高,<code>主宰者</code>切換至摧毀分解模式。\n') + \
                    _(f'若有誤判請至 @hexjudge 報告海克斯希貝兒先知系統存在問題\n') + \
                    _(f'案件追蹤:#tracker_{update.update_id}')
                warn_msg = update.message.reply_text(tmp, parse_mode='html')
                time.sleep(10)
                bot.kick_chat_member(update.message.chat_id, new_member.id)
                try:
                    bot.delete_message(update.message.chat_id,
                                       warn_msg.result().message_id)
                except BadRequest:
                    pass

            return True
    return False
Esempio n. 7
0
def extend_links(bot, update, inherit, cmd=None):
    # tinyurl, t.cn, bit.ly
    return False
    locales.i18n(update).loads.install(True)
    pattern = r'(http:\/\/www\.|https:\/\/www\.|http:\/\/|https:\/\/)(tinyurl\.com|bit\.ly|t\.cn)(\/[a-z0-9]+)'
    result = re.findall(pattern, unescape(update.message.text_html),
                        re.IGNORECASE)
    if len(result) == 0:
        return False
    extract_result = checker_result()
    extract_result.tags = []
    extract_result.name = ''

    for x in result:
        url = ''.join(x)
        # binance_shortcut.ico
        req = requests.get(url, allow_redirects=False)
        try:
            real_url = req.headers['Location']
        except Exception as e:
            logger.exception(e)

        ## Do All Checker ##
        for checker in check_list:
            result_ = checker(bot, update, real_url)
            if result_.name:
                extract_result.name += result_.name
                extract_result.tags.extend(result_.tags)
            else:
                return
        ## Do All Checker ##
    if sage.in_shield(update.message.from_user.id):
        return
    if is_participate_white(bot, update):
        return
    if is_admin(bot, update):
        return
    if extract_result.tags == []:
        logger.info('return with null tags')
        return
    day = druation(list(dict.fromkeys(extract_result.tags)))
    tags = list(dict.fromkeys(extract_result.tags))

    mongo = db_tools.use_mongo()

    query_group = mongo.group.find_one({'chat.id': update.message.chat.id})
    if query_group:
        group = db_parse.group()
        group.parse(query_group)
    else:
        return True
    if bool(set(group.config.sub_ban_list).intersection(list(to_emoji(tags)))):
        pass
    else:
        return

    evidence = 2
    try:
        fwd = update.message.forward(config.getint('log', 'evidence'))
    except BadRequest as e:
        pass
    else:
        evidence = fwd.message_id
    if day == 0:
        until = 0
    else:
        until = (datetime.now(taiwan_country) +
                 timedelta(days=day)).timestamp()
    excalibur(bot,
              update,
              update.message.from_user.id,
              tags,
              bot.id,
              until=until,
              reason=f'hex auto.{extract_result.name}',
              evidence=evidence)

    right = False
    try:
        update.message.delete()
    except BaseException:
        right = True
    try:
        bot.restrict_chat_member(update.message.chat.id,
                                 update.message.from_user.id)
    except BaseException:
        right = True

    text = _('偵測到 <code>{checker}</code> 垃圾訊息\n').format(
        checker=extract_result.name)
    if right:
        text += _('⚠️權限不足無法操作⚠️\n')
    if extract_result.tags:
        text += _('依照契約內容已吞噬 <code>Sammer</code>\n')
    text += _('名字:{full_name}\n' + 'UID:<code>{user_id}</code>\n' +
              '標籤:<code>{tags}</code>').format(
                  full_name=update.message.from_user.mention_html(),
                  user_id=update.message.from_user.id,
                  tags=', '.join(tags))
    sent = update.message.reply_html(text).result()
    time.sleep(10)
    sent.delete()
    homicide(bot, update, update.message.from_user.id)
Esempio n. 8
0
def xtext(bot, update):
    locales.i18n(update).loads.install(True)
    # Filters photo, documents
    if Filters.text(update.message):
        text = update.message.text_html
    else:
        text = update.message.caption_html

    if sage.in_shield(update.message.from_user.id):
        return
    if is_participate_white(bot, update):
        return
    if is_admin(bot, update):
        return

    cache = redis.lrange('xtext_filter', 0, -1)
    if len(cache) == 0:
        xfilter_refresh()
        cache = redis.lrange('xtext_filter', 0, -1)

    extend = extend_links(bot, update, text).result()
    excute = excute_()

    if not extend:
        for rule in cache:
            checker = re.findall(rule.decode(), text)
            if checker:
                query_xtext = mongo.xtext_filter.find_one(
                    {'rule': rule.decode()})
                rule_result = xtext_rules(query_xtext)
                if rule_result.match <= len(checker):
                    try:
                        evidence = update.message.forward(
                            config.getint('log', 'evidence')).message_id
                    except BaseException:
                        evidence = 2
                    else:
                        send_text = f'Sender: {update.message.from_user.mention_html()}\n' +\
                                    f'ID: {update.message.from_user.id}'
                        bot.send_message(
                            config.getint('log', 'evidence'),
                            send_text,
                            reply_to_message_id=send_text.message_id)
                    excute.parse(rule_result)
                else:
                    return False
    else:
        return

    if excute.name == '':
        return

    day = druation(list(dict.fromkeys(excute.tags)))
    tags = list(list(dict.fromkeys(excute.tags)))
    action = to_emoji(list(dict.fromkeys(excute.action)))
    query_group = mongo.group.find_one({'chat.id': update.message.chat.id})

    if query_group:
        group = db_parse.group()
        group.parse(query_group)
        if bool(
                set(group.config.sub_ban_list).intersection(
                    list(to_emoji(tags)))):
            pass
        else:
            return
    else:
        return

    right = False
    if 'delete' in action or tags:
        try:
            update.message.delete()
        except BadRequest as e:
            if e.message == "Message can't be deleted":
                right = True
    if 'restrict' in action:
        try:
            bot.restrict_chat_member(update.message.chat.id,
                                     update.message.from_user.id)
        except BadRequest as e:
            if e.message == 'Not enough rights to restrict/unrestrict chat member':
                right = True
    if 'alert' in action:
        try:
            pass
        except BadRequest as e:
            text = f'#error #{__name__}\n'
            f'message: {e.message}\n'
            bot.send_message(config.getint('log', 'error'))
    text = _('偵測到 <code>{rule}</code> 規則漢堡罐頭\n'.format(rule=excute.name))
    if right:
        text += _('⚠️權限不足無法操作⚠️\n')
    if excute.tags:
        text += _('依照契約內容已吞噬 Sammer\n')
    text += _('名字:{full_name}\n' + 'UID:<code>{user_id}</code>\n' +
              '標籤:<code>{tags}</code>').format(
                  full_name=update.message.from_user.mention_html(),
                  user_id=update.message.from_user.id,
                  tags=', '.join(tags))
    if day == 0:
        until = 0
    else:
        until = (datetime.now(taiwan_country) +
                 timedelta(days=day)).timestamp()
    excalibur(bot,
              update,
              update.message.from_user.id,
              tags,
              bot.id,
              until=until,
              reason=f'hex auto.{excute.name}',
              evidence=evidence)
    sent = update.message.reply_html(text).result()
    time.sleep(10)
    sent.delete()
    homicide(bot, update, update.message.from_user.id)
Esempio n. 9
0
def hexban_reply(bot, update):
    '''
    !hex ban ads,scam
    !hex ban u=123 t=scam r=ㄏㄏ
    '''
    i18n(update).loads.install(True)
    if sage.is_sage(update.message.from_user.id) == False:
        try:
            update.message.delete()
        except BaseException:
            return
        sent = update.message.reply_text('騷年,你渴望力量ㄇ?').result()
        time.sleep(5)
        sent.delete()
    if sage.elf(update.message.from_user.id):
        update.message.reply_text(_('等級不夠 🌚'))
        return
    args = update.message.text.split()
    if len(args) == 3:
        # !hex ban ads,scam
        tags = args[2].split(',')
        for tag in tags:
            if tag not in emojitags().emoji_dict.keys():
                text = _(f'找不到 <code>{tag}</code> 標籤')
                update.message.reply_html(text)
                return
        if 'spam' not in tags:
            tags.append('spam')

        day = druation(tags)
        now = datetime.now(taiwan_country)
        if day == 0:
            until = 0
        else:
            until = int((now + timedelta(days=day)).timestamp())
        tags_text = ', '.join(tags)
        opid = update.message.from_user.id

        bang = []
        if sage.in_shield(
                update.message.reply_to_message.from_user.id) == False:
            bang = [update.message.reply_to_message.from_user]
        if update.message.reply_to_message.forward_from:
            if sage.in_shield(
                    update.message.reply_to_message.forward_from.id) == False:
                bang.append(update.message.reply_to_message.forward_from)
        if update.message.reply_to_message.forward_from_chat:
            if sage.in_shield(
                    update.message.reply_to_message.forward_from_chat.id) == False:
                bang.append(update.message.reply_to_message.forward_from_chat)
        if bang:
            try:
                sent = bot.forward_message(
                    config.getint(
                        'log',
                        'evidence'),
                    update.message.reply_to_message.chat.id,
                    update.message.reply_to_message.message_id)
            except BaseException:
                sent = None
            if sent:
                evidence = sent.message_id
            else:
                evidence = 2
        else:
            text = ''
            if sage.in_shield(update.message.reply_to_message.from_user.id):
                if sage.is_sage(update.message.reply_to_message.from_user.id):
                    text += _(f'<code>{update.message.reply_to_message.from_user.id}</code> 有精靈保護 🌚')
                else:
                    text += _(
                        f'<code>{update.message.reply_to_message.from_user.id}</code> 白色恐怖快逃R 🌚')
            if update.message.reply_to_message.forward_from:
                if sage.in_shield(
                        update.message.reply_to_message.forward_from.id):
                    if sage.is_sage(
                            update.message.reply_to_message.forward_from.id):
                        text += _(
                            f'<code>{update.message.reply_to_message.forward_from.id}</code> 有精靈保護 🌚')
                    else:
                        text += _(
                            f'<code>{update.message.reply_to_message.from_user.id}</code> 白色恐怖快逃R 🌚')
            if update.message.reply_to_message.forward_from_chat:
                if sage.in_shield(
                        update.message.reply_to_message.forward_from_chat.id):
                    if sage.is_sage(
                            update.message.reply_to_message.forward_from_chat.id):
                        text += _(
                            f'<code>{update.message.reply_to_message.forward_from_chat.id}</code> 有精靈保護 🌚')
                    else:
                        text += _(
                            f'<code>{update.message.reply_to_message.from_user.id}</code> 白色恐怖快逃R 🌚')
            update.message.reply_html(text)
            return

        if Filters.sticker(update.message.reply_to_message):
            if update.message.reply_to_message.sticker.set_name:
                update_sticker = {
                    '$set': {
                        'sticker': {
                            'set_name': update.message.reply_to_message.sticker.set_name,
                            'tags': tags},
                        'opid': update.message.from_user.id,
                        'reason': tags_text,
                        'evidence': evidence}}
                mongo.sticker.find_one_and_update(
                    {'sticker.id': update.message.reply_to_message.sticker.file_id}, update_sticker, upsert=True)
                text = f'ID:<code>{update.message.reply_to_message.sticker.file_id}</code>\n'
                if update.message.reply_to_message.sticker.set_name:
                    # https://t.me/addstickers/nichijou
                    text += f'Set Name:https://t.me/addstickers/{update.message.reply_to_message.sticker.set_name}\n'
                text += _(f'標籤:<code>{tags_text}</code>')
                update.message.reply_html(text)
                sticker_judge.refresh()
        if Filters.photo(update.message.reply_to_message):
            file = bytes(
                update.message.reply_to_message.photo[-1].get_file().download_as_bytearray())
            bio = io.BytesIO(file)
            i = imagehash.hashing(bio)
            hashing = i.phash()

            query_photo = mongo.xmedia.find_one({'photo.hash': hashing})
            if query_photo:
                pass
            else:
                tmp_dict = {'photo':
                            {'hash': hashing,
                             'tags': to_emoji(tags),
                             'indexing': i.indexing()},
                            'evidence': evidence,
                            'opid': update.message.from_user.id,
                            'reason': tags_text}
                mongo.xmedia.insert_one(tmp_dict)
                text = f'hash:<code>{hashing}</code>\n' + \
                    _(f'標籤:<code>{tags_text}</code>\n') + \
                    _(f'標記:<code>{i.indexing()}</code>')
                update.message.reply_html(text)
                redis.lpush('photo_cache', hashing)

        for chat in bang:
            text = excalibur(
                bot,
                update,
                uid=chat.id,
                tags=tags,
                opid=opid,
                until=until,
                reason=tags_text,
                user=chat,
                evidence=evidence)
            update.message.reply_html(text, web_page_preview=False)
            update_user = {'$set': {'chat': chat.to_dict()}}
            mongo.user.find_one_and_update({'chat.id': chat.id}, update_user)
            homicide(bot, update, chat.id)

    # !hex ban t=ads r=臭
    elif len(args) >= 4:
        day = search('ban={:d}d', update.message.text)
        reason = search('r={:S}', update.message.text)
        tags = search('t={:S}', update.message.text)
        uid = search('u={:d}', update.message.text)
        now = datetime.now(taiwan_country)

        if tags is None:
            text = f'缺少標籤參數。'
            update.message.reply_html(text)
            return
        else:
            tags = tags[0].split(',')
            if 'spam' not in tags:
                tags.append('spam')
        for tag in tags:
            if tag not in emojitags().emoji_dict.keys():
                text = f'找不到 <code>{tag}</code> 標籤'
                update.message.reply_html(text)
                return

        if day:
            if day[0] == 0:
                until = 0
            else:
                until = int((now + timedelta(days=day[0])).timestamp())
        else:
            day_ = druation(tags)
            if day_ == 0:
                until = 0
            else:
                until = int((now + timedelta(days=day_)).timestamp())
        tags_text = ', '.join(tags)

        opid = update.message.from_user.id
        if reason:
            reason = reason[0]
        else:
            reason = tags_text

        if uid:
            uid = uid[0]
            try:
                sent = bot.forward_message(
                    config.getint(
                        'log',
                        'evidence'),
                    update.message.reply_to_message.chat.id,
                    update.message.reply_to_message.message_id)
            except BaseException:
                sent = None
            if sent:
                evidence = sent.message_id
            else:
                evidence = 2

            text = excalibur(
                bot,
                update,
                uid=uid,
                tags=tags,
                opid=opid,
                until=until,
                reason=reason,
                evidence=evidence)

            update.message.reply_html(text)
            return

        if sage.in_shield(update.message.reply_to_message.from_user.id):
            bang = []
        else:
            bang = [update.message.reply_to_message.from_user]
        if update.message.reply_to_message.forward_from:
            if sage.in_shield(
                    update.message.reply_to_message.forward_from.id) == False:
                bang.append(update.message.reply_to_message.forward_from)
        if update.message.reply_to_message.forward_from_chat:
            if sage.in_shield(
                    update.message.reply_to_message.forward_from_chat.id) == False:
                bang.append(update.message.reply_to_message.forward_from_chat)

        if bang:
            try:
                sent = bot.forward_message(
                    config.getint(
                        'log',
                        'evidence'),
                    update.message.reply_to_message.chat.id,
                    update.message.reply_to_message.message_id)
            except BaseException:
                sent = None
            if sent:
                evidence = sent.message_id
            else:
                evidence = 2
        else:
            text = ''
            if update.message.reply_to_message.forward_from:
                if sage.is_sage(
                        update.message.reply_to_message.forward_from.id):
                    text += f'<code>{update.message.reply_to_message.forward_from.id}</code> 有精靈護體 🌚'
                else:
                    text += f'<code>{update.message.reply_to_message.forward_from.id}</code> 白色恐怖快逃RRR 🌝'

            if update.message.reply_to_message.forward_from_chat:
                if sage.is_sage(
                        update.message.reply_to_message.forward_from_chat):
                    text += f'<code>{update.message.reply_to_message.forward_from_chat.id}</code> 有精靈護體 🌚'
                else:
                    text += f'<code>{update.message.reply_to_message.forward_from_chat.id}</code> 白色恐怖快逃RRR 🌝'
            update.message.reply_html(text)

        if Filters.sticker(update.message.reply_to_message):
            if update.message.reply_to_message.sticker.set_name:
                update_sticker = {
                    '$set': {
                        'sticker': {
                            'set_name': update.message.reply_to_message.sticker.set_name,
                            'tags': tags},
                        'opid': update.message.from_user.id,
                        'reason': tags_text,
                        'evidence': evidence}}
                mongo.sticker.find_one_and_update(
                    {'sticker.id': update.message.reply_to_message.sticker.file_id}, update_sticker, upsert=True)
                text = f'ID:<code>{update.message.reply_to_message.sticker.file_id}</code>\n'
                if update.message.reply_to_message.sticker.set_name:
                    # https://t.me/addstickers/nichijou
                    text += f'Set Name:https://t.me/addstickers/{update.message.reply_to_message.sticker.set_name}\n'
                text += _(f'標籤:<code>{tags_text}</code>')
                update.message.reply_html(text)
                sticker_judge.refresh()
        for chat in bang:
            update_user = {'$set': {'chat': chat.to_dict()}}
            mongo.user.find_one_and_update({'chat.id': chat.id}, update_user)
            text = excalibur(
                bot,
                update,
                uid=chat.id,
                opid=opid,
                until=until,
                reason=reason,
                tags=tags,
                user=chat,
                evidence=evidence)
            update.message.reply_html(text, web_page_preview=False)
Esempio n. 10
0
def namechecker(bot, update):
    """
    query_data rule
    category action data:data2

    bot leave  -100123456789 # bot leave group
    bot pass -100123456789 # keep bot in group
    user kick {update.message.chat.id}:{new_member.id}
    user pass {update.message.chat.id}:{new_member.id}
    user bypass {update.message.chat.id}:+{from_user.id}:-{new_member.id}
    +: keep, -: kick
    user back {update.message.chat.id}:+{from_user.id}:-{new_member.id}
    +: nothing, -: unban
    """
    query = update.callback_query
    callback = callabck_parse.callback_parse(query.data)

    if query.message.text_html:
        edit_msg = query.message.text_html
    else:
        edit_msg = query.message.caption_html

    if callback.qtype == 'user':
        target_chat_id, *targets = callback.qdata.split(':')
        if callback.qact == 'bypass':
            callback_data = f'user back {target_chat_id}'
            for target in targets:
                target_act, target_id = target[:1], target[1:]
                if target_act == '+':  # keep in group
                    edit_msg += f'\npass <code>{target_id}</code> by: {query.from_user.mention_html()}'
                    if target_id:
                        callback_data += f':+{target_id}'
                else:
                    try:
                        bot.kick_chat_member(target_chat_id, target_id)
                        edit_msg += f'\nkicked by: {query.from_user.mention_html()}'
                    except (BadRequest, Unauthorized) as e:
                        callback_data += f':+{target_id}'
                        try:
                            edit_msg += f'\nfailed to kick <code>{target_id}</code> by: {query.from_user.mention_html()}'
                        except TypeError:
                            query.answer('bot 並不在該群。', show_alert=True)
                            callback_data = None
                            return
                        if e.message == 'User is an administrator of the chat':
                            query.answer('你嘗試 bang 掉 admin。',
                                         show_alert=True)
                        elif e.message == 'Not enough rights to restrict/unrestrict chat member':
                            query.answer('Bot 在該群組並非 admin。',
                                         show_alert=True)
                            leave_group_msg = f'偵測到 <a href="tg://user?id={target_id}">spam 帳號</a>\n' \
                                '為 bot 正常運作請給予 admin 權限,請給予必要權限後再嘗試使用。\n' \
                                '有問題請至 @hexjudge 詢問。'
                            try:
                                bot.send_message(
                                    target_chat_id, leave_group_msg, parse_mode='html').done.wait()
                            except TelegramError as e:
                                edit_msg += '\n' + e.message
                                if e.message == 'Have no rights to send a message':
                                    pass
                            callback_data = None
                        elif e.message == 'Forbidden: bot is not a member of the supergroup chat':
                            query.answer('bot 並不在該群。', show_alert=True)
                            callback_data = None
                        else:
                            query.answer('發生了一些錯誤,一群訓練有素的猴子們正在圍觀。')
                            bot.send_message(
                                config.getint(
                                    'log',
                                    'error'),
                                f'<code>{escape(e.message)}</code>',
                                parse_mode='html')

                if callback_data is None:
                    keyboard = None
                else:
                    keyboard = [[InlineKeyboardButton(
                        '回去', callback_data=callback_data), ]]
        elif callback.qact == 'back':
            edit_msg += f'\nback by: {query.from_user.mention_html()}'
            if len(targets) == 2:
                for target in targets:
                    target_act, target_id = target[:1], target[1:]
                    if target_act == '-':
                        try:
                            bot.unban_chat_member(
                                target_chat_id, target_id)
                        except BadRequest as e:
                            if e.message == 'Not enough rights to restrict/unrestrict chat member':
                                query.answer('沒有力量去對那個人上下其手。')
                                return
                callback_data = [
                    f'user bypass {target_chat_id}:+{targets[0][1:]}:-{targets[1][1:]}',
                    f'user bypass {target_chat_id}:-{targets[0][1:]}:+{targets[1][1:]}',
                    f'user bypass {target_chat_id}:+{targets[0][1:]}:+{targets[1][1:]}',
                    f'user bypass {target_chat_id}:-{targets[0][1:]}:-{targets[1][1:]}',
                ]
                keyboard = [
                    [InlineKeyboardButton("掐死被邀人", callback_data=callback_data[0]),  # kick from_user group
                        InlineKeyboardButton("掐死邀請人", callback_data=callback_data[1])],  # kick new_member group
                    [InlineKeyboardButton("先放過", callback_data=callback_data[2]),  # keep both
                        InlineKeyboardButton("殉情", callback_data=callback_data[3])]]  # kick both
            else:
                for target in targets:
                    target_act, target_id = target[:1], target[1:]
                    if target_act == '-':
                        bot.unban_chat_member(target_chat_id, target_id)
                callback_data = [
                    f'user bypass {target_chat_id}:-{targets[0][1:]}',
                    f'user bypass {target_chat_id}:+{targets[0][1:]}']
                keyboard = [
                    [
                        InlineKeyboardButton(
                            '阿拉花瓜',
                            callback_data=callback_data[0]),
                        InlineKeyboardButton(
                            '他還只是個孩子啊',
                            callback_data=callback_data[1])]]

    try:
        reply_markup = None if keyboard is None else InlineKeyboardMarkup(
            keyboard)
    except UnboundLocalError:
        query.answer('這個按鈕似乎有問題...?')
        return

    bot.edit_message_text(text=edit_msg,
                          parse_mode='html',
                          chat_id=query.message.chat.id,
                          reply_markup=reply_markup,
                          message_id=query.message.message_id)
Esempio n. 11
0
def xmedia(bot, update):
    locales.i18n(update).loads.install(True)
    if in_shield(update.message.from_user.id):
        return
    if is_participate_white(bot, update):
        return

    query_user = mongo.user.find_one({'chat.id': update.message.from_user.id})
    if query_user:
        user = db_parse.user()
        user.parse(query_user)
        if user.current:
            if datetime.fromtimestamp(user.current.until).astimezone(
                    taiwan_country).year == 1970:
                return
    if is_admin(bot, update):
        return

    if Filters.photo(update.message):
        file = bytes(
            update.message.photo[-1].get_file().download_as_bytearray())

    bio = io.BytesIO(file)
    i = imagehash.hashing(bio)
    hashing = i.phash()
    middle = i.indexing()

    query_xmedia = list(
        mongo.xmedia.find(
            {'photo.indexing': {
                '$gte': middle - 10,
                '$lte': middle + 10
            }}))
    if query_xmedia == []:
        logger.info('no target found')
    if query_xmedia:
        compare_list = []
        for parse in query_xmedia:
            media = db_parse.media()
            media.parse(parse)
            compare_list.append(media.hash)

        compare_result = i.plooks_like(compare_list)
        if compare_result[-1].judge:

            query_photo = mongo.xmedia.find_one(
                {'photo.hash': compare_result[-1].hash})

            media = db_parse.media()
            media.parse(query_photo)
            if media.is_white:
                logger.debug(f'{hashing} in white list')
                return

            query_group = mongo.group.find_one(
                {'chat.id': update.message.chat.id})
            if query_group:
                group = db_parse.group()
                group.parse(query_group)
            else:
                return

            check = bool(
                set(group.config.sub_ban_list).intersection(list(media.tags)))
            if not check:
                pass
            else:
                try:
                    sent = update.message.forward(
                        config.getint('log', 'evidence')).message_id
                except BaseException:
                    sent = 2
                else:
                    until = druation(list(media.tags_list))
                    excalibur(bot,
                              update,
                              update.message.from_user.id,
                              media.tags_list,
                              media.opid,
                              until=until,
                              reason=media.reason,
                              evidence=sent,
                              user=update.message.from_user)
                    announce_ban = _(
                        '名字:{fullname}\n'
                        '傳送了已被標記為 <code>{tags}</code> 的圖片,已進行處置。').format(
                            fullname=update.message.from_user.mention_html(),
                            tags=media.tags_text)
                try:
                    update.message.delete()
                except BaseException:
                    pass
                try:
                    bot.restrict_chat_member(update.message.chat.id,
                                             update.message.from_user.id)
                except BadRequest as e:
                    if e.message == 'User is an administrator of the chat':
                        return
                    elif e.message == 'Not enough rights to restrict/unrestrict chat member':
                        text = _('⚠️權限不足⚠️\n') + announce_ban
                        update.message.reply_html(text)
                        return
                else:
                    sent = update.message.reply_html(announce_ban).result()
                    time.sleep(10)
                    try:
                        bot.delete_message(update.message.chat.id,
                                           sent.message_id)
                    except BaseException:
                        pass
                    finally:
                        homicide(bot, update, update.message.from_user.id)
                    return

    # NSFW DETECT #
    query_group = mongo.group.find_one({'chat.id': update.message.chat.id})
    if query_group is None:
        return
    group = db_parse.group()
    group.parse(query_group)
    check = bool(set(group.config.sub_ban_list_text).intersection(['p**n']))
    if not check:
        return
    if group.config.ml_nsfw in [None, False]:
        return

    nsfw = nsfw_detect(file=file)
    if nsfw.ban:
        abyss = config.getint('log', 'abyss')
        sent = update.message.forward(abyss)
        evidence = update.message.forward(config.getint('log', 'evidence'))
        record_msg = f'Name:{update.message.from_user.mention_html()}\n' \
            f'UID:<code>{update.message.from_user.id}</code>\n' \
            f'Checker:<code>NSFW</code>\n' \
            f'Group Name:<code>{update.message.chat.title}</code>\n' \
            f'Group ID:<code>{update.message.chat.id}</code>\n' \
            f'Group Username:{f"@{update.message.chat.username}" if update.message.chat.username else None}\n' \
            f'NSFW Score:<code>{nsfw.score}</code>\n' \
            f'#NSFW #tracker_{update.update_id}'
        bot.send_message(abyss,
                         record_msg,
                         parse_mode='html',
                         reply_to_message_id=sent.message_id)
        try:
            text = ''
            bot.restrict_chat_member(update.message.chat.id,
                                     update.message.from_user.id)
        except BadRequest as e:
            if e.message == 'Not enough rights to restrict/unrestrict chat member':
                text = _('⚠️權限不足⚠️\n')
        finally:
            text += _('淺行系統偵測到 <code>NSFW</code> 內容媒體,依照契約將吞食內容\n'
                      '名字:{fullname}\n'
                      'UID:<code>{uid}</code>\n'
                      '若有誤判請至 @hexjudge 報告 淺行系統 存在問題。\n'
                      '案件追蹤 ID:#tracker_{tracker_id}').format(
                          fullname=update.message.from_user.mention_html(),
                          uid=update.message.from_user.id,
                          tracker_id=update.update_id)
            try:
                update.message.delete()
            except BaseException:
                pass
            sent = update.message.reply_html(text).result()
            until = int((datetime.now(taiwan_country) +
                         timedelta(days=90)).timestamp())

            time.sleep(10)
            bot.delete_message(update.message.chat_id, sent.message_id)
            excalibur(bot,
                      update,
                      update.message.from_user.id, ['p**n'],
                      bot.id,
                      until=until,
                      reason='NSFW 自動偵測',
                      evidence=evidence.message_id,
                      user=update.message.from_user)

            homicide(bot, update, update.message.from_user.id)
Esempio n. 12
0
def ban_sticker(bot, update):
    i18n(update).loads.install(True)
    if update.message.forward_from:
        chat = update.message.forward_from
    elif update.message.forward_from_chat:
        chat = update.message.forward_from_chat
    else:
        chat = update.message.from_user
    if update.message.sticker.set_name is None:
        return
    if sage.in_shield(update.message.from_user.id):
        return
    group = db_parse.group()
    query_group = mongo.group.find_one({'chat.id': update.message.chat.id})
    group.parse(query_group)
    if group.white_participate:
        if update.message.from_user.id in group.white_participate:
            return
    if is_admin(bot,
                update,
                specfic=(update.message.chat.id, update.message.from_user.id)):
        return

    ban = sticker_judge.checker(bot, update, update.message.sticker.set_name)

    if ban:
        try:
            evidence = update.message.forward(config.getint('log', 'evidence'))
        except BaseException:
            evidence = 2

        if update.message.sticker.set_name:
            query_stiker = mongo.sticker.find_one(
                {'sticker.set_name': update.message.sticker.set_name})
        if query_stiker:
            sticker = db_parse.sticker()
            sticker.parse(query_stiker)
            query_user = mongo.user.find_one(
                {'chat.id': update.message.from_user.id})
            user = db_parse.user()
            user.parse(query_user)

            if sticker.day == 0:
                until = 0
            else:
                until = int((datetime.now(taiwan_country) +
                             timedelta(days=sticker.day)).timestamp())

            # check group sub with sticker ban
            check = bool(
                set(group.config.sub_ban_list).intersection(sticker.tags_list))
            logger.debug(
                f'sticker compare with group sub is {check}, should ban')

            if not check:
                return
            if until == 0:
                pass
            '''
            當 A 子在別的地方得到 mark as spam (ads), 在 B 群沒有訂閱 (ads) 而有訂閱 p**n,
            而 A 在貼了 mark as p**n 的貼圖。
            A 子會被踢出去,並且記錄在 banned_participate, 但不更新 ban.current
            '''
            single_ban = True
            if user.current and user.current.until != 0:
                single_ban = False
                update.message.from_user.fullname = update.message.from_user.full_name
                if evidence == 2:
                    evidence_ = sticker.evidence
                else:
                    evidence_ = evidence.message_id

                excalibur(bot,
                          update,
                          update.message.from_user.id,
                          sticker.tags,
                          sticker.opid,
                          until=until,
                          reason=sticker.reason,
                          evidence=evidence_,
                          user=update.message.from_user)
                announce_ban = _(
                    announce(update.message.from_user.id,
                             sticker.tags,
                             sticker.opid,
                             until=until,
                             reason=sticker.reason,
                             evidence=evidence_,
                             query_user=update.message.from_user))
            else:
                announce_ban = _(
                    '名字:{fullname}\n'
                    '傳送了 <code>{sticker}</code> 已被標記為 <code>{tags}</code> 的貼圖。'
                ).format(fullname=user.mention_html,
                         sticker=sticker.set_name,
                         tags=sticker.tags_text)
            try:
                update.message.delete()
            except BaseException:
                pass
            try:
                bot.restrict_chat_member(update.message.chat.id,
                                         update.message.from_user.id)
            except BadRequest as e:
                if e.message == 'User is an administrator of the chat':
                    return
                elif e.message == 'Not enough rights to restrict/unrestrict chat member':
                    text = _('⚠️權限不足⚠️\n') + announce_ban
                    update.message.reply_html(text)
                    return

            else:
                sent = update.message.reply_html(announce_ban).result()

            time.sleep(10)
            try:
                sent.delete()
            except BaseException:
                pass

            homicide(bot, update, update.message.from_user.id)