Exemple #1
0
    def _if_conquest(self):
        '''   Захват-передача локации.   '''
        enemy_code = db.check('SELECT code FROM loc WHERE name = ?',
                              [self.enemy_head])
        db.query(
            'UPDATE loc SET work_status = "⏳", conqueror = ? WHERE name = ? and lvl = ?',
            [self.enemy_head, self.loc_name,
             int(self.loc_lvl)])

        if enemy_code:
            db.query(
                'INSERT INTO loc_history (code,time,url,txt) VALUES (?,?,?,?)',
                [
                    enemy_code[0], self.date, self.message_id,
                    '<b>{}{} lvl.{}[✅🚩]</b>'.format(
                        LOC_TYPES.get(self.loc_name.split(' ')[-1]),
                        self.loc_name, self.loc_lvl)
                ])

        if self.conqueror != 'Forbidden Clan':
            db.query(
                'INSERT INTO loc_history (code,time,url,txt) VALUES (?,?,?,?)',
                [
                    self.code, self.date, self.message_id,
                    '<b>{}{} lvl.{}[🚫🚩]</b>'.format(
                        LOC_TYPES.get(self.loc_name.split(' ')[-1]),
                        self.loc_name, self.loc_lvl)
                ])
async def loc_info_answer(mes: Message, loc: list):
    code, name, lvl, conqueror = loc[0], loc[1], loc[2], loc[3]
    if lvl == 99:
        guilds = mes.db.checkall(
            'SELECT guild_emoji, guild_tag FROM al_guild_info WHERE code = ?',
            [loc[0]])
        guilds = ','.join(['{}[{}]'.format(l[0], l[1])
                           for l in guilds]) if guilds else 'Нет данных'

        capture_locs = mes.db.checkall(
            'SELECT code,name,lvl FROM loc WHERE conqueror = ? ORDER BY lvl LIMIT 5',
            [name])
        capture_locs_num = len(
            mes.db.checkall(
                'SELECT code,name,lvl FROM loc WHERE conqueror = ?', [name]))
        capture_locs = '\n'.join(['<a href="https://t.me/share/url?url=/l_info%20{}"><b>{}{} lvl.{}</b></a>'.format(
            l[0], LOC_TYPES.get(l[1].split(' ')[-1], 'error'), l[1], str(l[2])) for l in \
            capture_locs]) if capture_locs else 'Нет данных'
        capture_locs += '\n...' if capture_locs_num > 5 else ''

        loc_history = mes.db.checkall(
            'SELECT time, url, txt FROM loc_history WHERE code = ? ORDER BY -url LIMIT 5',
            [code])
        loc_history_num = len(loc_history)
        loc_history = '\n\n'.join([
            '[{}]\n{}'.format(
                '<a href="https://t.me/ChatWarsDigest/{}">{}</a>'.format(
                    str(l[1]), l[0]), l[2]) for l in loc_history
        ])
        loc_history = loc_history if loc_history else 'Нет данных'
        loc_history += '\n...' if loc_history_num > 5 else ''

        answer = AL_INFO_TEXT.format(name, code, guilds, code,
                                     capture_locs_num, capture_locs, code,
                                     loc_history)

    else:
        buffs = mes.db.checkall(
            'SELECT bless_type, bless_name FROM loc_buff_info WHERE code = ?',
            [code])
        conq_code = mes.db.check('SELECT code FROM loc WHERE name = ?',
                                 [conqueror])
        conqueror = '<a href="https://t.me/share/url?url=/l_info%20{}"><b>🎪{}</b></a>'.format(conq_code[0], conqueror)\
            if conq_code else 'Нет данных'

        answer = LOC_INFO_TEXT.format(
            LOC_TYPES.get(loc[1].split(' ')[-1], 'error'), name, str(lvl),
            code, conqueror, (await buff_f(buffs)))
    return answer
async def l_capture(mes: Message):
    if not uc.check_perm_role(mes.from_user.id, [2, 3, 4]):
        await mes.answer('Доступ запрещён.')
        return
    if len(mes.text) < 12:
        await mes.answer('/l_capture [code]')
        return

    code = mes.text[11:]
    loc = mes.db.check('SELECT name,lvl,conqueror FROM loc WHERE code = ?',
                       [code])

    if not loc:
        await mes.answer('Данной локации нет в базе данных.')
        return
    if loc[1] != 99:
        await mes.answer('Информация доступна только по альянсам.')
        return

    capture_locs = mes.db.checkall(
        'SELECT code,name,lvl FROM loc WHERE conqueror = ? ORDER BY lvl LIMIT 20',
        [loc[0]])
    capture_locs = '\n'.join(['<a href="https://t.me/share/url?url=/l_info%20{}"><b>{}{} lvl.{}</b></a>'.format(
        l[0], LOC_TYPES.get(l[1].split(' ')[-1], 'error'), l[1], str(l[2])) for l in \
        capture_locs]) if capture_locs else 'Нет данных'

    await mes.answer(AL_CAPTURE_TEXT.format(code, capture_locs),
                     disable_web_page_preview=True)
async def create_pin_loc_list(mes: Message):
    mes_text = CALL_DATA_LOC_TYPE_DICT.get('loc_type_cap')
    als = mes.db.checkall(
        'SELECT name, lvl, code FROM loc WHERE lvl = 99 ORDER BY name', [])
    txt = '<u><b>{}</b></u>\n\n'.format(mes_text['text'])
    for al in als:
        # All locations of alliance
        locs = mes.db.checkall(
            'SELECT code,name,lvl,working,work_status FROM loc WHERE conqueror = ? ORDER BY lvl',
            [al[0]])
        if not locs:
            continue

        # String with alliance
        if al[0] == 'Alert Eyes':
            txt += f'<b>⚜🎪{al[0]} ({len(locs)}):</b> — <code>/ga_def_{al[2]}</code>\n'
        else:
            txt += f'<b>⚜🎪{al[0]} ({len(locs)}):</b> — <code>/ga_atk_{al[2]}</code>\n'
        if al[0] == 'Alert Eyes':
            for l in locs:
                c = 'None' if l[0].startswith('NoneCode') else l[0]
                txt += '{} {} lvl.{} [{}{}] — <code>/ga_def_{}</code>\n'.format(
                    LOC_TYPES.get(l[1].split(' ')[-1], 'error'), l[1],
                    str(l[2]), str(l[3]), l[4], c)
        else:
            for l in locs:
                c = 'None' if l[0].startswith('NoneCode') else l[0]
                txt += '{} {} lvl.{} [{}{}] — <code>/ga_atk_{}</code>\n'.format(
                    LOC_TYPES.get(l[1].split(' ')[-1], 'error'), l[1],
                    str(l[2]), str(l[3]), l[4], c)
        txt += '\n'

    empty_locs = mes.db.checkall(
        'SELECT code,name,lvl FROM loc WHERE conqueror = "Forbidden Clan" ORDER BY lvl',
        [])
    len_el = len(empty_locs)
    txt += f'<b>🏴‍☠ Forbidden Clan ({len_el})</b>{":" if len_el else ""}\n'
    if len_el:
        for l in empty_locs:
            txt += '{} {} lvl.{} — <code>/ga_atk_{}</code>\n'.format(
                LOC_TYPES.get(l[1].split(' ')[-1], 'error'), l[1], str(l[2]),
                'None' if l[0].startswith('NoneCode') else l[0])

    await mes.answer(txt)
async def loc_list_query(query: InlineQuery):
    if not uc.select_id(query.from_user.id):
        return

    mes_text = CALL_DATA_LOC_TYPE_DICT.get('loc_type_cap')
    res = query.db.checkall(
        'SELECT name, lvl, code FROM loc WHERE lvl = 99 ORDER BY name', [])
    txt = '<u><b>{}</b></u>\n\n'.format(mes_text['text'])
    for el in res:
        locs = query.db.checkall(
            'SELECT code,name,lvl,working,work_status FROM loc WHERE conqueror = ? ORDER BY lvl',
            [el[0]])
        if not locs: continue
        txt += '<b>{}{} ({}):</b>\n'.format('⚜🎪 ', el[0], len(locs))
        for l in locs:
            txt += '{}{} lvl.{} [{}{}]\n'.format(
                LOC_TYPES.get(l[1].split(' ')[-1], 'error'), l[1], str(l[2]),
                str(l[3]), l[4])
        txt += '\n'
    empty_locs = query.db.checkall(
        'SELECT code,name,lvl FROM loc WHERE conqueror = "Forbidden Clan" ORDER BY lvl',
        [])
    len_el = len(empty_locs)
    txt += f'<b>🏴‍☠ Forbidden Clan ({len_el})</b>{":" if len_el else ""}\n'
    if len_el:
        for l in empty_locs:
            txt += '{}{} lvl.{}</a>\n'.format(
                LOC_TYPES.get(l[1].split(' ')[-1], 'error'), l[1], str(l[2]))

    results = []
    results.append(
        InlineQueryResultArticle(id=query.from_user.id,
                                 title='🚩Карта',
                                 description='Карта мира',
                                 input_message_content=InputTextMessageContent(
                                     message_text=txt, parse_mode='HTML')))
    await query.answer(results=results, cache_time=1, is_personal=True)
async def loc_miss(mes: Message):
    if not uc.select_id(mes.from_user.id):
        await mes.answer('Доступ запрещён.')
        return

    res = mes.db.checkall('SELECT name, lvl FROM loc WHERE code LIKE "NoneCode%"', [])
    answer = '<b><u>🔎Разыскиваемые локации:</u></b>\n\n{}'
    txt = ''
    if not res:
        answer = answer.format('Пусто')
        await mes.answer(answer)
        return
    for i, l in enumerate(res):
        txt += '<b>{}){} {} lvl.{}</b>\n\n'.format(i+1, LOC_TYPES.get(l[0].split(" ")[-1]), l[0], l[1])
    await mes.answer(answer.format(txt))
Exemple #7
0
    def work(self, event: str):
        '''   Основной метод обработки каждого ивента.   '''
        self.event = event
        self.loc_name, self.loc_lvl, self.status, self.enemy_head, self.code, self.conqueror = self.parse(
            event)
        self.atk_answer, self.def_answer = '', ''

        for line in event.split('\n'):
            if '🎖Attack:' in line:
                self.atk_in_event_line(line)
            elif '🎖Defense:' in line:
                self.def_in_event_line(line)

        if 'belongs to' in self.event:
            self._if_conquest()
        elif 'Forbidden' not in self.event:
            working_num = db.check('SELECT working FROM loc WHERE code = ?',
                                   [self.code])[0]
            db.query(
                'UPDATE loc SET work_status = "⚡", working = ? WHERE code = ?',
                [working_num + 1, self.code])

        own = '🔷' if self.conqueror == 'Alert Eyes' else ''
        loc_type = LOC_TYPES.get(self.loc_name.split(' ')[-1])
        name_lvl = '{} lvl.{}'.format(self.loc_name, self.loc_lvl)
        new_owner = f'\n➕🚩[{self.enemy_head}]' if self.enemy_head else ''

        ans = Location(
            '<b>{}{}{} [{}]</b>'.format(own, loc_type, name_lvl, self.status),
            self.loc_lvl)
        if loc_type == '🏷':
            self.ruins.append(ans)
        elif loc_type == '📦':
            self.mines.append(ans)
        elif loc_type == '🎖':
            self.forts.append(ans)

        self.answer_mode1 += '<b>{}{}{} [{}]{}</b>\n{}{}\n'.format(
            own, loc_type, name_lvl, self.status, new_owner, self.atk_answer,
            self.def_answer)
async def new_loc(mes: Message):
    if not datetime.datetime.now() - mes.forward_date < datetime.timedelta(
            days=2):
        return

    # Определение это локация или альянс и расфасовка в словарь
    result = re.search(NEW_LOC_INPUT_PARSE, mes.text).groupdict()
    result = {k: v for k, v in result.items() if v is not None}
    code = result.get("loc_code", result.get("head_code"))

    # Определение есть ли данная точка в БД
    if mes.db.check('SELECT * FROM loc WHERE code = ?', [code]):
        l = await mes.answer('Данная локация уже есть в базе.')
        await asyncio.sleep(2)
        await bot.delete_message(mes.chat.id, mes.message_id)
        await asyncio.sleep(8)
        await l.delete()
        return

    name = result.get("loc_name", result.get("head_name"))
    lvl = int(result.get("loc_lvl", "99"))
    type = LOC_TYPES.get(name.split(' ')[-1], '🎪 ')

    check = mes.db.check('SELECT code from loc WHERE name = ? and lvl = ?',
                         [name, lvl])
    if check:
        if check[0].startswith('NoneCode'):
            mes.db.query('UPDATE loc SET code = ? WHERE name = ? and lvl = ?',
                         [code, name, lvl])
        else:
            mes.db.query('INSERT INTO loc (name, lvl, code) VALUES (?,?,?)',
                         [name, lvl, code])
    else:
        mes.db.query('INSERT INTO loc (name, lvl, code) VALUES (?,?,?)',
                     [name, lvl, code])

    # Награда за нахождение
    top = mes.db.check('SELECT top_loc FROM users WHERE id = ?',
                       [mes.from_user.id])
    if top:
        mes.db.query('UPDATE users SET top_loc = top_loc + 1 WHERE id = ?',
                     [mes.from_user.id])
        uc.loading()

    # Оповещение о новой локации
    answer = type + name + ("" if lvl == 99 else " lvl. " + str(lvl))
    text = f'Обнаружена новая локация!\n\n<b>{answer}</b>\n  └ <code>{code}</code>\n\nНашедший: @{mes.from_user.username}'
    chats = mes.db.checkall('SELECT id FROM chats WHERE new_loc_ntf = 1', [])

    if not chats:
        await mes.answer('Новая локация! {}'.format(
            'Зачислен +1 балл! (/top)'
            if top else 'Балл не засчитан, требуется регистрация.'))
        return

    for chat in chats:
        try:
            await bot.send_message(chat[0], text)
        except:
            pass
        await asyncio.sleep(0.3)
    await mes.answer(
        'Новая локация! {}'.format('Зачислен +1 балл!' if top else
                                   'Балл не засчитан, требуется регистрация.'))
async def loc_type(call: CallbackQuery):
    await call.answer(cache_time=2)
    mes_text = CALL_DATA_LOC_TYPE_DICT.get(call.data)

    # 🚩Карта
    if call.data == 'loc_type_cap':
        als = call.db.checkall(
            'SELECT name, lvl, code FROM loc WHERE lvl = 99 ORDER BY name', [])
        txt = '<u><b>{}</b></u>\n\n'.format(mes_text['text'])
        for al in als:
            # All locations of alliance
            locs = call.db.checkall(
                'SELECT code,name,lvl,working,work_status FROM loc WHERE conqueror = ? ORDER BY lvl',
                [al[0]])
            if not locs:
                continue

            # String with alliance
            txt += f'<b>⚜🎪<a href="https://t.me/share/url?url=/l_info%20{al[2]}">{al[0]}</a> ({len(locs)}):</b>\n'
            for l in locs:
                txt += '{} <a href="https://t.me/share/url?url=/l_info%20{}">{} lvl.{}</a> [{}{}]\n'.format(
                    LOC_TYPES.get(l[1].split(' ')[-1], 'error'), l[0], l[1],
                    str(l[2]), str(l[3]), l[4])
            txt += '\n'

        empty_locs = call.db.checkall(
            'SELECT code,name,lvl FROM loc WHERE conqueror = "Forbidden Clan" ORDER BY lvl',
            [])
        len_el = len(empty_locs)
        txt += f'<b>🏴‍☠ Forbidden Clan ({len_el})</b>{":" if len_el else ""}\n'
        if len_el:
            for l in empty_locs:
                txt += '{} <a href="https://t.me/share/url?url=/l_info%20{}">{} lvl.{}</a>\n'.format(
                    LOC_TYPES.get(l[1].split(' ')[-1], 'error'), l[0], l[1],
                    str(l[2]))

        await call.message.edit_text(txt, reply_markup=loc_keyboard)
        return

    # 🎪Альянсы
    if call.data == 'loc_type_al':
        res = call.db.checkall(
            'SELECT name, lvl, code FROM loc WHERE lvl = 99 ORDER BY name', [])

    # 🏷Руины & 📦Шахты
    elif call.data == 'loc_type_ruins' or call.data == 'loc_type_mines':
        res = call.db.checkall(
            'SELECT name, lvl, code FROM loc WHERE name LIKE {} ORDER BY lvl'.
            format(mes_text['parse']), [])

    # 🎖Форты
    elif call.data == 'loc_type_forts':
        res = call.db.checkall(
            'SELECT name, lvl, code FROM loc WHERE name IN {} ORDER BY lvl'.
            format(mes_text['parse']), [])

    txt = '<u><b>{}</b></u>\n\n'.format(mes_text['text'])
    for i, el in enumerate(res):
        num, type, name = i + 1, mes_text['type'], str(el[0])
        lvl, code = '' if not mes_text['parse'] else ' lvl.' + str(el[1]), str(
            el[2])
        txt += f'<b>{num}){type}{name}{lvl}</b> — <code>{code}</code>\n\n'
    await call.message.edit_text(txt, reply_markup=loc_keyboard)
Exemple #10
0
async def loc_check_f(mes: Message):
    #journal_log(mes)
    if not uc.check_perm_role(mes.from_user.id, [2, 3, 4]):
        await mes.answer('Доступ запрещён.')
        return

    if mes.from_user.id != ADMIN:
        now = datetime.datetime.now()
        now_str = now.strftime('%Y-%m-%d-%H-%M-%S')
        last_update = mes.db.check(
            'SELECT info FROM settings WHERE name = "last_l_check_datetime"')

        if last_update and last_update[0]:
            lu = last_update[0].split('-')
            td = datetime.timedelta(hours=7, minutes=59)
            lu_date = datetime.datetime(year=int(lu[0]),
                                        month=int(lu[1]),
                                        day=int(lu[2]),
                                        hour=int(lu[3]),
                                        minute=int(lu[4]),
                                        second=int(lu[5]))

            if now - lu_date < td:
                l = await mes.answer(
                    f'Не доступно! Запрещено до {lu_date + td}.\nДля экстренной проверки обратитесь к @Irrenriel.'
                )
                await asyncio.sleep(2)
                await mes.delete()
                await asyncio.sleep(3)
                await l.delete()
                return
            else:
                mes.db.query(
                    'UPDATE settings SET info = ? WHERE name = "last_l_check_datetime"',
                    [now_str])
        else:
            mes.db.query(
                'UPDATE settings SET info = ? WHERE name = "last_l_check_datetime"',
                [now_str])

    await mes.answer('Выполняется, жди...')
    err = "Strange fog is so dense that you can't reach this place."
    text = 'Истёкшие локации!\n\n'
    req = 'SELECT code FROM loc WHERE lvl != 99' if mes.text.startswith(
        '/l_chk') else 'SELECT code FROM loc'
    locs = mes.db.checkall(req)
    result = []

    await main_client.connect()
    for loc in locs:
        if loc[0].startswith('NoneCode'):
            continue
        async with main_client.conversation(CW_BOT_ID) as conv:
            time.sleep(float(str(random.uniform(1, 3))[0:4]))
            await conv.send_message('/ga_atk_' + loc[0])
            ga_atk_answer = await conv.get_response()

            if ga_atk_answer.message == 'Ты сейчас занят другим приключением. Попробуй позже.' or 'Ветер завывает по окрестным лугам, замки как будто вымерли. Это воины зашивают раны и латают доспехи после тяжелой битвы. Ближайшие несколько минут все учреждения и ворота замка закрыты. Жди сводки с полей в @ChatWarsDigest.':
                await mes.answer(
                    'Мы сейчас заняты другим приключением. Попробуйте позже.')
                return

            if ga_atk_answer.message == err:
                time.sleep(float(str(random.uniform(1, 3))[0:4]))
                await conv.send_message('/ga_def_' + loc[0])
                ga_def_answer = await conv.get_response()

        if ga_atk_answer.message == err and ga_def_answer.message == err:
            req = mes.db.check(
                'SELECT name, lvl, code FROM loc WHERE code = ?', [loc[0]])
            answer = LOC_TYPES.get(req[0].split(' ')[-1], '🎪 ') + req[0] + (
                "" if req[1] == 99 else " lvl. " + str(req[1]))
            result.append('<b>{}</b>\n  └ <code>{}</code>'.format(
                answer, req[2]))
            mes.db.query('DELETE FROM loc WHERE code = ?', [loc[0]])
            mes.db.query('DELETE FROM loc_buff_info WHERE code = ?', [loc[0]])
            if not mes.text.startswith('/l_chk'):
                mes.db.query('DELETE FROM al_guild_info WHERE code = ?',
                             [loc[0]])

    chats = mes.db.checkall('SELECT id FROM chats WHERE delete_loc_ntf = 1',
                            [])
    if not chats and not result:
        await mes.answer('Done!')
        return
    for chat in chats:
        try:
            await bot.send_message(chat[0], text + '\n\n'.join(result))
        except:
            pass
        await asyncio.sleep(0.3)
    await mes.answer('Done!')
    mes.db.query('UPDATE settings SET info = ? WHERE name = "last_l_check"',
                 [str(datetime.datetime.today().strftime('%d.%m.%Y %H:%M'))])

    async with main_client.conversation(CW_BOT_ID) as conv:
        time.sleep(float(str(random.uniform(1, 3))[0:4]))
        await conv.send_message('/myshop_open')
    await main_client.disconnect()