Esempio n. 1
0
def xfilter_refresh():
    redis = db_tools.use_redis()
    mongo = db_tools.use_mongo()

    result = mongo.xtext_filter.find()
    redis.delete('xtext_filter')
    for x in list(result):
        redis.lpush('xtext_filter', x['rule'])
    return True
Esempio n. 2
0
def extinguish(bot, update, target: 'input chat.id and uid with int in tuple'):
    redis = db_tools.use_redis()
    chat, user = target[0], target[1]
    query_redis = redis.lrange(f'msg:{chat}', 0, -1)
    for data in query_redis:
        user_, message_id = data.decode().split(',')
        if int(user) == int(user_):
            try:
                bot.delete_message(chat_id=chat, message_id=message_id)
            except BadRequest as e:
                logger.warning(e)
            else:
                redis.lrem(f'msg:{chat}', data, num=1)
Esempio n. 3
0
def new_chat_members(bot, update):
    i18n(update).loads.install(True)
    mongo = db_tools.use_mongo()
    redis = db_tools.use_redis()

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

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

        # 安裝指南
        guide(bot, update)

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

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

            else:
                checker(bot, update, new_member)

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

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

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

            keyboard = InlineKeyboardMarkup(keyboard)
            bot.send_message(config.getint('log', 'namecheck'),
                             tmp,
                             parse_mode='html',
                             reply_markup=keyboard)
Esempio n. 4
0
from plugin import db_parse, db_tools
mongo = db_tools.use_mongo()
redis = db_tools.use_redis()


def refresh():
    query_sticker = mongo.sticker.find()
    redis.delete('sticker_cache')
    for query in query_sticker:
        sticker = db_parse.sticker()
        sticker.parse(query)
        if sticker.set_name:
            redis.lpush('sticker_cache', sticker.set_name)


def checker(bot, update, set_name=None):
    stickers = redis.lrange('sticker_cache', 0, -1)
    d = set_name.encode()
    if set_name and set_name.encode() in stickers:
        return True
    else:
        False
Esempio n. 5
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)
Esempio n. 6
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)
Esempio n. 7
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