コード例 #1
0
def change_update_message(bot, update, user_data):
    user_data.update({"status": "technical_tower", "location_id": 5})
    tower = Location.get_location(5)
    format_values = tower.special_info.get("enter_text_format_values")
    format_values[
        0] = "Последнее обновление: {}.\nДля просмотра возьмите страничку сверху 🗂Архива".format(
            great_format_time(get_current_datetime()))
    tower.special_info.update({"enter_text_format_values": format_values})

    tower.update_location_to_database()
    last_update_id = tower.special_info.get("last_update_id")
    last_update_id += 1
    tower.special_info.update({"last_update_id": last_update_id})
    tower.update_location_to_database()

    request = "insert into bot_updates (text, date_created) VALUES (%s, %s)"
    cursor.execute(request,
                   (update.message.text,
                    datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None)))
    bot.send_message(
        chat_id=update.message.from_user.id,
        text=
        "Обновление успешно опубликовано. Вы спускаетесь, чтобы проверить, что всё выглядит "
        "хорошо.\n\n<em>В случае, если после этого не последует сообщение с обновлением, "
        "измените его</em>",
        parse_mode='HTML')
    send_general_buttons(update.message.from_user.id, user_data, bot=bot)
    bot.send_message(chat_id=MY_CHANNEL_ID,
                     text=update.message.text,
                     parse_mode='HTML')
コード例 #2
0
def get_reward_combo(reward_name: str) -> int:
    reward = rewards.get(reward_name)
    request = "select count(*) from castle_logs where action = %s and date > %s"
    cursor.execute(request,
                   ("reward_{}".format(reward_name), get_current_datetime() -
                    datetime.timedelta(weeks=REWARD_PRICE_RESET_WEEKS)))
    count, *skip = cursor.fetchone()
    return count
コード例 #3
0
def create_reward_log(player, reward_name, cost, reward_text, *args, **kwargs):
    additional_info = {"cost": cost}
    if "disable_global_triggers" in reward_name:
        period = re.search("(hour|day|weeks)", reward_name).group(1)
        period = period_hours.get(period)
        additional_info.update({"chat_id": reward_text, "period": period})
    request = "insert into castle_logs(player_id, action, result, date, additional_info) values (%s, %s, %s, %s, %s)"
    cursor.execute(
        request,
        (player.id, "reward_{}".format(reward_name), 1, get_current_datetime(),
         json.dumps(additional_info, ensure_ascii=False)))
コード例 #4
0
 def create(self):
     request = "insert into shops(link, name, ownerTag, ownerName, ownerCastle, kind, mana, offers, " \
               "castleDiscount, guildDiscount, specialization, qualityCraftLevel, maintenanceEnabled, " \
               "maintenanceCost, last_seen) values (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
     cursor = conn.cursor()
     cursor.execute(request,
                    (self.link, self.name, self.ownerTag, self.ownerName,
                     self.ownerCastle, self.kind, self.mana,
                     self.get_json_offers(), self.castleDiscount,
                     self.guildDiscount, self.get_json_specialization(),
                     self.qualityCraftLevel, self.maintenanceEnabled,
                     self.maintenanceCost, get_current_datetime()))
     cursor.close()
コード例 #5
0
    def update_or_create_shop(cls, shop_dict: dict):
        link = shop_dict.get("link")
        shop = cls.get_shop(link=link)
        new = False
        if shop is None:
            shop = cls(None, *cls.attributes)
            new = True

        for attribute in cls.attributes:
            setattr(shop, attribute, shop_dict.get(attribute, None))
        shop.last_seen = get_current_datetime()

        if new:
            shop.create()
        else:
            shop.update()

        if cls.last_update is None or shop.last_seen > cls.last_update:
            cls.last_update = shop.last_seen
コード例 #6
0
ファイル: api.py プロジェクト: keeper77/Dark-Desire-Order-Bot
def repair(bot, update):
    """
    Показывает список лавок с открытым обслуживанием (команда /repair)
    """
    mes = update.message
    full = "full" in update.message.text
    shops = cwapi.api_info.get("shops")
    if shops is None or not shops:
        bot.send_message(chat_id=mes.chat_id,
                         text="Нет данных о магазинах. Ожидайте обновления.")
        return
    player = Player.get_player(mes.from_user.id)
    player_castle = player.castle if player is not None else '🖤'
    sh = []
    for shop in shops:
        if shop.get("maintenanceEnabled"):
            sh.append(shop)
    sh.sort(key=lambda x: repair_comparator(x, player_castle), reverse=True)

    response = "Выгодные магазины для обслуживания:\n"
    castle_stage = sh[0].get("ownerCastle") if sh else '🖤'
    gold_min = min(
        list(map(lambda shop: shop.get("maintenanceCost", 1000), sh)))
    for shop in sh:
        castle, link, gold, mana, discount, name = shop.get("ownerCastle"), shop.get("link"), shop.get("maintenanceCost"), \
                                             shop.get("mana"), shop.get("castleDiscount"), shop.get("name")
        if not full and gold > gold_min and castle != player_castle:
            continue
        if castle_stage != castle == player_castle:
            castle_stage = player_castle
            response += "\n"
        response += "{} <a href=\"https://t.me/share/url?url={}\">{}</a> 💰{} 💧{} {}" \
                    "\n".format(castle, "/ws_" + link, "/ws_" + link, gold, mana,
                                "🏰: -{}%".format(discount) if discount is not None else "")
    last_updated = cwapi.api_info.get("shops_updated")
    if last_updated:
        updated = (get_current_datetime() - last_updated).total_seconds() // 60
        response += "\nОбновлено {}".format(
            "{} часов назад".format(int(updated // 60)) if updated //
            60 else "{} минут назад".format(int(updated)))
    response += "\n<em>/repair_full - все открытые лавки</em>"
    bot.send_message(chat_id=mes.chat_id, text=response, parse_mode='HTML')
コード例 #7
0
def add_class_from_player(bot, update):
    translate = {
        "рыцарь": "Knight",
        "защитник": "Sentinel",
        "рейнджер": "Ranger",
        "алхимик": "Alchemist",
        "кузнец": "Blacksmith",
        "добытчик": "Collector",
    }
    mes = update.message
    player = Player.get_player(mes.from_user.id)
    if player is None:
        bot.send_message(
            chat_id=mes.from_user.id,
            text="Сначала необходимо зарегистрироваться. Для этого необходимо "
            "прислать ответ @ChatWarsBot на команду /hero")
        return
    forward_message_date = get_forward_message_time(mes)
    if get_current_datetime() - forward_message_date > datetime.timedelta(
            seconds=30):
        bot.send_message(
            chat_id=mes.chat_id,
            text="Этот профиль старше 30 секунд. Пришли актуальный профиль!",
            reply_to_message_id=mes.message_id)
        return
    game_class = re.search(
        "🖤{} (\\w+) Скалы".format(re.escape(player.nickname)), mes.text)
    if game_class is None:
        bot.send_message(chat_id=mes.chat_id,
                         text="Произошла ошибка.",
                         reply_to_message_id=mes.message_id)
        return
    game_class = game_class.group(1)
    if game_class.lower() in translate:
        game_class = translate.get(game_class.lower())
    player.game_class = game_class
    player.update_to_database()
    bot.send_message(
        chat_id=mes.from_user.id,
        text="Информация о классе обновлена, <b>{}</b>! Теперь ты "
        "<b>{}</b>!".format(player.nickname, player.game_class),
        parse_mode='HTML')
コード例 #8
0
def add_alliance_location(bot, update):
    mes = update.message
    player, guild, alliance = get_player_and_guild_and_alliance(
        mes.from_user.id)
    try:
        parse = re.search("simple combination: (\\w+)", mes.text)
        link = parse.group(1)

        parse = re.search(
            "You found hidden (location (.+) lvl.(\\d+)|headquarter (.+))",
            mes.text)
        if parse.group(4) is not None:
            return add_alliance_link(parse.group(4), link)
        name, lvl = parse.group(2), int(parse.group(3))

    except Exception:
        logging.error(traceback.format_exc())
        if filter_is_pm(mes):
            bot.send_message(chat_id=mes.chat_id, text="Произошла ошибка")
        return
    request = "select id from alliance_locations where link = %s and expired is false"
    cursor.execute(request, (link, ))
    row = cursor.fetchone()
    if row is not None:
        return
    request = "select id from alliance_locations where name = %s and lvl = %s and link is null " \
              "and expired is false limit 1"
    cursor.execute(request, (name, lvl))
    row = cursor.fetchone()
    if row is not None:
        location = AllianceLocation.get_location(row[0])
        location.link = link
        location.update()
    else:
        location = AllianceLocation(None, link, name, None, lvl, None, 0,
                                    False, False)
        location.figure_type()
        location.insert_to_database()
    for alli in Alliance.get_active_alliances():
        if alli.hq_chat_id is not None:
            bot.send_message(chat_id=alli.hq_chat_id,
                             parse_mode='HTML',
                             text="Новая локация: <b>{} Lvl.{}</b>\n{}".format(
                                 name, lvl, link))

    text = "Спасибо! Новая локация!"
    if player is not None:
        player.reputation += 250
        player.update()
        text += "\nПолучено: 250🔘"
        request = "insert into castle_logs(player_id, action, result, date, additional_info) values (%s, %s, %s, %s, %s)"
        cursor.execute(request,
                       (mes.from_user.id, "add_alliance_location", 1,
                        get_current_datetime(),
                        json.dumps({"link": link}, ensure_ascii=False)))
    else:
        request = "insert into castle_logs(action, result, date, additional_info) values (%s, %s, %s, %s)"
        cursor.execute(
            request, ("add_alliance_location", 1, get_current_datetime(),
                      json.dumps({
                          "link": link,
                          "player_id": mes.from_user.id
                      },
                                 ensure_ascii=False)))

    bot.send_message(chat_id=mes.chat_id,
                     text=text,
                     reply_to_message_id=mes.message_id)
コード例 #9
0
def hero(bot, update, user_data):
    mes = update.message
    text = mes.text
    castle = re.search("([🍁☘️🖤🐢🦇🌹🍆🎖]+)(.+)", text)
    nickname = castle.group(2)
    castle = castle.group(1)
    if castle != '🖤':
        pass
        # Игрок не из Скалы
        # bot.send_message(chat_id=mes.from_user.id, text="Пользователям не из Скалы запрещена регистрация!")
        # return
    player = Player.get_player(mes.from_user.id, notify_on_error=False)
    if player is not None and player.id == 402027858 and player.castle != '🖤' and castle == '🖤':
        # Рыбак вернулся!
        bot.send_message(
            chat_id=player.id,
            text=
            "Стражи с гулким стуком ударяют копьями о землю. Врата медленно "
            "отворяются, открывая взору такие знакомые, но в то же время изменившиеся улицы.\n"
            "<b>С возвращением домой!</b>",
            parse_mode='HTML')
    if player is None and mes.chat_id != mes.from_user.id:
        # Добавление новых пользователей только в личке у бота
        return
    forward_message_date = get_forward_message_time(mes)
    print(forward_message_date)
    if get_current_datetime() - forward_message_date > datetime.timedelta(seconds=30) and \
            mes.from_user.id not in urned_players:
        bot.send_message(
            chat_id=mes.chat_id,
            text="Этот профиль старше 30 секунд. Пришли актуальный профиль!",
            reply_to_message_id=mes.message_id)
        return
    # Парсинг хиро
    guild_tag = re.search("[🍁☘🖤🐢🦇🌹🍆🎖]\\[(.+)\\]", text)
    if guild_tag:
        guild_tag = guild_tag.group(1)
    lvl = int(re.search("🏅Уровень: (\\d+)", text).group(1))
    attack = int(re.search("⚔Атака: (\\d+)", text).group(1))
    defense = int(re.search("🛡Защита: (\\d+)", text).group(1))
    stamina = re.search("🔋Выносливость: (\\d+)/(\\d+)", text)
    stamina, max_stamina = tuple(map(lambda x: int(x), stamina.groups()))
    pet = re.search("Питомец:\n.(\\s.+\\(\\d+ lvl\\))", text)
    exp = int(re.search("🔥Опыт: (\\d+)", text).group(1))
    last_updated = datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None)
    if pet:
        pet = pet.group(1)
    # Парсинг экипировки
    print("parsing eq")
    player_equipment = {
        "main_hand": None,
        "second_hand": None,
        "head": None,
        "gloves": None,
        "armor": None,
        "boots": None,
        "cloaks": None
    }
    equip_strings = text.partition("🎽Экипировка")[2].splitlines()[1:]
    for string in equip_strings:
        # clear_name = re.search("\\+?\\d?\\s?(.+?)\\s\\+", string)
        clear_name = re.search(
            "(⚡?\\+?\\d*\\s?(.+?))\\s\\+((\\d*)⚔)?\\s*\\+?(\\d*)🛡?", string)
        if clear_name is None:
            # logging.warning("Error while parsing item_string\n{}".format(string))
            continue
        else:
            pass
            # logging.info("successful parsed {},, Got: {}".format(string, clear_name.group(1)))
        full_name = clear_name.group(1)
        eq_attack = int(clear_name.group(4)) if clear_name.group(
            4) is not None and clear_name.group(4) != "" else 0
        eq_defense = int(
            clear_name.group(5)) if clear_name.group(5) != "" else 0
        clear_name = clear_name.group(2)
        eq = get_equipment_by_name(clear_name)
        if eq is None:
            logging.warning(
                "Equipment with name {} is None".format(clear_name))
            continue
        eq.name = full_name
        eq.attack = eq_attack
        eq.defense = eq_defense
        player_equipment.update({eq.place: eq})
    if player is None:
        if mes.from_user.username is None:
            bot.send_message(
                chat_id=mes.chat_id,
                text=
                "Регистрация без имени пользователя невозможна. Пожалуйста, "
                "установите его в настройках аккаунта Telegram")
            return
        player = Player(mes.from_user.id,
                        mes.from_user.username,
                        nickname,
                        guild_tag,
                        None,
                        lvl,
                        attack,
                        defense,
                        stamina,
                        pet,
                        player_equipment,
                        castle=castle,
                        last_updated=last_updated,
                        created=last_updated,
                        exp=exp,
                        max_stamina=max_stamina)
        # Добавляем игрока в бд
        player.insert_into_database()
        player = player.reload_from_database()

        user_data.update({"status": DEFAULT_CASTLE_STATUS, "location_id": 0})
        bot.send_message(
            chat_id=mes.chat_id,
            text=
            "Добро пожаловать в 🖤Скалу, <b>{}</b>!\n\n<a href=\"https://t.me/joinchat/DdKE7kUfsmDVIC2DJymw_A\">Чат центральной площади</a>\n\nДля добавления информации о классе "
            "необходимо прислать ответ @ChatWarsBot на кнопку \"🏅Герой\" (рекомендуется сделать для "
            "получения доступа к некоторых дополнительным фишкам, особенно стражникам).\n\n"
            "<em>Вы всегда можете отключить рп составляющую бота командой </em>/change_rp.<em> "
            "Обратите внимание, что это сделает недоступными некоторые функции "
            "бота.</em>".format(player.nickname),
            parse_mode='HTML')
        if filter_is_pm(mes):
            send_general_buttons(mes.from_user.id, user_data)
        auth(bot, update)

    else:
        # Обновляем существующую информацию
        player.username = mes.from_user.username
        player.nickname = nickname
        player.guild_tag = guild_tag
        player.lvl = lvl
        player.attack = attack
        player.defense = defense
        player.stamina = stamina
        player.max_stamina = max_stamina
        player.pet = pet
        player.equipment = player_equipment
        player.castle = castle
        player.last_updated = last_updated
        player.exp = exp
        player.update()
        bot.send_message(chat_id=mes.chat_id,
                         text="Профиль успешно обновлён, <b>{}</b>!".format(
                             player.nickname),
                         parse_mode='HTML')
        if player.guild is not None:
            guild = Guild.get_guild(player.guild)
            guild.calculate_attack_and_defense()
            guild.sort_players_by_exp()
コード例 #10
0
def check_global_triggers_ignore(chat_id):
    return ignore_global_triggers.get(chat_id, datetime.datetime(1970, 1, 1)) > get_current_datetime() or \
           chat_id in GLOBAL_TRIGGERS_IGNORE
コード例 #11
0
def show_web_page_preview(player, user_data):
    status = user_data.get("status")
    location_id = user_data.get("location_id")
    rp_off = user_data.get("rp_off")
    return status == "central_square" and location_id == 0 and not rp_off and \
        (player.created is None or get_current_datetime() - player.created < datetime.timedelta(days=30))