Пример #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
Пример #2
0
def groupconfig(bot, update):
    i18n(update).loads.install(True)
    mongo = db_tools.use_mongo()
    try:
        update.message.delete()
    except BaseException:
        pass
    users = bot.get_chat_member(update.message.chat.id,
                                update.message.from_user.id)
    if is_admin(bot, update) == False or sage.lucifer(
            update.message.chat.id) == False:
        text = _('你不是管理員好嗎,請不要亂打擾我。')
        sent = update.message.reply_text(text).result()
        time.sleep(5)
        sent.delete()
        return
    text = f'<code>{escape(update.message.chat.title)}</code>\n' + \
        _('📋 訂閱黑名單列表\n') + \
        _('本清單預設開啟 "兒童色情內容" \n') + \
        _('✅ - 開啟訂閱\n') + \
        _('❌ - 關閉訂閱')
    keyboard = generate.inline_groupconfig(bot, update, 0)
    sent = update.message.reply_text(text,
                                     parse_mode='html',
                                     reply_markup=keyboard)
    mongo.group.find_one_and_update(
        {'chat.id': update.message.chat.id},
        {'$set': {
            'chat.config.configuring': sent.result().message_id
        }})
Пример #3
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')
Пример #4
0
def add_wl(bot, update, args):
    i18n(update).loads.install(True)
    if len(args) == 0:
        try:
            update.message.delete()
        except BaseException:
            pass
        return
    if sage.is_sage(update.message.from_user.id):
        if sage.lucifer(update.message.from_user.id) == False:
            try:
                update.message.delete()
            except BaseException:
                pass
            text = '你等級不夠 🌚\n最低等級要求是 <code>Lucifer</code>'
            update.message.reply_html(text)
            return
    else:
        try:
            update.message.delete()
        except BaseException:
            pass
        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_user = mongo.user.find_one({'chat.id': uid})
    if query_user:
        user = db_parse.user()
        user.parse(query_user)
        if user.is_white:
            text = _(f'<code>{uid}</code> 已在白名單內')
            update.message.reply_html(text)
        else:
            mongo.user.find_one_and_update({'chat.id': uid},
                                           {'$set': {
                                               'chat.is_white': True
                                           }})
            text = _('已更新全域白名單 ✅')
            update.message.reply_text(text)
    else:
        update_user = {'chat': {'id': uid, 'is_white': True}}
        mongo.user.insert(update_user)
        text = _('已更新全域白名單 ✅')
Пример #5
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)
Пример #6
0
def users(bot, update):
    # reply only
    i18n(update).loads.install(True)
    text = ''
    if update.message.reply_to_message.forward_from:
        uid = update.message.reply_to_message.forward_from.id
        text += _(f'被回覆人:<code>{uid}</code>')
    else:
        uid = update.message.reply_to_message.from_user.id
        text += _(f'被回覆人:<code>{uid}</code>')
    if uid:
        update.message.reply_html(text)
Пример #7
0
def eula(bot, update):
    i18n(update).loads.install(True)
    text = _('<pre>'
             '"海克斯真香協議" 初版\n'
             '@DingChen_Tsai 編訂此協議,並由 "海克斯" 宇宙成員們同意。'
             '只要你看到這個協議檔案,不管你有沒有打開看,只要使用了 "海克斯" 任何程式碼做'
             '任何事表示皆接受 "踢低吸真香" 此共識,並且將此協議文本保留在該專案底下,加入'
             '本協議可以隨時修改不再另行通知。未來有一天與我們任何一成員相遇了你可以買咖'
             '啡請當事人。 \n\n'
             '- @allen0099 @bestpika @DingChen_Tsai @smailzhu \n'
             '</pre>')
    update.message.reply_text(text, parse_mode='html')
Пример #8
0
def banstat(bot, update, args=None):
    i18n(update).loads.install(True)
    if args:
        text = banstat_user_args(bot, update, args)
        update.message.reply_text(text, parse_mode='html')

    elif Filters.reply(update.message) != True:
        text = banstat_user(bot, update)
        update.message.reply_text(text, parse_mode='html')

    elif Filters.reply(update.message):
        text = banstat_chat(bot, update)
        update.message.reply_text(text, parse_mode='html')
Пример #9
0
def about(bot, update):
    i18n(update).loads.install(True)
    text = _('本Bot隸屬於 <a href="https://t.me/hexuniverse">hex</a> 旗下\n'
             '並由多名小精靈共同維護,若有合作需求請洽 @orangetofu \n\n'
             '使用本Bot視同同意<code>海克斯真香協議</code> (詳情 /eula 查看)\n'
             '主要開發人員:\n'
             '@hexlightning @DingChen_Tsai @smailzhu\n'
             '主要嘴砲人員:@bestpika\n'
             '看板虎(娘):@allen0099\n'
             '人工智障奶子偵測器:@toy17 @NekoNymphJapari')

    update.message.reply_text(
        text, parse_mode='html', disable_web_page_preview=True)
Пример #10
0
def hint(bot, update):
    query = update.callback_query
    i18n(query).loads.install(True)

    mongo = db_tools.use_mongo()
    callback = callabck_parse.callback_parse(query.data)

    if callback.qact in ['groupconfig', 'guide']:
        if callback.qdata in emojitags().emoji_dict.keys():
            answer = emojitags().emoji_dict[callback.qdata]['hint']
        elif callback.qdata in generate.groupconfig_dict(1).keys():
            answer = generate.groupconfig_dict(1)[callback.qdata]['hint']

        query.answer(_('{answer}'.format(answer=answer)), show_alert=True)
Пример #11
0
def start(bot, update):
    i18n(update).loads.install(True)
    tmp = _('Hi!我是 hexlightning 以下是我的常用指令 \n\n'
            '[群組管理員]\n'
            '!bang - 回覆時使用,將該訊息刪除以及剔除該名成員,並且自動回報給團隊。\n'
            '!hex config - 在群組內發送查看黑名單訂閱狀況。\n\n'
            '[一般成員]\n'
            '/report /spam @admin !admin - 回覆時使用,將訊息回報給團隊。\n'
            '/banstat <uid> - 可回覆時使用,也可單獨使用,查看有無被標記黑名單。\n'
            '/ping - pong,檢察網路狀況。\n'
            '/eula - 僅私訊時可用,查看 hex 使用者條款。\n'
            '/user - 回覆時使用,查看使用者 ID\n'
            '/help - 你知道你正在看嗎?')
    update.message.reply_text(tmp)
Пример #12
0
def cleancb(bot, update):
    i18n(update).loads.install(True)
    kb = ReplyKeyboardMarkup([[ReplyKeyboardRemove]])
    try:
        update.message.delete()
    except BaseException:
        pass
    sent = update.message.reply_text(
        _('已清除鍵盤'), reply_markup=ReplyKeyboardRemove(
            remove_keyboard=True)).result()
    time.sleep(5)
    try:
        sent.delete()
    except BaseException:
        pass
Пример #13
0
def banstat_chat(bot, update):
    i18n(update).loads.install(True)

    if Filters.forwarded(update.message.reply_to_message):
        if update.message.reply_to_message.forward_from_chat:
            query = mongo.user.find_one(
                {'chat.id': update.message.reply_to_message.forward_from_chat.id})
            if query:
                user = db_parse.user()
                user.parse(query)
                text = _(f'頻道名稱:<code>{update.message.reply_to_message.forward_from_chat.title}</code>\n') + \
                    _(f'UID:<code>{update.message.reply_to_message.forward_from_chat.id}</code>\n') + \
                    _(f'標籤:{user.current.tags}\n') + \
                    _(f'證據:https://t.me/hexevidence/{user.current.evidence}\n') + \
                    _(f'封鎖日:<code>{user.current.date_text}</code>\n') + \
                    _(f'封鎖到:<code>{user.current.until_text}</code>')
                if sage.is_sage(
                        update.message.from_user.id) or sage.is_sage(
                        update.message.reply_to_message.from_user.id):
                    excuse = mongo.user.find_one(
                        {'chat.id': user.current.opid})
                    execser = db_parse.user()
                    execser.parse(excuse)
                    text = text + \
                        _(f'\n處刑人: <a href="tg://user?id={user.current.opid}">{execser.fullname}</a>')
            else:
                text = _(f'頻道名稱:<code>{update.message.reply_to_message.forward_from_chat.title}</code>\n') + \
                    _(f'UID:<code>{update.message.reply_to_message.forward_from_chat.id}</code>\n') + \
                    _(f'頻道未被封鎖')
            return text
        else:
            if update.message.reply_to_message.forward_from:
                update.message.from_user = update.message.reply_to_message.forward_from
                return banstat_user(bot, update)
            else:
                return _('找不到目標!\n可能來源訊息沒有連結到發送者帳號。')

    else:
        update.message.from_user = update.message.reply_to_message.from_user
        return banstat_user(bot, update)
Пример #14
0
def guide(bot, update):
    # install guide
    i18n(update).loads.install(True)
    '''
    安裝指南
    **注意**
    ⚠️這個安裝指引沒有回到上一頁的功能⚠️
    ------
    安裝指南

    給予 bot (ban, delete 權限)
    <a href="" 操作指南 a>
    ------
    安裝指南

    在群內發送 `!hex config` 進行訂閱黑名單。
    ------
    恭喜你安裝完成!
    若有其他問題可到 @hexjudge 內詢問
    以及可以參考說明手冊。
    本訊指引將在 N 秒後自動消失。
    ------
    '''
    tmp = '<code>安裝指南</code>\n' + \
        '**注意**\n' + \
        '⚠️這個安裝指引沒有回到上一頁的功能⚠️\n\n' + \
        '<code>Install Guide</code>\n' + \
        '**ATTENTION**\n' + \
        '⚠️This install guide only show once WITHOUT previous step button⚠️'
    keyboard = [[
        InlineKeyboardButton('Next ⏭', callback_data=f'guide keyboard 1')
    ]]
    reply_markup = InlineKeyboardMarkup(keyboard)

    bot.send_message(update.message.chat_id,
                     tmp,
                     parse_mode='html',
                     disable_web_page_preview=True,
                     reply_markup=reply_markup)
Пример #15
0
def banstat_user_args(bot, update, args):
    i18n(update).loads.install(True)
    try:
        uid = int(args[0])
    except ValueError as e:
        logger.warn(e)
        args = ' '.join(args)
        return _(f'<code>{args}</code> 啊...恩...啊...這..好像不是 UID')
    query = mongo.user.find_one({'chat.id': uid})
    text = ''
    if query:
        user = db_parse.user()
        user.parse(query)
        if user.current is None:
            text = _(f'UID:<code>{uid}</code>\n') + \
                _('並未被封鎖')
            return text
        text = ''
        if user.fullname:
            text += _(f'名字:<code>{user.fullname}</code>\n')
        text += _(f'UID:<code>{uid}</code>\n') + _(f'標籤:{user.current.tags}\n') + _(
            f'證據:https://t.me/hexevidence/{"2" if user.current.evidence == None else user.current.evidence}\n')
        if user.current.reason:
            text += _(f'說明:<code>{user.current.reason}</code>\n')
        text += _(f'封鎖日:<code>{user.current.date_text}</code>\n') + \
            _(f'封鎖到:<code>{user.current.until_text}</code>\n')
        if sage.is_sage(update.message.from_user.id):
            execser = db_parse.user()
            excuse = mongo.user.find_one(
                {'chat.id': user.current.opid})
            execser.parse(excuse)
            text = text + \
                _(f'\n處刑人:{execser.mention_html}')
        return text
    else:
        text = _(f'UID:<code>{uid}</code>\n') + \
            _('並未被封鎖')
        return text
Пример #16
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')
Пример #17
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
Пример #18
0
def ping(bot, update):
    i18n(update).loads.install(True)
    update.message.reply_text(_('pong'))
Пример #19
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)
Пример #20
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import locales.i18n as i18n

_ = i18n.ugettext('i18n_demo')


def i18n(n=1):
    if n == 1:
        return _('This is a translatable string3.')
    else:
        return _('This is a translatable string4.')


if __name__ == '__main__':
    print i18n()
Пример #21
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)
Пример #22
0
def banstat_user(bot, update):
    i18n(update).loads.install(True)
    query = mongo.user.find_one({'chat.id': update.message.from_user.id})
    user = db_parse.user()
    user.parse(query)
    if user.current:
        text = _(f'名字:{update.message.from_user.mention_html()}\n') + \
            _(f'UID:<code>{update.message.from_user.id}</code>\n') + \
            _(f'標籤:{user.current.tags}\n') + \
            _(f'證據:https://t.me/hexevidence/{user.current.evidence}\n')
        if user.current.reason:
            text += _(f'說明:<code>{user.current.reason}</code>\n')
        text += _(f'封鎖日:<code>{user.current.date_text}</code>\n') + \
            _(f'封鎖到:<code>{user.current.until_text}</code>\n')
        elfs = update.message.from_user.id
        if update.message.reply_to_message:
            elfs = update.message.reply_to_message.from_user.id
        if sage.is_sage(elfs):
            logger.info(user.current.opid)
            excuse = mongo.user.find_one({'chat.id': user.current.opid})
            execser = db_parse.user()
            execser.parse(excuse)
            text = text + \
                _(f'\n處刑人: {execser.mention_html}')
    elif user.current is None:
        text = _(f'名字:{update.message.from_user.mention_html()}\n') + \
            _(f'UID:<code>{update.message.from_user.id}</code>\n') + \
            _('並未被封鎖')

    if Filters.reply(
            update.message) and Filters.sticker(
            update.message.reply_to_message):
        judge = sticker_judge.checker(
            bot, update, set_name=update.message.reply_to_message.sticker.set_name)
        text_sticker = ''
        if judge:
            query_stiker = mongo.sticker.find_one(
                {'sticker.set_name': update.message.reply_to_message.sticker.set_name})
            sticker = db_parse.sticker()
            sticker.parse(query_stiker)
            text_sticker = _(f'貼圖:<code>{sticker.set_name}</code>\n') + \
                _(f'標籤:<code>{sticker.tags_text}</code>')
            text += f'\n<code>{"="*23}</code>\n' + text_sticker
        else:
            text_sticker = _(
                f'貼圖:<code>{update.message.reply_to_message.sticker.set_name}</code>\n') + _('貼圖並未被封鎖!')
            text += f'\n<code>{"="*23}</code>\n' + text_sticker

    if Filters.reply(
            update.message) and 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:
            media = db_parse.media()
            media.parse(query_photo)
            text_photo = _(f'圖片標記:<code>{media.hash}</code>\n') + \
                _(f'標籤:<code>{media.tags_text}</code>\n') + \
                _(f'天數:<code>{druation(media.tags_list)}</code>')
            if sage.is_sage(
                    update.message.from_user.id) or sage.is_sage(
                    update.message.reply_to_message.from_user.id):
                # add excutor
                execser = db_parse.user()
                excuse = mongo.user.find_one(
                    {'chat.id': media.opid})
                execser.parse(excuse)
                text_photo += _(f'\n處刑人:{execser.mention_html}')

            text += f'\n<code>{"="*23}</code>\n' + text_photo
        else:
            text_photo = _('圖片並未被封鎖!')
            text += f'\n<code>{"="*23}</code>\n' + text_photo
    return text
Пример #23
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)
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)
Пример #25
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)
Пример #26
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)
Пример #27
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)
Пример #28
0
def excalibur(
        bot,
        update,
        uid,
        tags,
        opid,
        date=None,
        until=0,
        reason=None,
        evidence=2,
        user=None,
        reply=False):
    i18n(update).loads.install(True)
    mongo = db_tools.use_mongo()
    redis = db_tools.use_redis()

    query_user = mongo.user.find_one({'chat.id': uid})
    parse = parser(uid, tags, opid, date=date, until=until,
                   reason=reason, evidence=evidence, user=user)
    if query_user:
        user_ = db_parse.user()
        user_.parse(query_user)

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

        elif user_.current is None:
            # 不是拉 警察這是我第一次拉
            # : 欸 我也是第一次開罰單啊 Q_Q
            # 辣我可以順便要你的電話嘛? OS: 好 好...好可愛
            # : Q_Q 不要投訴我啦
            user_update = {'$set': {'current': parse}}
            mongo.user.find_one_and_update({'chat.id': uid}, user_update)

    else:
        if user:
            user_update = {'chat': user.to_dict(), 'current': parse}
            mongo.user.insert(user_update)
        else:
            user_update = {'chat': {'id': uid}, 'current': parse}
            mongo.user.insert(user_update)

    ban_cache = redis.lrange('ban_cache', 0, -1)
    if str(uid).encode() not in ban_cache:
        redis.lpush('ban_cache', uid)
    if query_user:
        return announce(
            uid,
            tags,
            opid,
            date=None,
            until=until,
            reason=reason,
            evidence=evidence,
            query_user=user_,
            reply=False)
    else:
        return announce(uid, tags, opid, date=None, until=until,
                        reason=reason, evidence=evidence)
Пример #29
0
def hexban_long(bot, update):
    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()
        return
    if sage.elf(update.message.from_user.id):
        update.message.reply_text(_('等級不夠 🌚'))
        return
    # !hex ban u=123 t=spam

    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:
        update.message.reply_html(_('缺少 <code>標籤</code> 參數。'))
        return
    elif uid is None:
        update.message.reply_html(_('缺少 <code>UID</code> 參數。'))
        return

    if uid:
        uid = uid[0]
    if tags:
        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())

    if sage.in_shield(uid):
        if sage.is_sage(uid):
            text = '精靈保護 🌚'
        else:
            text = '白色恐怖ㄉ力量 🌝'
        update.message.reply_text(text)
        return

    until_text = datetime.fromtimestamp(until).astimezone(taiwan_country)
    opid = update.message.from_user.id

    tags_text = ', '.join(tags)

    evidence = 2
    opid = update.message.from_user.id
    if reason:
        reason = reason[0]
    else:
        reason = tags_text
    query_user = mongo.user.find_one({'chat.id': uid})

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

    text = ''
    if query_user:
        user = db_parse.user()
        user.parse(query_user)
        if user.fullname:
            if user.id < 0:
                text += _(f'頻道:<code>{user.fullname}</code>\n')
            else:
                text += _(f'名字:<code>{user.fullname}</code>\n')
    text += _(f'UID:<code>{uid}</code>\n') + \
        _(f'標籤:<code>{tags_text}</code>\n') + \
        _(f'證據:https://t.me/hexevidence/{evidence}\n')
    if until == 0:
        text += _(banyourwords.forever.format(reason=reason))
    else:
        text += _(banyourwords.temp.format(reason=reason, date=until_text))

    update.message.reply_html(text, web_page_preview=False)
Пример #30
0
def admins_text(bot, update, args=''):
    i18n(update).loads.install(True)
    if len(args) == 0:
        if Filters.group(update.message):
            mention = '目前群組:\n'
            creator = None  # Creator is not set now
            administrator = list()  # Administrators is not set now

            # Make sure Creator is not in list
            get_admins = bot.get_chat_administrators(
                update.message.chat.id).result()
            for u in get_admins:
                if u.status != 'creator':
                    administrator.append(u)
                else:
                    creator = u  # Set creator

            admins = [creator]  # Make creator in 0
            administrator.sort(key=sort_key)

            for u in administrator:
                admins.append(u)

            for users in admins:
                if users.status == 'creator':
                    mention += _('群主:') + users.user.mention_html() + '\n'
                    continue
                # List Permission
                if users.can_change_info is True:
                    mention += 'ℹ️'
                else:
                    mention += '🌚'
                if users.can_delete_messages is True:
                    mention += '🗑️'
                else:
                    mention += '🌚'
                if users.can_restrict_members is True:
                    mention += '🚫'
                else:
                    mention += '🌚'
                if users.can_pin_messages is True:
                    mention += '📌'
                else:
                    mention += '🌚'
                if users.can_invite_users is True:
                    mention += '🔗'
                else:
                    mention += '🌚'
                if users.can_promote_members is True:
                    mention += '➕'
                else:
                    mention += '🌚'

                mention += users.user.mention_html() + '\n'
            return mention
    elif len(args) == 1:
        if args[0].startswith('https://t.me/'):
            args[0] = args[0].replace('https://t.me/', '@')
        if args[0].startswith('@') or args[0].startswith('-100'):
            try:
                mention = _('群組內的管理員') + args[0] + '\n'
                creator = None
                administrator = list()

                for u in bot.get_chat_administrators(args[0]):
                    if u.status != 'creator':
                        administrator.append(u)
                    else:
                        creator = u

                admins = [creator]
                administrator.sort(key=sort_key)

                for u in administrator:
                    admins.append(u)

                for users in admins:
                    if users.status == 'creator':
                        mention += _('群主:') + users.user.mention_html() + '\n'
                        continue
                    if users.can_change_info is True:
                        mention += 'ℹ️'
                    else:
                        mention += '🌚'
                    if users.can_delete_messages is True:
                        mention += '🗑️'
                    else:
                        mention += '🌚'
                    if users.can_restrict_members is True:
                        mention += '🚫'
                    else:
                        mention += '🌚'
                    if users.can_pin_messages is True:
                        mention += '📌'
                    else:
                        mention += '🌚'
                    if users.can_invite_users is True:
                        mention += '🔗'
                    else:
                        mention += '🌚'
                    if users.can_promote_members is True:
                        mention += '➕'
                    else:
                        mention += '🌚'

                    mention += users.user.mention_html() + '\n'
                return mention
            except TelegramError:
                return '<b>錯誤</b> 檢查輸入的內容'
        else:
            return '傳送 <b>@groupname</b> 或群組 UID.'
    else:
        return '不要停!!嗯嗯 ... 你給太多參數了!恩...'