예제 #1
0
def get_message_forward_time(message):
    try:
        forward_message_date = utc.localize(
            message.forward_date).astimezone(tz=moscow_tz).replace(tzinfo=None)
    except ValueError:
        try:
            forward_message_date = message.forward_date
        except AttributeError:
            forward_message_date = local_tz.localize(
                message.date).astimezone(tz=moscow_tz).replace(tzinfo=None)
    return forward_message_date
예제 #2
0
def add_trap(bot, update):
    """
    Функция сохраняет результаты сработавшей ловушки
    """
    mes = update.message
    player = Player.get_player(mes.from_user.id)
    if player is None:
        return
    if player.game_class != 'Ranger':
        bot.send_message(chat_id=mes.from_user.id,
                         text="Учёт статистики ловушек доступен только лучникам.\n\n<em>Для обновления класса "
                              "необходимо скинуть форвард ответа игрокого бота на команду /me</em>", parse_mode='HTML')
        return
    strings = re.findall("Получено: (.+) \\((\\d+)\\)", mes.text)
    trap_info = player.class_info.get("trap_info")
    if trap_info is None:
        trap_info = {}
        player.class_info.update({"trap_info": trap_info})

    for res in strings:
        item_name = res[0]
        item_count = int(res[1])
        item_code = get_item_code_by_name(item_name)
        if item_code is None:
            logging.error("Item_code is None for {}".format(item_name))
            continue
        count = trap_info.get(item_code) or 0
        trap_info.update({item_code: count + item_count})
        if not item_code[0].isdigit():
            try:
                forward_message_date = local_tz.localize(mes.forward_date).astimezone(tz=moscow_tz).replace(tzinfo=None)
            except Exception:
                forward_message_date = datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None)
            trap_info.update({"last_not_resource": item_code, "last_not_resource_date":
                              forward_message_date.strftime("%d/%m/%y %H:%M")})
    player.update_to_database()
    bot.send_message(chat_id=mes.chat_id, text="Дроп из ловушек записан.\nСтатистика: /trap_stats")
    pass
예제 #3
0
def add_report(bot, update, user_data):
    """
    Функция сохранения репорта от игрока
    """
    mes = update.message
    s = mes.text
    player = Player.get_player(mes.from_user.id)
    if player is None:
        return

    try:
        forward_message_date = utc.localize(
            mes.forward_date).astimezone(tz=moscow_tz).replace(tzinfo=None)
    except ValueError:
        try:
            forward_message_date = mes.forward_date
        except AttributeError:
            forward_message_date = local_tz.localize(
                mes.date).astimezone(tz=moscow_tz).replace(tzinfo=None)

    line = re.search(
        "[🍆🍁☘️🌹🐢🦇🖤️]*(.*)\\s⚔:(\\d+)\\(?(.?\\d*)\\)?.*🛡:(\\d+)\\(?(.?\\d*)\\)?.*Lvl: (\\d+)\\s",
        s)
    """ 
    . - замок, (.*)\\s - никнейм в игре - от замка до эмодзи атаки. ⚔:(\\d+) - Парсинг атаки в конкретной битве
    \\(? - Возможно атака подверглась модификациям, тогда сразу после числа атаки будет открывающая скобка. 
    \\(?(.?\\d*)\\)? - Парсинг дополнительной атаки целиком. Группа будет равна ' ', то есть одному пробельному символу,
    если дополнительной атаки нет.
    .*🛡: - всё лишнее до дефа. Далее абсолютно аналогично атаке 🛡:(\\d+)\\(?(.?\\d*)\\)?
    .*Lvl: (\\d+)\\s - лишнее до уровня и парсинг уровня, в комментариях не нуждается
    """
    nickname = line.group(1)
    if nickname != player.nickname:
        bot.send_message(
            chat_id=mes.chat_id,
            text="Это не ваш репорт. В случае ошибок обновите профиль.",
            reply_to_message_id=mes.message_id)
        return
    attack = int(line.group(2))
    additional_attack = int(line.group(3)) if line.group(3) != " " else 0
    defense = int(line.group(4))
    additional_defense = int(line.group(5)) if line.group(5) != " " else 0
    lvl = int(line.group(6))
    exp = re.search("🔥Exp:\\s(-?\\d+)", s)
    exp = int(exp.group(1)) if exp is not None else 0
    gold = re.search("💰Gold:\\s+(-?\\d+)", s)
    gold = int(gold.group(1)) if gold is not None else 0
    stock = re.search("📦Stock:\\s+(-?\\d+)", s)
    stock = int(stock.group(1)) if stock is not None else 0
    battle_id = count_battle_id(mes)
    hp = re.search("❤️Hp: (-?\\d+)", s)
    hp = int(hp.group(1)) if hp is not None else 0
    outplay = re.search("You outplayed (.+) by ⚔️(\\d+)", s)
    outplay_dict = {}
    if outplay is not None:
        outplay_nickname = outplay.group(1)
        outplay_attack = int(outplay.group(2))
        outplay_dict.update({
            "nickname": outplay_nickname,
            "attack": outplay_attack
        })

    if 'Встреча:' in s or ('Твои удары' in s.lower()
                           and 'Атаки врагов' in s.lower()
                           and 'Ластхит' in s.lower()):
        # Репорт с мобов
        earned = re.search("Получено: (.+) \\((\\d+)\\)", s)
        if earned is not None:
            name = earned.group(1)
            count = earned.group(2)
            code = get_item_code_by_name(name)
            if code is None:
                code = name
            drop = player.mobs_info.get("drop")
            if drop is None:
                drop = {}
                player.mobs_info.update({"drop": drop})
            drop.update(
                {forward_message_date.timestamp(): {
                     "code": code,
                     "count": 1
                 }})
            player.update()
        names, lvls, buffs = [], [], []
        for string in mes.text.splitlines():
            parse = re.search("(.+) lvl\\.(\\d+)", string)
            if parse is not None:
                name = parse.group(1)
                lvl = int(parse.group(2))
                names.append(name)
                lvls.append(lvl)
                buffs.append("")
            else:
                parse = re.search("  ╰ (.+)", string)
                if parse is not None:
                    buff = parse.group(1)
                    buffs.pop()
                    buffs.append(buff)
        hit = re.search("Твои удары: (\\d+)", s)
        hit = int(hit.group(1)) if hit is not None else 0
        miss = re.search("Атаки врагов: (\\d+)", s)
        miss = int(miss.group(1)) if miss is not None else 0
        last_hit = re.search("Ластхит: (\\d+)", s)
        last_hit = int(last_hit.group(1)) if last_hit is not None else 0
        request = "select report_id from mob_reports where date_created = %s and player_id = %s"
        cursor.execute(request, (forward_message_date, player.id))
        row = cursor.fetchone()
        if row is not None:
            return
        request = "insert into mob_reports(player_id, date_created, attack, additional_attack, defense, " \
                  "additional_defense, lvl, exp, gold, stock, mob_names, mob_lvls, buffs, hp, hit, miss, last_hit) " \
                  "values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
        cursor.execute(
            request,
            (player.id, forward_message_date, attack, additional_attack,
             defense, additional_defense, lvl, exp, gold, stock, names, lvls,
             buffs, hp, hit, miss, last_hit))
        return

    equip = re.search("Found: (.+) \\(from (.+)\\)", s)
    equip_change = None
    if equip is not None:
        name = equip.group(1)
        found_from = equip.group(2)
        equip_change = {"status": "Found", "name": name, "from": found_from}
    else:
        equip = re.search("Lost: (.+)", s)
        if equip is not None:
            name = equip.group(1)
            equip_change = {"status": "Lost", "name": name}

    request = "select report_id from reports where battle_id = %s and player_id = %s"
    cursor.execute(request, (battle_id, player.id))
    row = cursor.fetchone()
    if row is not None:
        bot.send_message(chat_id=mes.from_user.id,
                         text="Репорт за эту битву уже учтён!")
        return
    request = "insert into reports(player_id, battle_id, attack, additional_attack, defense, additional_defense, lvl, "\
              "exp, gold, stock, equip, outplay) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    cursor.execute(
        request,
        (player.id, battle_id, attack, additional_attack, defense,
         additional_defense, lvl, exp, gold, stock,
         json.dumps(equip_change, ensure_ascii=False) if equip_change
         is not None else None, json.dumps(outplay_dict, ensure_ascii=False)
         if outplay_dict is not None else None))

    player.count_reports()
    reputation = REPORT_REPUTATION_COUNT

    if forward_message_date < datetime.datetime(
            year=2019, month=5, day=29, hour=12):
        reputation = 0

    player.reputation += reputation
    player.update()
    response = "Репорт учтён. Спасибо!\n" \
               "{}".format("Получено {}🔘!".format(reputation) if not user_data.get("rp_off") else "")
    bot.send_message(chat_id=mes.from_user.id,
                     text=response,
                     parse_mode='HTML')
    if exp != 0:
        on_add_report(player, forward_message_date)
    """