Exemplo n.º 1
0
 def update(self):
     request = "update alliances set link = %s, name = %s, creator_id = %s, assistants = %s, " \
               "hq_chat_id = %s, active = %s " \
               "where id = %s"
     cursor.execute(request,
                    (self.link, self.name, self.creator_id, self.assistants,
                     self.hq_chat_id, self.active, self.id))
Exemplo n.º 2
0
def count_reputation_sum(bot, update):
    """
    Функция для отлавливания багов и их использования. Команда /count_reputation_sum
    Выводит разницу между полученными "легально" жетонами и текущими жетонами у игроков.
    """
    request = "select action, player_id from castle_logs"
    cursor.execute(request)
    rep = {}
    action_to_rep = {"collect_resources": 3, "construction": 5}
    row = cursor.fetchone()
    while row is not None:
        action, player_id = row
        cur_rep = rep.get(player_id) or 0
        cur_rep += action_to_rep.get(action)
        rep.update({player_id: cur_rep})
        row = cursor.fetchone()
    lst = list(rep.items())
    lst.sort(key=lambda x: Player.get_player(x[0]).reputation - x[1],
             reverse=True)
    response = "Статистика по жетонам:\n"
    for obj in lst:
        id, reputation = obj
        player = Player.get_player(id)
        new_response = "<code>{:<20}</code> 🔘: <code>{:4<}</code>, всего 🔘: <code>{:<4}</code>, <code>{}</code>\n" \
                       "".format(player.username, reputation, player.reputation, player.reputation - reputation)
        if len(response + new_response) > 4000:
            bot.send_message(chat_id=update.message.chat_id,
                             text=response,
                             parse_mode='HTML')
            response = ""
        response += new_response
    bot.send_message(chat_id=update.message.chat_id,
                     text=response,
                     parse_mode='HTML')
Exemplo n.º 3
0
def two_action_timeout(bot, cur_job):
    player_id, pair_player_id = cur_job.context.get("ids")
    player, pair_player = Player.get_player(player_id), Player.get_player(pair_player_id)
    user_data, pair_user_data = dispatcher.user_data.get(player_id), dispatcher.user_data.get(pair_player_id)

    status, quest = user_data.get("status"), user_data.get("quest")
    if status != "two_quest":
        return

    qst = quest_texts[quest]["two_players"][user_data["quest_id"]]
    first_text = qst.get("first_fail")
    second_text = qst.get("second_fail") or first_text

    return_from_quest(player_id, user_data)
    return_from_quest(pair_player_id, pair_user_data)
    player.reputation += GO_NOT_SUCCESS_REPUTATION
    pair_player.reputation += GO_NOT_SUCCESS_REPUTATION
    player.update()
    pair_player.update()
    buttons = get_general_buttons(user_data, player)

    bot.send_message(chat_id=player_id, text=first_text + "\nПолучено {}🔘".format(GO_NOT_SUCCESS_REPUTATION),
                     reply_markup=buttons)
    bot.send_message(chat_id=pair_player_id, text=second_text + "\nПолучено {}🔘".format(GO_NOT_SUCCESS_REPUTATION),
                     reply_markup=buttons)

    now = datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None)
    request = "insert into castle_logs(player_id, action, result, date, additional_info) values (%s, %s, %s, %s, %s)"
    cursor.execute(request, (player.id, quest, 2, now, json.dumps({"result": "two_players_fail",
                                                                   "pair_player_id": pair_player_id})))
    cursor.execute(request, (pair_player_id, quest, 2, now, json.dumps({"result": "two_players_fail",
                                                                        "pair_player_id": player.id})))
Exemplo n.º 4
0
def battle_equip(bot, update):
    mes = update.message
    if mes.from_user.id != SUPER_ADMIN_ID:
        return
    battle_id = re.search("\\d+", mes.text)
    if battle_id is None:
        battle_id = count_battle_id(mes)
    else:
        battle_id = int(battle_id.group(0))
    full = 'full' in mes.text
    request = "select player_id, equip from reports where battle_id = %s and equip is not null " \
              "order by equip ->> 'status'"
    cursor.execute(request, (battle_id, ))
    rows = cursor.fetchall()
    response = "Дроп с битвы {} - {} :\n".format(
        battle_id,
        count_battle_time(battle_id).strftime("%d/%m/%y %H:%M:%S"))
    for row in rows:
        name, found_from = row[1].get("name"), row[1].get("from")
        player = Player.get_player(row[0])
        response += "{}<b>{}</b> {}\n".format(
            "{} ".format((player.castle + player.nickname) if full else ""),
            name,
            "(От {})".format(found_from) if found_from is not None else "")
    bot.send_message(chat_id=mes.chat_id, text=response, parse_mode='HTML')
Exemplo n.º 5
0
def import_triggers(bot, update, args):
    mes = update.message
    if mes.from_user.id != SUPER_ADMIN_ID:
        return
    try:
        file_name = args[0]
        chat_id = int(args[1])
    except (IndexError, TypeError, ValueError, AttributeError):
        bot.send_message(
            chat_id=mes.chat_id,
            text=
            "Неверный синтаксис. Пример:\n/import_triggers triggers.json -123456789"
        )
        return
    triggers_imported = 0
    try:
        with open(file_name, "r") as f:
            j = json.load(f)
            for key, value in list(j.items()):
                if value[0] == "text":
                    request = "insert into triggers(text_in, chat_id, type, data_out, creator, date_created) values " \
                              "(%s, %s, %s, %s, %s, %s)"
                    cursor.execute(
                        request,
                        (key, chat_id, 0, value[1], "Triggers importer",
                         datetime.datetime.now(tz=moscow_tz).replace(
                             tzinfo=None)))
                    triggers_imported += 1
    except FileNotFoundError:
        bot.send_message(chat_id=mes.chat_id, text="Файл не найден.")
        return
    fill_triggers_lists()
    bot.send_message(chat_id=mes.chat_id,
                     text="Импортировано {} триггеров. "
                     "Триггеры перекешированы".format(triggers_imported))
Exemplo n.º 6
0
def replace_trigger(bot, update):
    mes = update.message
    if filter_is_pm(mes):
        return
    if mes.from_user.id not in get_admin_ids(bot=bot, chat_id=mes.chat_id):
        bot.send_message(chat_id=mes.chat_id,
                         text="Доступ только у админов.",
                         reply_to_message_id=mes.message_id)
        return
    text = mes.text.partition(" ")[2].lower()
    list_triggers = triggers_in.get(mes.chat_id)
    if list_triggers is None or text not in list_triggers:
        bot.send_message(chat_id=mes.chat_id,
                         text="Триггер не найден",
                         reply_to_message_id=mes.message_id)
        return
    request = "update triggers set type = %s, data_out = %s, creator = %s, date_created = %s where chat_id = %s and " \
              "text_in = %s"
    trigger_type, data = get_message_type_and_data(mes.reply_to_message)
    cursor.execute(request,
                   (trigger_type, data, mes.from_user.username
                    or mes.from_user.id, datetime.datetime.now(
                        tz=moscow_tz).replace(tzinfo=None), mes.chat_id, text))
    bot.send_message(chat_id=mes.chat_id,
                     text="Триггер успешно заменён!",
                     reply_to_message_id=mes.message_id)
    return
Exemplo n.º 7
0
def info_trigger(bot, update):
    mes = update.message
    if filter_is_pm(mes):
        return
    if mes.from_user.id not in get_admin_ids(bot=bot, chat_id=mes.chat_id):
        bot.send_message(chat_id=mes.chat_id,
                         text="Доступ только у админов.",
                         reply_to_message_id=mes.message_id)
        return
    text = mes.text.partition(" ")[2].lower()
    list_triggers = triggers_in.get(mes.chat_id)
    chat_id = mes.chat_id
    if list_triggers is None:
        list_triggers = []
        triggers_in.update({mes.chat_id: list_triggers})
    if text not in list_triggers:
        if text not in global_triggers_in:
            bot.send_message(chat_id=mes.chat_id,
                             text="Триггер не найден",
                             reply_to_message_id=mes.message_id)
            return
        chat_id = 0
    request = "select creator, date_created from triggers where text_in = %s and chat_id = %s"
    cursor.execute(request, (text, chat_id))
    row = cursor.fetchone()
    response = "<code>{}</code> — создал <code>{}</code> {}".format(
        text, row[0], row[1].strftime("%d/%m/%y %H:%M:%S"))
    bot.send_message(chat_id=mes.chat_id,
                     text=response,
                     parse_mode='HTML',
                     reply_to_message_id=mes.message_id)
Exemplo n.º 8
0
 def get_alliance_by_link(link: str) -> 'Alliance':
     request = "select id from alliances where lower(link) = lower(%s) limit 1"
     cursor.execute(request, (link, ))
     row = cursor.fetchone()
     if row is None:
         return None
     return Alliance.get_alliance(row[0])
Exemplo n.º 9
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')
Exemplo n.º 10
0
def finish_vote(bot, update, user_data):
    mes = update.message
    if not check_access(mes.from_user.id):
        return
    name, variants, text = user_data.get("vote_name"), user_data.get("vote_variants"), user_data.get("vote_text")
    if not all([name, variants, text]):
        bot.send_message(chat_id=mes.chat_id, text="Все этапы должны быть заполнены перед запуском голосования")
    choices = {}
    for i in range(len(variants)):
        choices.update({i: []})
    choices = json.dumps(choices)
    request = "insert into votes(name, text, variants, choices) VALUES (%s, %s, %s, %s) returning id"
    cursor.execute(request, (name, text, variants, choices))
    row = cursor.fetchone()
    if row is None:
        bot.send_message(chat_id=mes.chat_id, text="Произошла ошибка. Возможно, голосование всё же создалось, "
                                                   "проверьте: /vote")
        return
    bot.send_message(chat_id=mes.chat_id, text="Голосование <b>{}</b> успешно создано.\n"
                                               "Просмотреть голосование: /view_vote_{}".format(name, row[0]),
                     parse_mode='HTML')
    user_data.pop("vote_name")
    user_data.pop("vote_variants")
    user_data.pop("vote_text")
    user_data.pop("status")
Exemplo n.º 11
0
def resource_return(bot, job):
    cursor = conn.cursor()
    if job.context[1].get("status") not in ["sawmill", "quarry"]:
        logging.warning(
            "Status not in  [\"sawmill\", \"quarry\"], status = {}".format(
                job.context[1].get("status")))
        return
    statuses_to_res = {"sawmill": "wood", "quarry": "stone"}
    res = statuses_to_res.get(job.context[1].get("status"))
    count = 1
    throne = Location.get_location(2)
    throne.treasury.change_resource(res, count)
    player = Player.get_player(job.context[0])
    player.reputation += 3
    player.update_to_database()
    job.context[1].update({"status": "castle_gates"})
    buttons = get_general_buttons(job.context[1], player)
    if job.context[0] in construction_jobs:
        try:
            construction_jobs.pop(job.context[0])
        except Exception:
            logging.error(traceback.format_exc())
    request = "insert into castle_logs(player_id, action, result, additional_info, date) values (%s, %s, %s, %s, %s)"
    cursor.execute(
        request,
        (player.id, "collect_resources", 1,
         json.dumps({
             "resource": res,
             "count": count
         }), datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None)))
    bot.send_message(chat_id=job.context[0],
                     text="Вы успешно добыли {}. Казна обновлена. Получено 3 🔘"
                     "".format("дерево" if res == "wood" else "камень"),
                     reply_markup=buttons)
    on_resource_return(player, res)
Exemplo n.º 12
0
def get_mobs_info_by_link(link):
    cursor = conn.cursor()
    request = "select mob_names, mob_lvls, date_created, helpers, buffs, minutes, created_player from mobs where link = %s"
    cursor.execute(request, (link,))
    row = cursor.fetchone()
    cursor.close()
    return row
Exemplo n.º 13
0
def update_daily_quests(bot, job):
    cursor = conn.cursor()
    request = "select id from players"
    cursor.execute(request)
    row = cursor.fetchone()
    while row is not None:
        player = Player.get_player(row[0])
        if player is None:
            continue
        daily_quests: [Quest] = player.quests_info.get("daily_quests")
        if daily_quests is None:
            daily_quests = []
            player.quests_info.update({"daily_quests": daily_quests})
        else:
            daily_quests.clear()
        forbidden_list = []
        for i in range(3):
            quest = copy.deepcopy(random.choice(list(quests.values())))
            limit = 0
            while (quest.id in forbidden_list
                   or quest.skip_selection) and limit < 5:
                quest = copy.deepcopy(random.choice(list(quests.values())))
                limit += 1
            quest.start(player)
            if quest.daily_unique:
                forbidden_list.append(quest.id)
            daily_quests.append(quest)
        player.update_to_database()
        row = cursor.fetchone()
    time.sleep(1)
    plan_update_daily_quests()
Exemplo n.º 14
0
def view_vote(bot, update):
    mes = update.message
    if not check_access(mes.from_user.id):
        return
    vote_id = re.search("_(\\d+)", mes.text)
    if vote_id is None:
        bot.send_message(chat_id=mes.chat_id, text="Неверный синтаксис.")
        return
    vote_id = int(vote_id.group(1))
    request = "select name, text, variants, started, duration, classes from votes where id = %s"
    cursor.execute(request, (vote_id,))
    row = cursor.fetchone()
    if row is None:
        bot.send_message(chat_id=mes.chat_id, text="Голосование не найдено.")
        return
    response = "Голосование <b>{}</b>\n".format(row[0])
    response += row[1] + "\n\n"
    response += "Начало: <code>{}</code>\n".format(row[3].strftime("%d/%m/%y %H:%M:%S") if row[3] is not None else
                                                  "Не началось.")
    response += "Длительность: <code>{}</code>\n".format(row[4] if row[4] is not None else
                                                        "Не задано.")
    cl_text = ""
    if all(row[5]) or not row[5]:
        cl_text = "ВСЕ"
    else:
        for i, b in enumerate(row[5]):
            cl_text += classes_list[i] if b else ""
    response += "Классы: <code>{}</code>\n".format(cl_text)
    if row[3] is None:
        response += "Изменить длительность: /change_vote_duration_{}\n".format(vote_id)
        response += "Начать голосование: /start_vote_{}\n".format(vote_id)
        response += "\nИзменить классы для голосований: /set_vote_classes_{} [Классы, которые ПРИНИМАЮТ участие " \
                    "в голосовании]\n\n<em>Классы ТОЛЬКО как в списке: {}</em>".format(vote_id, classes_list)
    print(response)
    bot.send_message(chat_id=mes.chat_id, text=response, parse_mode='HTML')
Exemplo n.º 15
0
def king_cabinet_construction(bot, update):
    request = "select location_id from locations where state is false and building_process = -1"
    cursor.execute(request)
    row = cursor.fetchone()
    response = "Здания, которые можно начать строить:\n"
    while row is not None:
        location = Location.get_location(row[0])
        if location is None:
            row = cursor.fetchone()
            continue
        response += "<b>{}</b>\nСтоимость: 🌲: <code>{}</code>, ⛰: <code>{}</code>\nНачать строительство: " \
                    "/begin_construction_{}\n".format(location.name, location.need_res_to_construct.get("wood") or 0,
                                                      location.need_res_to_construct.get("stone") or 0, location.id)
        row = cursor.fetchone()
    response += "\n----------------------\nСтройка в процессе:\n"
    request = "select location_id from locations where state is false and building_process >= 0"
    cursor.execute(request)
    row = cursor.fetchone()
    while row is not None:
        location = Location.get_location(row[0])
        if location is None:
            row = cursor.fetchone()
            continue
        response += "<b>{}</b>\nПрогресс: <code>{}</code> из <code>{}</code>\n" \
                    "\n".format(location.name, location.building_process, location.need_clicks_to_construct)
        row = cursor.fetchone()
    treasury = Location.get_location(6)
    response += "\n----------------------\nСостояние казны: 🌲Дерево: <b>{}</b>, " \
                "⛰Камень: <b>{}</b>".format(treasury.wood, treasury.stone)
    bot.send_message(chat_id=update.message.chat_id,
                     text=response,
                     parse_mode='HTML')
Exemplo n.º 16
0
 def insert_to_database(self):
     request = "insert into alliance_locations(link, name, type, lvl, owner_id, can_expired, expired) VALUES " \
               "(%s, %s, %s, %s, %s, %s, %s) returning id"
     cursor.execute(request,
                    (self.link, self.name, self.type, self.lvl,
                     self.owner_id, self.can_expired, self.expired))
     self.id = cursor.fetchone()[0]
Exemplo n.º 17
0
def remove_trigger(bot, update):
    mes = update.message
    if filter_is_pm(mes):
        return
    if mes.from_user.id not in get_admin_ids(bot=bot, chat_id=mes.chat_id):
        bot.send_message(chat_id=mes.chat_id,
                         text="Доступ только у админов.",
                         reply_to_message_id=mes.message_id)
        return
    text = mes.text.partition(" ")[2].lower()
    chat_id = mes.chat_id
    trigger_list = triggers_in.get(mes.chat_id)
    if trigger_list is None or text not in trigger_list:
        chat_id = 0
        if text in global_triggers_in:
            if not check_access(mes.from_user.id):
                bot.send_message(
                    chat_id=mes.chat_id,
                    text="Недостаточно прав для удаления глобального триггера",
                    reply_to_message_id=mes.message_id)
                return
        else:
            bot.send_message(chat_id=mes.chat_id,
                             text="Триггер не найден",
                             reply_to_message_id=mes.message_id)
            return
        trigger_list = global_triggers_in
    trigger_list.remove(text)
    request = "delete from triggers where text_in = %s and chat_id = %s"
    cursor.execute(request, (text, chat_id))
    bot.send_message(chat_id=mes.chat_id,
                     text="Триггер успешно удалён!",
                     reply_to_message_id=mes.message_id)
Exemplo n.º 18
0
def mob_help(bot, update):
    data = update.callback_query.data
    mes = update.callback_query.message
    link = re.search("mob_partify_(.+)", data)
    if link is None:
        bot.send_message(chat_id=update.callback_query.from_user.id, text="Произошла ошибка.")
        return
    link = link.group(1)
    try:
        names, lvls, forward_message_date, helpers, buffs, minutes, player_id = get_mobs_info_by_link(link)
    except (ValueError, TypeError):
        bot.send_message(chat_id=update.callback_query.from_user.id, text="Событие не найдено")
        return
    if update.callback_query.from_user.username in helpers:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text="Ты уже помог!", show_alert=True)
        return
    if len(helpers) >= 5:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text="Уже собралось достаточно помощников!",
                                show_alert=True)
    else:
        helpers.append(update.callback_query.from_user.username)
    minutes = AMBUSH_MINUTES if 'засада' in mes.text else USUAL_MINUTES
    response, buttons, avg_lvl, remailing_time = get_mobs_text_and_buttons(mes.chat_id, link, names, lvls, helpers,
                                                                           forward_message_date, buffs, minutes,
                                                                           player_id)

    try:
        bot.editMessageText(chat_id=mes.chat_id, message_id=mes.message_id, text=response,
                            reply_markup=buttons, parse_mode='HTML')
    except Exception:
        logging.error(traceback.format_exc())
    bot.answerCallbackQuery(callback_query_id=update.callback_query.id, text="Успешно добавлено")
    request = "update mobs set helpers = %s where link = %s"
    cursor.execute(request, (helpers, link))
Exemplo n.º 19
0
def fill_union_chats():
    request = "select name, chat_id from trade_unions where chat_id is not null"
    cursor.execute(request)
    row = cursor.fetchone()
    union_chats.clear()
    while row is not None:
        union_chats.update({row[0]: row[1]})
        row = cursor.fetchone()
Exemplo n.º 20
0
def fill_allowed_list():
    request = "select id from players"
    cursor.execute(request)
    row = cursor.fetchone()
    allowed_list.clear()
    while row is not None:
        allowed_list.append(row[0])
        row = cursor.fetchone()
Exemplo n.º 21
0
 def update(self):
     request = "update alliance_locations set link = %s, name = %s, type = %s, lvl = %s, owner_id = %s, " \
               "turns_owned = %s, can_expired = %s, expired = %s " \
               "where id = %s"
     cursor.execute(
         request,
         (self.link, self.name, self.type, self.lvl, self.owner_id,
          self.turns_owned, self.can_expired, self.expired, self.id))
Exemplo n.º 22
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
Exemplo n.º 23
0
 def get_location_by_link(link: str) -> 'AllianceLocation':
     if link is None:
         return None
     request = "select id from alliance_locations where lower(link) = lower(%s) and expired is false limit 1"
     cursor.execute(request, (link, ))
     row = cursor.fetchone()
     if row is None:
         return None
     return AllianceLocation.get_location(row[0])
Exemplo n.º 24
0
 def get_or_create_alliance_by_name(name: str) -> 'Alliance':
     request = "select id from alliances where lower(name) = lower(%s)"
     cursor.execute(request, (name, ))
     row = cursor.fetchone()
     if row is None:
         alliance = Alliance(None, None, name, None, None, None)
         alliance.insert_to_database()
         return alliance
     return Alliance.get_alliance(row[0])
Exemplo n.º 25
0
 def get_location(location_id: int) -> 'AllianceLocation':
     request = "select link, name, type, lvl, owner_id, turns_owned, can_expired, expired from alliance_locations where id = %s " \
               "limit 1"
     cursor.execute(request, (location_id, ))
     row = cursor.fetchone()
     if row is None:
         return None
     link, name, location_type, lvl, owner_id, turns_owned, can_expired, expired = row
     return AllianceLocation(location_id, link, name, location_type, lvl,
                             owner_id, turns_owned, can_expired, expired)
Exemplo n.º 26
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)))
Exemplo n.º 27
0
def fight_club(bot, update):
    mes = update.message
    link = re.search("/fight_(.*)$", mes.text)
    if link is None:
        bot.send_message(chat_id=mes.chat_id, text="Ошибка.")
        return
    link = link.group(1)
    player = Player.get_player(mes.from_user.id)
    try:
        forward_message_date = utc.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)
    request = "select mob_lvls, helpers from mobs where link = %s"
    cursor.execute(request, (link,))
    row = cursor.fetchone()
    helpers = []
    lvl = player.lvl
    if row is not None:
        lvls, helpers = row
        lvl = lvls[0]
    response = get_fight_club_txt(link, lvl, helpers, forward_message_date)
    buttons = [[InlineKeyboardButton(text="⚔ {}-{}🏅".format(int(lvl - 5), int(lvl + 10)),
                                     url=u"https://t.me/share/url?url=/fight_{}".format(link)),
                InlineKeyboardButton(text="🤝Помогаю!", callback_data="fight_club_partify_{}".format(link))]]
    guild = Guild.get_guild(chat_id=mes.chat_id)
    if guild is not None:
        ping = []
        for player_id in guild.members:
            cur_player = Player.get_player(player_id)
            if cur_player is None:
                continue
            if cur_player.settings.get("pretend") and cur_player.lvl in range(lvl - 5, lvl + 11) and \
                    player.username not in ping:
                ping.append(player.username)
            if len(ping) >= 4:
                text = "Подпольный бой!\n"
                for username in ping:
                    text += "@{} ".format(username)
                bot.send_message(chat_id=mes.chat_id, text=text)
                ping.clear()
        if ping:
            text = "Подпольный бой!\n"
            for username in ping:
                text += "@{} ".format(username)
            bot.send_message(chat_id=mes.chat_id, text=text)
    if guild is not None:
        response += "\n\n<em>Подписаться на уведомления о клубах в чате ги:</em> /pretend"
    bot.send_message(chat_id=mes.chat_id, text=response, reply_markup=InlineKeyboardMarkup(buttons), parse_mode='HTML')
    request = "insert into mobs(link, mob_names, mob_lvls, date_created, created_player) values (" \
              "%s, %s, %s, %s, %s)"
    try:
        cursor.execute(request, (link, ["Fight Club"], [lvl], forward_message_date, mes.from_user.id))
    except psycopg2.IntegrityError:
        pass
Exemplo n.º 28
0
 def get_alliance(alliance_id: int) -> 'Alliance':
     if alliance_id is None:
         return None
     request = "select link, name, creator_id, assistants, hq_chat_id from alliances where id = %s " \
               "limit 1"
     cursor.execute(request, (alliance_id, ))
     row = cursor.fetchone()
     if row is None:
         return None
     link, name, creator_id, assistants, hq_chat_id = row
     return Alliance(alliance_id, link, name, creator_id, assistants,
                     hq_chat_id)
Exemplo n.º 29
0
def rangers_notify_start(bot, update):
    cursor = conn.cursor()
    time_to_battle = get_time_remaining_to_battle()
    print("time_to_battle", time_to_battle)
    try:
        callback_chat_id = update.message.chat_id
    except AttributeError:
        try:
            callback_chat_id = int(update)
        except TypeError:
            return
    count = 0
    request = "select id from players where class_skill_lvl is not NULL"
    cursor.execute(request)
    row = cursor.fetchone()
    while row is not None:
        player = Player.get_player(row[0])
        if player is None:
            row = cursor.fetchone()
            continue
        if player.settings is not None and player.settings.get(
                "rangers_notify") is False:
            row = cursor.fetchone()
            continue
        guild = Guild.get_guild(guild_id=player.guild)
        if guild is None:
            row = cursor.fetchone()
            continue
        telegram_username = player.username
        username = player.nickname
        class_skill_lvl = player.class_skill_lvl
        context = [telegram_username, username, guild.chat_id]
        print(class_skill_lvl)
        time_to_aim_mins = ranger_aiming_minutes[class_skill_lvl] if \
            class_skill_lvl < len(ranger_aiming_minutes) else 40

        time_to_aim = datetime.timedelta(minutes=time_to_aim_mins)
        print("time_to_aim", time_to_aim)
        time_to_notify = time_to_battle - time_to_aim - datetime.timedelta(
            minutes=1)
        print(time_to_notify)
        # time_to_notify = datetime.timedelta(minutes=1)    # TEST
        if time_to_notify >= datetime.timedelta(minutes=0):
            job.run_once(ranger_notify, time_to_notify, context=context)

        row = cursor.fetchone()
        count += 1
    cursor.close()
    bot.send_message(
        chat_id=callback_chat_id,
        text="Запланировано оповещение <b>{0}</b> бедных лучников".format(
            count),
        parse_mode='HTML')
Exemplo n.º 30
0
def construction_return(bot, job):
    cursor = conn.cursor()
    player_id = job.context[0]
    user_data = job.context[1]
    if user_data.get("status") not in ["construction"]:
        return
    location_id = user_data.get("construction_id")
    if location_id is None:
        bot.send_message(chat_id=player_id, text="Ошибка поиска локации.")
        return
    location = Location.get_location(location_id)
    if location is None:
        bot.send_message(chat_id=player_id, text="Ошибка поиска локации.")
        return
    print(location.name, location.state, location.building_process)
    if location.state is True or location.building_process < 0:
        bot.send_message(
            chat_id=player_id,
            text=
            "Локация уже построена или стройка не начиналась. Возможно, локацию "
            "построили в то время, пока вы добирались до стройки.")
        return
    location.building_process += 3
    player = Player.get_player(job.context[0])
    if location.building_process >= location.need_clicks_to_construct:
        location.state = True
        bot.send_message(
            chat_id=player_id,
            text="Локация успешно построена! Вы положили последний камень!")
        player.reputation += 50 - CONSTRUCTION_REPUTATION
    player.reputation += CONSTRUCTION_REPUTATION
    player.update_to_database()
    location.update_location_to_database()
    user_data.update({"status": "central_square"})
    if "construction_id" in user_data:
        user_data.pop("construction_id")
    if job.context[0] in construction_jobs:
        try:
            construction_jobs.pop(job.context[0])
        except Exception:
            logging.error(traceback.format_exc())
    buttons = get_general_buttons(user_data, player)
    request = "insert into castle_logs(player_id, action, result, additional_info, date) values (%s, %s, %s, %s, %s)"
    cursor.execute(request,
                   (player.id, "construction", 1,
                    json.dumps({"location_id": location_id}),
                    datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None)))
    bot.send_message(
        chat_id=job.context[0],
        text="Вы вернулись со стройки. Получено <code>{}</code> 🔘".format(
            CONSTRUCTION_REPUTATION),
        reply_markup=buttons,
        parse_mode='HTML')