Example #1
0
def new_member_check_ban(bot, update, new_member):
    i18n(update).loads.install(True)
    if gatejieitai(
        bot,
        update,
        specfic=(
            update.message.chat.id,
            new_member.id)):
        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)

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

        if user.current.evidence is None:
            user.current.evidence = 2
        text = _('名字:{fullname}\n'
                 'UID:{uid}\n'
                 '證據:https://t.me/hexevidence/{evidence}\n'
                 '標籤:{tags}\n'
                 '因為 <code>{reason}</code>\n'
                 '封鎖至 <code>{until}</code>\n'
                 '處刑人:{execser}\n'
                 '有任何問題請至 @hexjudge 詢問').format(
                     fullname=new_member.mention_html(),
                     uid=new_member.id,
                     evidence=user.current.evidence,
                     tags=to_string(user.current.tags),
                     reason=user.current.reason,
                     until=user.current.date_text,
                     execser=user.current.opid)
        try:
            sent = bot.send_message(
                update.message.chat.id, text, parse_mode='html').result()
        except BadRequest as e:
            if e.message == 'Have no rights to send a message':
                pass
            logger.warn(e.message)
        time.sleep(5)
        try:
            sent.delete()
        except BadRequest as e:
            logger.warn(e.message)
        try:
            bot.kick_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 = _(
                    '因權限不足無法踢除 {fullname}\n'
                    '⚠️為bot正常運作,請給予admin權限⚠️').format(
                    fullname=new_member.mention_html())
                bot.send_message(text, parse_mode='html')
        return True
    return False
Example #2
0
def add_white(bot, update, args):
    i18n(update).loads.install(True)
    if len(args) == 0:
        try:
            update.message.delete()
        except BaseException:
            pass
        return
    admins = bot.get_chat_member(update.message.chat.id,
                                 update.message.from_user.id)
    if is_admin(bot, update) == False:
        try:
            update.message.delete()
        except BaseException:
            pass
        text = '此指令只允許管理員操作。'
        update.message.reply_text(text)
        return

    mongo = db_tools.use_mongo()
    if len(args) > 1:
        update.message.reply_text(_('傳入過多參數。'))
        return
    try:
        uid = int(args[0])
    except BaseException:
        update.message.reply_html(_(f'UID <code>{args[0]}</code> 解析錯誤 '))
        return
    if uid > 9999999999:
        update.message.reply_text(_('傳入怪怪的 UID 參數。'))
        return

    query_group = mongo.group.find_one({'chat.id': update.message.chat.id})
    if query_group:
        group = db_parse.group()
        group.parse(query_group)
        if group.white_participate:
            if uid in group.white_participate:
                text = _(f'<code>{uid}</code> 已在群組白名單內')
                update.message.reply_html(text)
        else:
            mongo.group.update_one(
                {'chat.id': group.id},
                {'$addToSet': {
                    'chat.white_participate': uid
                }},
                upsert=True)
            text = _('已更新白名單 ✅')
            update.message.reply_text(text)
    else:
        text = _('似乎發生了點問題...?\n') + \
            _('請先使用 <code>!hex config</code> 設定群組試試?')
        update.message.reply_html(text)
Example #3
0
def refresh():
    logger.warning('Rebuild Class Level Cache...')
    result = mongo.class_level.find_one({})
    lucifer = result['lucifer']
    michael = result['michael']
    elf = result['elf']
    for sage_calling, sage_name in zip([elf, michael, lucifer],
                                       ['elf', 'michael', 'lucifer']):
        redis.delete(sage_name)
        for x in sage_calling:
            redis.lpush(sage_name, x)
    groups = list(mongo.group.find())

    for group_ in groups:
        group = db_parse.group()
        group.parse(group_)
        redis.delete(f'white:{group.id}')
        if group.white_participate:
            for wp in group.white_participate:
                redis.lpush(f'white:{group.id}', wp)
    logger.warning('Rebuild Class Level Finished.')
Example #4
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')
Example #5
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
Example #6
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)
Example #7
0
def unban(bot, update):
    i18n(update).loads.install(True)
    # !hex unban u=123 r=噗噗噗
    if sage.michael(update.message.from_user.id) == False:
        update.message.reply_text('權限不足啦 🌚')
        return
    if sage.lucifer(update.message.from_user.id) == False:
        update.message.reply_text('權限不足啦 🌚')
        return

    args = update.message.text.split()
    if len(args) == 2:
        update.message.reply_text(_('缺少參數'))
        return
    reason = search('r={:S}', update.message.text)
    uid = search('u={:d}', update.message.text)

    if uid is None:
        update.message.reply_html(_('缺少 <code>u=</code> 參數'))
        return
    else:
        uid = uid[0]
    if reason is None:
        update.message.reply_html(_('缺少 <code>r=</code> 參數'))
        return
    else:
        reason = reason[0]

    mongo = db_tools.use_mongo()
    redis = db_tools.use_redis()
    query_user = mongo.user.find_one({'chat.id': uid})
    if query_user is None:
        update.message.reply_html(_('找不到這個人,失蹤了!!'))
        return

    user = db_parse.user()
    user.parse(query_user)
    if user.current is None:
        update.message.reply_html(_('這人沒有被封鎖過啊'))
        return

    user.current_raw['unban'] = reason
    update_user = {
        '$unset': {
            'current': ''
        },
        '$addToSet': {
            'history': user.current_raw
        }
    }
    mongo.user.find_one_and_update({'chat.id': uid}, update_user)
    redis.lrem('ban_cache', uid, 0)

    if user.banned_participate is None or user.banned_participate == []:
        update.message.reply_text('解除封鎖完成。')
        return

    groups = ''
    for ban in user.banned_participate:
        try:
            user_ = bot.get_chat_member(ban, uid)
        except BaseException:
            groups += _('解封失敗\n') + \
                f'{ban}'
        else:
            if user_.status == 'kicked':
                try:
                    bot.unban_chat_member(ban, uid)
                except BaseException:
                    groups += _('解封失敗\n') + \
                        f'{ban}'
                else:
                    query_group = mongo.group.find_one({'chat.id': ban})
                    if query_group:
                        group = db_parse.group()
                        group.parse(query_group)
                        groups += f'<code>{group.title}</code>\n' + \
                            f'<code>{ban}</code>\n' + \
                            f'{"="*10}\n'
                    else:
                        groups += f'<code>{ban}</code>'

                    update_user = {'$pull': {'chat.banned_participate': ban}}
                    mongo.user.find_one_and_update({'chat.id': uid},
                                                   update_user)
    update.message.reply_html('[解封完成]\n' + groups)
Example #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)
def groupconfig_callback(bot, update):
    query = update.callback_query
    i18n(update).loads.install(True)

    mongo = db_tools.use_mongo()
    callback = callabck_parse.callback_parse(query.data)
    query_group = mongo.group.find_one({'chat.id': query.message.chat.id})
    group = db_parse.group()
    group.parse(query_group)
    if sage.lucifer(query.from_user.id) or is_admin(
            bot, update, (query.message.chat.id, query.from_user.id)):
        pass
    else:
        text = '你又不是管理員 😘'
        query.answer(text, show_alert=True)
        return

    if group.config is None:
        return

    if callback.qact == 'keyboard' and callback.qdata == 'close':
        text = _('<code>[設定完成]</code>\n\n') + \
            _(f'<code>{escape(query.message.chat.title)}</code>\n') + \
            _('📋 已訂閱黑名單列表:\n')
        emoji_list = emojitags().emoji_dict
        sub = ''
        plugin_ = ''
        for emoji in emoji_list:
            if emoji_list[emoji]['emoji'][0] in group.config.sub_ban_list:
                sub += '{title}\n'.format(title=_(emoji_list[emoji]['title']))
        text += f'<pre>{sub}</pre>'

        for groupconfig_mcro in group.config_list_k:
            if groupconfig_mcro:
                plugin_ += '{title}\n'.format(title=generate.groupconfig_dict(
                    1)[groupconfig_mcro]['title'])
        if plugin_:
            text += _('⚙️ 已啟動附加功能:\n') + f'<pre>{plugin_}</pre>'

        query.edit_message_text(text=text, parse_mode='html')

    elif callback.qact == 'keyboard':
        if callback.qdata == '0':
            text = f'<code>{escape(query.message.chat.title)}</code>\n' + \
                _('📋 訂閱黑名單列表\n') + \
                _('本清單預設開啟 "兒童色情內容" \n') + \
                _('✅ - 開啟訂閱\n') + \
                _('❌ - 關閉訂閱')
            keyboard = generate.inline_groupconfig(bot, update, 0)
            query.edit_message_text(text=text,
                                    reply_markup=keyboard,
                                    parse_mode='html')

        elif callback.qdata == '1':
            text = f'<code>{escape(query.message.chat.title)}</code>\n' + \
                _('⚙️ 附加功能設定\n') + \
                _('✅ - 開啟訂閱\n') + \
                _('❌ - 關閉訂閱')
            keyboard = generate.inline_groupconfig(bot, update, 1)
            query.edit_message_text(text=text,
                                    reply_markup=keyboard,
                                    parse_mode='html')

        elif callback.qdata == '2':
            text = f'<code>{escape(query.message.chat.title)}</code>\n' + \
                '🌐 語言設定/Language Settings\n' + \
                _('✅ - Choosen\n')
            keyboard = generate.inline_groupconfig(bot, update, page=2)
            query.edit_message_text(text=text,
                                    reply_markup=keyboard,
                                    parse_mode='html')

    elif callback.qact == 'sub':
        # group.config.sub_ban_list
        click = to_emoji([callback.qdata])
        sub_total = len(emojitags().emoji_dict.keys()) - 1

        if click not in group.config.sub_ban_list and callback.qdata != 'spam':
            group.config.sub_ban_list.extend(click)
            if sub_total == len(group.config.sub_ban_list):
                group.config.sub_ban_list.append('💩')
            mongo.group.find_one_and_update(
                {'chat.id': query.message.chat.id}, {
                    '$set': {
                        'chat.config.sub_ban_list': group.config.sub_ban_list
                    }
                })
        elif click in group.config.sub_ban_list and callback.qdata != 'spam':
            group.config.sub_ban_list.remove(click[0])
            if sub_total == len(group.config.sub_ban_list):
                group.config.sub_ban_list.remove('💩')
            mongo.group.find_one_and_update(
                {'chat.id': query.message.chat.id}, {
                    '$set': {
                        'chat.config.sub_ban_list': group.config.sub_ban_list
                    }
                })

        if callback.qdata == 'spam':
            if sub_total > len(group.config.sub_ban_list):
                group.config.sub_ban_list = to_emoji(
                    list(emojitags().emoji_dict.keys()))
                mongo.group.find_one_and_update(
                    {'chat.id': query.message.chat.id}, {
                        '$set': {
                            'chat.config.sub_ban_list':
                            list(group.config.sub_ban_list)
                        }
                    })
            else:
                group.config.sub_ban_list = []
                mongo.group.find_one_and_update(
                    {'chat.id': query.message.chat.id}, {
                        '$set': {
                            'chat.config.sub_ban_list':
                            group.config.sub_ban_list
                        }
                    })

        keyboard = generate.inline_groupconfig(bot, update, 0)
        query.edit_message_reply_markup(reply_markup=keyboard)
        query.answer('Done.')

    elif callback.qact == 'set':
        # group.config.ml_nsfw
        if callback.qdata in group.config_list.keys():
            if group.config_list[callback.qdata]:
                mongo.group.find_one_and_update(
                    {'chat.id': query.message.chat.id},
                    {'$set': {
                        f'chat.config.{callback.qdata}': False
                    }},
                    upsert=True)
            else:
                mongo.group.find_one_and_update(
                    {'chat.id': query.message.chat.id},
                    {'$set': {
                        f'chat.config.{callback.qdata}': True
                    }},
                    upsert=True)
        else:
            if callback.qdata == 'all':
                group_config = query_group['chat']['config'].copy()
                for settings in generate.groupconfig_dict(1):
                    group_config[settings] = True
                if group_config == query_group['chat']['config']:
                    query.answer('>:(')
                    return
                mongo.group.find_one_and_update(
                    {'chat.id': query.message.chat.id},
                    {'$set': {
                        f'chat.config': group_config
                    }},
                    upsert=True)
            else:
                mongo.group.find_one_and_update(
                    {'chat.id': query.message.chat.id},
                    {'$set': {
                        f'chat.config.{callback.qdata}': True
                    }},
                    upsert=True)

        keyboard = generate.inline_groupconfig(bot, update, 1)
        try:
            query.edit_message_reply_markup(reply_markup=keyboard)
            query.answer('Done.')
        except Exception as e:
            logger.warning(e)

    elif callback.qact == 'langset':
        mongo.group.find_one_and_update(
            {'chat.id': query.message.chat.id},
            {'$set': {
                'chat.config.lang_code': callback.qdata
            }})
        keyboard = generate.inline_groupconfig(bot, update, 2)
        try:
            query.edit_message_reply_markup(reply_markup=keyboard)
            query.answer('Done.')
        except Exception as e:
            logger.warning(e)
Example #10
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)
Example #11
0
def gatejieitai(bot, update, specfic=False):
    # compare from_user and chat.id and tags if banned in group
    # return True if need action
    mongo = db_tools.use_mongo()
    redis = db_tools.use_redis()

    user = db_parse.user()
    group = db_parse.group()

    # check cache
    query_redis = redis.lrange('ban_cache', 0, -1)
    query_white = redis.lrange('white_cache', 0, -1)
    if specfic:
        specfic_chat, specfic_id = specfic
    else:
        specfic_chat, specfic_id = update.message.chat.id, update.message.from_user.id
    if str(specfic_id).encode() not in query_redis:
        logger.debug(f'{specfic_id} not in redis cache')
        return False
    if str(specfic_id).encode() in query_white:
        logger.debug(f'{specfic_id} in white cache')
        return False
    if sage.is_sage(specfic_id):
        logger.debug(f'{specfic_id} in sage')
        return False
    query_group_white = redis.lrange(f'white:{str(specfic_chat)}', 0, -1)
    if str(specfic_id).encode() in query_group_white:
        logger.debug(f'{specfic_id} in group white cache')
        return False

    else:
        user_query = mongo.user.find_one(
            {'chat.id': specfic_id})
        group_query = mongo.group.find_one({'chat.id': specfic_chat})
        user.parse(user_query)
        group.parse(group_query)
        if user.current is None:
            return False
        if group_query is None:
            return False
        date = datetime.fromtimestamp(
            user.current.until).astimezone(taiwan_country)
        now = datetime.now(taiwan_country)
        l = user.current.until - now.timestamp()
        if user.current.until - now.timestamp() > 0:
            # kick yout ass
            if group.config.sub_ban_list:
                # 比較兩者
                check = bool(set(group.config.sub_ban_list).intersection(
                    user.current.tags_list))
                if check:
                    return user
            else:
                # 沒有設定清單
                return False
        else:
            # bang for ever
            if date.year == 1970:
                if group.config and group.config.sub_ban_list:
                    check = bool(set(group.config.sub_ban_list).intersection(
                        user.current.tags_list))
                    if check:
                        return user
            # punishiment finished
            if user.current.until - now.timestamp() <= 0 and user.current.until != 0:
                logger.info('punishiment fin')
                mongo.user.find_one_and_update(
                    {'chat.id': specfic_id},
                    {'$set': {'chat.banned_participate': []}}
                )
                return False
Example #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)