Esempio n. 1
0
def g_info(bot, update):
    mes = update.message
    request = "SELECT username, user_lvl, user_attack, user_defense FROM users WHERE guild = %s ORDER BY user_lvl DESC"
    cursor.execute(request, (mes.text.split(' ')[1],))
    row = cursor.fetchone()

    response = "Статистика по гильдии <b>" + mes.text.split(' ')[1] + "</b>:\n"

    total_attack = 0
    total_defense = 0
    max_lvl = 0
    max_lvl_user = ""

    count = 1
    while row:
        response = response + '\n' + "{0}: <b>".format(count) + row[0] + "</b>" + "\n🏅" + str(row[1]) + " ⚔" + str(row[2]) + " 🛡" + str(row[3]) + '\n'
        total_attack += row[2]
        total_defense += row[3]
        if row[1] > max_lvl:
            max_lvl = row[1]
            max_lvl_user = row[0]

        row = cursor.fetchone()
        count += 1
    count -= 1
    response += "\n\n" + "Всего игроков: {0}\nВсего атаки: ⚔".format(count) + str(total_attack) + ", всего защиты: 🛡" + str(total_defense)
    response += "\n" + "Максимальный уровень у <b>" + max_lvl_user + "</b>, 🏅" + str(max_lvl)
    bot.send_message(chat_id=update.message.chat_id, text=response, parse_mode='HTML')
Esempio n. 2
0
def recashe_guilds():
    logging.info("Recaching guilds...")
    request = "select guild_id, castle, tag, name, lvl, glory, num_players from guilds"
    cursor.execute(request)
    guilds.clear()
    row = cursor.fetchone()
    while row:
        current = Guild(row[0], row[1], row[2], row[3], row[4], row[5], row[6])
        guilds.update({current.tag: current})
        row = cursor.fetchone()
    logging.info("Guilds recashed")
Esempio n. 3
0
def list_guilds(bot, update, user_data):
    response = "Отслеживаемые гильдии:\n"
    request = "select guild_id, castle, tag, name, lvl, glory, num_players from guilds"
    cursor.execute(request)
    row = cursor.fetchone()
    while row:
        response += "{0}<b>{1}</b> 🏅: {2} 🎖: {3}\nУдалить гильдию: /del_guild_{4}\n\n".format(
            row[1], row[2], row[4], row[5], row[0])
        row = cursor.fetchone()
    bot.send_message(chat_id=update.message.chat_id,
                     text=response,
                     parse_mode='HTML')
Esempio n. 4
0
def notify_guild_attack(bot, update):
    print(get_time_remaining_to_battle())
    mes = update.message
    remaining_time = get_time_remaining_to_battle()
    if mes.forward_date - datetime.datetime.now() > datetime.timedelta(minutes=2):
        return 0
    if remaining_time > datetime.timedelta(minutes=30):
        return 0
    if mes.from_user.id not in get_admin_ids(bot, chat_id=mes.chat_id) and mes.from_user.id not in admin_ids:
        bot.send_message(chat_id=mes.chat_id, text="Доступ только у админов", parse_mode='HTML',
                         reply_to_message_id=mes.message_id)
        return
    ready_to_battle = mes.text.count("[⚔]") + mes.text.count("[🛡]")
    sleeping = mes.text.count("[🛌]")
    print("sleeping =", sleeping)
    response = "<b>{0}</b>\nГотово к битве: <b>{1}</b>\nНе готово к битве, но занято <b>{2}</b>\n" \
               "Спит: <b>{3}</b>\n\nВремя до битвы: {4}\n".format(mes.text.splitlines()[0], ready_to_battle,
                                                                mes.text.count("\n") - ready_to_battle - sleeping,
                                                                sleeping, ":".join(str(remaining_time).partition(".")[0].split(":")[0:3]))
    tag = guilds_name_to_tag.get(mes.text.splitlines()[0][1:])
    if tag is not None:
        do_not_ready = []
        sleeping = []
        for string in mes.text.splitlines()[1:]:
            if not ("[⚔]" in string or "[🛡]" in string):
                nickname = string.partition("]")[2][1:]
                do_not_ready.append(nickname)
                if "[🛌]" in string:
                    sleeping.append(nickname)

        request = "select username, telegram_username from users where guild = %s"
        cursor.execute(request, (tag,))
        row = cursor.fetchone()
        in_dict_do_not_ready = []
        in_dict_sleeping = []
        ping_dict = {"do not ready" : in_dict_do_not_ready, "sleeping" : in_dict_sleeping}
        while row:
            db_nickname = row[0].partition("]")[2]
            if db_nickname in do_not_ready:
                in_dict_do_not_ready.append(row[1])
                if db_nickname in sleeping:
                    in_dict_sleeping.append(row[1])

            row = cursor.fetchone()
        ping_by_chat_id.update({mes.chat_id : ping_dict})
        response += "Пингануть тех, кто спит: /notify_guild_sleeping\n" \
                    "Пингануть всех, кто не готов: /notify_guild_not_ready"
    bot.send_message(chat_id = mes.chat_id, text = response, parse_mode = 'HTML')
Esempio n. 5
0
    def update_from_database(self):

        request = "select chat_name, message_count, text_messages_count, stickers_messages_count, " \
                  "audio_messages_count, photo_messages_count, video_messages_count, document_messages_count, " \
                  "voice__messages_count from stats where chat_id = %s"
        cursor.execute(request, (self.chat_id,))
        row = cursor.fetchone()
        if row is None:
            request = "insert into stats(chat_id, chat_name, message_count, text_messages_count, stickers_messages_count, " \
                  "audio_messages_count, photo_messages_count, video_messages_count, document_messages_count, " \
                  "voice__messages_count) values(%s, %s, %s,%s, %s, %s,%s, %s, %s, %s)"
            cursor.execute(request, (self.chat_id, self.chat_name, self.message_count, self.text_messages_count,
                                      self.stickers_messages_count, self.audio_messages_count, self.photo_messages_count,
                                      self.video_messages_count, self.document_messages_count, self.voice_messages_count))
            conn.commit()
            return CREATE_ROW_RETURN_CODE

        self.chat_name = row[0]
        self.message_count = row[1]
        self.text_messages_count = row[2]
        self.stickers_messages_count = row[3]
        self.audio_messages_count = row[4]
        self.photo_messages_count = row[5]
        self.video_messages_count = row[6]
        self.document_messages_count = row[7]
        self.voice_messages_count = row[8]
        return
Esempio n. 6
0
def report_handling(bot, update):
    mes = update.message
    nickname = mes.text.partition("⚔")[0][:-1]
    inspired_by = mes.text.partition("Тебя вдохновил ")[2].splitlines()[0]
    message_datetime = local_tz.localize(update.message.forward_date).astimezone(tz=moscow_tz).replace(tzinfo = None)
    time = message_datetime - message_datetime.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
    if time < datetime.timedelta(hours=1):  #   Дневная битва прошлого дня
        message_datetime -= datetime.timedelta(days=1)
        battle_time = message_datetime.replace(hour = 17, minute = 0, second = 0, microsecond = 0)
    else:
        battle_time = datetime.datetime.combine(message_datetime.date(), datetime.time(hour=1))
        while message_datetime - battle_time >= datetime.timedelta(hours=8):
            battle_time += datetime.timedelta(hours = 8)
    request = "select nickname from inspirations where nickname = %s and battle_time = %s"
    cursor.execute(request, (nickname, battle_time))
    row = cursor.fetchone()
    if row is not None:
        bot.send_message(chat_id=update.message.chat_id, text="Данный репорт уже есть на канале!")
        return
    tag = re.search("\\[(\\S+)\\]", nickname)
    if tag:
        tag = tag.group(1)
        inspired_by = "[🤷🏿‍♀️/{}]{}".format(tag, inspired_by)
    response = "⚡️<b>{0}</b> was inspired by <b>{1}</b>\n\n🕒 Battle on {2}".format(nickname, inspired_by, battle_time.strftime("%D %H:%M"))
    bot.send_message(chat_id = POST_CHANNEL_ID, text = response, parse_mode = 'HTML')
    bot.send_message(chat_id = mes.chat_id, text = "Спасибо! Отправлено на канал\nМожешь кидать сюда следующие репорты")
    castle = nickname[0]
    request = "insert into inspirations(castle, nickname, inspured_by_nickname, battle_time) values (%s, %s, %s, %s)"
    cursor.execute(request, (castle, nickname, inspired_by, battle_time))
Esempio n. 7
0
def get_resource_by_rarity(rarity):
    request = "select item_id, item_name, item_type from items where item_rarity = %s order by random() limit 1"
    cursor.execute(request, (rarity, ))
    row = cursor.fetchone()
    if row is None:
        return None
    return Resource(row[0], row[1], row[2], rarity)
Esempio n. 8
0
 def update_from_database(self):
     request = "select item_type, item_name from items where item_id = %s"
     cursor.execute(request, (self.id, ))
     row = cursor.fetchone()
     self.type = row[0]
     self.name = row[1]
     return 0
Esempio n. 9
0
 def update_from_database(self):
     request = "SELECT type, name, endurance, power, armor, charge, speed FROM equipment WHERE id = %s"
     cursor.execute(request, (self.id, ))
     row = cursor.fetchone()
     if row is None:
         return None
     self.type = "e{0}".format(row[0])
     if row[0] == 'h':
         self.place = 'head'
     elif row[0] == 'b':
         self.place = 'body'
     elif row[0] == 's':
         self.place = 'shoulders'
     elif row[0] == 'l':
         self.place = 'left_arm'
     elif row[0] == 'r':
         self.place = 'right_arm'
     elif row[0] == 'z':
         self.place = 'legs'
     elif row[0] == 'f':
         self.place = 'feet'
     elif row[0] == 'm':
         self.place = 'mount'
     self.name = row[1]
     self.stats.update({'endurance': row[2]})
     self.stats.update({'power': row[3]})
     self.stats.update({'armor': row[4]})
     self.stats.update({'charge': row[5]})
     self.stats.update({'speed': row[6]})
     return 0
Esempio n. 10
0
 def update_from_database(self):
     request = "select user_id, user_castle, telegram_username, username, guild, user_lvl, user_attack, " \
               "user_defense, user_class, last_update, birthday, dspam_user, class_skill_lvl from users " \
               "where telegram_id = %s"
     cursor.execute(request, (self.telegram_id, ))
     row = cursor.fetchone()
     if row is None:
         return 1
     self.user_id, self.castle, self.telegram_username, self.username, self.guild, self.lvl, self.attack, \
         self.defense, self.game_class, self.last_update, self.birthday, self.dspam_user, self.class_skill_lvl = row
     return 0
Esempio n. 11
0
def group_invite(bot, update, user_data):
    mes = update.message
    group = user_data.get("battle_group")
    if group is None:
        group = BattleGroup(mes.from_user.id)
        user_data.update({"battle_group": group})
    elif group.creator != mes.from_user.id:
        bot.send_message(
            chat_id=mes.from_user.id,
            text=
            "Вы не являетесь создателем группы и не можете приглашать в неё новых игроков"
        )
        return
    id = mes.text.partition(" ")[2]
    if not id.isdigit():
        request = "select id from players where nickname = %s"
        cursor.execute(request, (id, ))
        row = cursor.fetchone()
        if row is None:
            bot.send_message(
                chat_id=mes.from_user.id,
                text="Игрок не найден. Проверьте правильность ввода.")
            return
        id = row[0]
    creator = get_player(mes.from_user.id)
    invited_player = get_player(id, notify_not_found=False)
    if invited_player is None:
        bot.send_message(chat_id=mes.from_user.id,
                         text="Игрок не найден. Проверьте правильность ввода.")
        return
    if dispatcher.user_data.get(id).get("battle_group") is not None:
        bot.send_message(chat_id=mes.from_user.id,
                         text="Данный игрок уже находится в группе.")
        return
    group.invitations.append(id)
    buttons = [
        InlineKeyboardButton("Да",
                             callback_data="bgiy {0}".format(
                                 mes.from_user.id)),
        InlineKeyboardButton("Нет",
                             callback_data="bgin {0}".format(mes.from_user.id))
    ]
    reply_markup = InlineKeyboardMarkup(build_menu(buttons, 2))
    bot.send_message(
        chat_id=id,
        text="<b>{0}</b> пригласил вас в свою группу. Вы примете приглашение?".
        format(creator.nickname),
        parse_mode='HTML',
        reply_markup=reply_markup)
    bot.send_message(chat_id=mes.from_user.id,
                     text="Приглашение игроку <b>{0}</b> отправлено!".format(
                         invited_player.nickname),
                     parse_mode='HTML')
Esempio n. 12
0
def pult_ok_callback(bot, update):
    mes = update.callback_query.message
    pult = Pult.get_pult(mes.chat_id)
    twink_id = pult.status.get("twink")
    twink_target = pult.status.get("target")
    real_account = pult.real_account
    if twink_id == -1 and not real_account:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Необходимо выбрать аккаунт!")
        return
    if twink_target == -1:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Необходимо выбрать замок!")
        return
    if real_account:
        twink = twinks.get(pult.chat_id)
    else:
        try:
            twink = twinks.get(twink_id)
        except IndexError:
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                    text="Ошибка при выборе аккаунта")
            return
    request = "select current_castle from twinks where telegram_id = %s"
    cursor.execute(request, (twink.telegram_id, ))
    row = cursor.fetchone()
    if row is None:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Ошибка при поиске аккаунта")
        return
    if row[0] == castles[twink_target]:
        new_target = "defense"
    else:
        new_target = "attack"
    new_castle_target = castles[twink_target]
    request = "update twinks set target = %s, castle_target = %s where telegram_id = %s"
    cursor.execute(request, (new_target, new_castle_target, twink.telegram_id))
    twink.target = new_target
    twink.castle = new_castle_target
    if twink.real_account:
        twink.target_set = True
    response = get_pult_text(
        user_id=pult.chat_id if pult.real_account else None)
    reply_markup = rebuild_pult("current", None, pult)
    bot.editMessageText(chat_id=mes.chat_id,
                        message_id=mes.message_id,
                        text=response,
                        parse_mode='HTML',
                        reply_markup=reply_markup)
    bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                            text="Успешно выполнено")
Esempio n. 13
0
    def create(self):
        self.time_start = datetime.datetime.now(tz = pytz.timezone('Europe/Moscow'))
        self.time_end = self.time_start + datetime.timedelta(hours=self.duration)
        item_id = self.item.id
        item_type = self.item.type

        request = "insert into lots(item_type, item_id, item_name, player_created_id," \
                  " price, buyout_price, time_start, time_end) " \
                  "values(%s, %s, %s, %s," \
                  " %s, %s, %s, %s) returning lot_id"
        cursor.execute(request, (item_type, item_id, self.item.name, self.player_created.id,
                                                 self.price, self.buyout_price, self.time_start, self.time_end))
        conn.commit()
        id = cursor.fetchone()[0]
        return id
Esempio n. 14
0
def info(bot, update):
    mes = update.message
    response = "ℹ️ Инфо:\n"
    request = "select castle, lvl_min, lvl_max, active from players where id = %s limit 1"
    cursor.execute(request, (mes.from_user.id, ))
    row = cursor.fetchone()
    if row is None:
        bot.send_message(
            chat_id=mes.chat_id,
            text="Произошла ошибка. Попробуйте начать снова (/start)")
        return
    castle, lvl_min, lvl_max, active = row
    response += "💬Статус: <b>{}</b>\n".format(
        "✅ Активно" if active else "❌ Отключено")
    response += "🏰Замок: {}\n".format(castle)
    response += "🏅Диапазон уровней: <b>{}</b> - <b>{}</b>\n".format(
        lvl_min, lvl_max)
    response += "\n↔️Изменить данные: /start\n"
    response += "🔺Включить: /on\n" if not active else "🔻Отключить: /off"
    bot.send_message(chat_id=mes.chat_id, text=response, parse_mode='HTML')
Esempio n. 15
0
def add_hero(bot, update):
    mes = update.message
    request = "SELECT * FROM users WHERE telegram_id = %s"
    cursor.execute(request, (mes.from_user.id, ))
    row = cursor.fetchone()
    username = mes.text[1:].split('\n')[0]
    lvl = int(mes.text[mes.text.find('🏅Уровень:'):].split()[1])
    guild = None
    if mes.text[1] == '[':
        guild = mes.text[1:].split(']')[0][1:]
    attack = int(mes.text[mes.text.find('⚔Атака:'):].split()[1])
    defense = int(mes.text[mes.text.find('⚔Атака:'):].split()[3])
    if row is None:  # Добавляем нового игрока
        request = "INSERT INTO users(telegram_id, telegram_username, user_castle, username, guild, user_lvl, " \
                  "user_attack, user_defense, last_update) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)"
        cursor.execute(
            request,
            (mes.from_user.id, mes.from_user.username, mes.text[0], username,
             guild, lvl, attack, defense, time.strftime('%Y-%m-%d %H:%M:%S')))
        bot.send_message(chat_id=update.message.chat_id,
                         text='Профиль успешно добавлен')
    else:
        # Игрок уже существует в базе данных, обновляем информацию
        request = "UPDATE users SET telegram_id = %s, telegram_username = %s,user_castle = %s, username = %s, " \
                  "guild = %s, user_lvl = %s, user_attack = %s, user_defense = %s, last_update = %s WHERE telegram_id = %s"
        cursor.execute(request,
                       (mes.from_user.id, mes.from_user.username, mes.text[0],
                        username, guild, lvl, attack, defense,
                        time.strftime('%Y-%m-%d %H:%M:%S'), mes.from_user.id))

        bot.send_message(chat_id=-1001197381190,
                         text='Профиль успешно обновлён для пользователя @' +
                         mes.from_user.username)
        try:
            bot.send_message(chat_id=update.message.from_user.id,
                             text='Профиль успешно обновлён')
        except TelegramError:
            return
Esempio n. 16
0
def g_add_defense(bot, update):
    mes = update.message
    user_id = mes.reply_to_message.from_user.id
    request = "SELECT user_defense, username FROM users WHERE telegram_id = %s"
    cursor.execute(request, (mes.reply_to_message.from_user.id,))
    row = cursor.fetchone()
    if row is None:
        bot.send_message(chat_id=update.message.chat_id, text="Пользователь не найден в базе данных")
        return
    current = User(mes.reply_to_message.from_user.id, row[1], 0, row[0])
    for i in g_defending_users:
        if i.id == user_id:
            bot.send_message(chat_id=update.message.chat_id, text="Игрок уже защищает")
            return
    globals.g_added_defense += row[0]
    g_defending_users.append(current)
    response = "Пользователь добавлен. Всего защиты: 🛡<b>{0}</b>\n".format(globals.g_added_defense)
    response += "Атакующие игроки:\n"
    g_defending_users.sort(key = lambda curr:curr.defense, reverse = True)
    for i in g_defending_users:
        response += "<b>{0}</b> 🛡<b>{1}</b>\n".format(i.username, i.defense)

    bot.send_message(chat_id=update.message.chat_id, text=response, parse_mode='HTML')
Esempio n. 17
0
    def update_from_database(self):
        request = "SELECT id, username, nickname, sex, fraction, race, game_class," \
                  " exp, lvl, free_points, free_skill_points, fatigue, first_skill_lvl, second_skill_lvl, " \
                  "third_skill_lvl, fourth_skill_lvl, fifth_skill_lvl, endurance, power, armor, charge, speed, mana, hp," \
                  " location, gold, metal, wood, " \
                  "head, body, shoulders, legs, feet, left_arm, right_arm, mount FROM players WHERE id = %s"
        cursor.execute(request, (self.id, ))
        row = cursor.fetchone()
        if row is None:
            return None
        self.id = row[0]
        self.username = row[1]
        self.nickname = row[2]
        self.sex = row[3]
        self.fraction = row[4]
        self.race = row[5]
        self.game_class = row[6]
        self.aggro_prob = aggro_probe_game_classes.get(self.game_class)
        self.exp = row[7]
        self.lvl = row[8]
        self.free_points = row[9]
        self.free_skill_points = row[10]
        self.fatigue = row[11]
        skill_names = list(skills.get(self.game_class))
        for i in range(len(skill_names)):
            if i in [0, len(skill_names) - 1]:
                continue
            self.skill_lvl.update({skill_names[i]: row[12 + i - 1]})
        self.stats.update(endurance=row[17],
                          power=row[18],
                          armor=row[19],
                          charge=row[20],
                          speed=row[21])
        self.charge = row[22]
        self.hp = row[23]
        self.location = row[24]
        self.resources.update(gold=row[25], metal=row[26], wood=row[27])

        self.on_character.update(
            head=row[28] if row[28] != 'None' else None,
            body=row[29] if row[29] != 'None' else None,
            shoulders=row[30] if row[30] != 'None' else None,
            legs=row[31] if row[31] != 'None' else None,
            feet=row[32] if row[32] != 'None' else None,
            left_arm=row[33] if row[33] != 'None' else None,
            right_arm=row[34] if row[34] != 'None' else None,
            mount=row[35] if row[35] != 'None' else None)
        request = "SELECT type, id, quanty FROM inventory WHERE user_id = %s"
        cursor.execute(request, (self.id, ))
        row = cursor.fetchone()
        while row:
            type = row[0]
            id = row[1]
            quanty = row[2]
            if type == "a":
                self.al_backpack.update({id: quanty})
            elif type == "r":
                self.res_backpack.update({id: quanty})
            else:
                self.eq_backpack.update({id: quanty})
            row = cursor.fetchone()
        return self
Esempio n. 18
0
def add_report(bot, update):
    mes = update.message
    request = "SELECT * FROM users WHERE telegram_id = %s"
    cursor.execute(request, (mes.from_user.id, ))
    row = cursor.fetchone()
    if row is None:
        try:
            bot.send_message(
                chat_id=update.message.from_user.id,
                text=
                'Профиль не найден в базе данных. Пожалуйста, обновите /hero')
        except TelegramError:
            return
        return
    d = datetime.datetime(2018, 5, 27, 9, 0, 0, 0)
    c = datetime.timedelta(hours=8)
    try:
        forward_message_date = local_tz.localize(
            update.message.forward_date).astimezone(tz=moscow_tz).replace(
                tzinfo=None)
    except ValueError:
        print("value error")
        try:
            forward_message_date = update.message.forward_date.astimezone(
                tz=moscow_tz).replace(tzinfo=None)
        except ValueError:
            forward_message_date = update.message.forward_date
    a = forward_message_date - d
    battle_id = 0
    while a > c:
        a = a - c
        battle_id = battle_id + 1
    if mes.text[1:mes.text.find('⚔') - 1] != row[4]:
        try:
            bot.send_message(
                chat_id=update.message.from_user.id,
                text=
                'Это не ваш репорт. В случае возникновения ошибок обновите профиль'
            )
        except TelegramError:
            return
        return
    attack = int(mes.text[mes.text.find('⚔') + 2:].split()[0].split('(')[0])
    defense = int(mes.text[mes.text.find('🛡') + 2:].split()[0].split('(')[0])
    lvl = int(mes.text[mes.text.find("Lvl") + 4:].split()[0])
    if mes.text.find("🔥Exp:") == -1:
        exp = 0
    else:
        exp = int(mes.text[mes.text.find("🔥Exp:"):].split()[1])
    if mes.text.find("💰Gold") == -1:
        gold = 0
    else:
        gold = int(mes.text[mes.text.find("💰Gold"):].split()[1])
    if mes.text.find("📦Stock") == -1:
        stock = 0
    else:
        stock = int(mes.text[mes.text.find("📦Stock"):].split()[1])
    critical = 0
    guardian = 0
    request = "SELECT * FROM reports WHERE user_id = %s AND battle_id = %s"
    cursor.execute(request, (row[0], battle_id))
    response = cursor.fetchone()
    if response is not None:
        bot.send_message(chat_id=update.message.chat_id,
                         text='Репорт за эту битву уже учтён!')
        return
    additional_attack = 0
    additional_defense = 0
    guild_tag = str(mes.text[2:mes.text.find(']')].upper())
    if mes.text.find('⚡Critical strike') != -1:
        critical = 1
        if guild_tag in list(guilds_chat_ids):
            knight_critical(bot, update)
        text = mes.text.partition('🛡')[0]
        try:
            additional_attack = int(text[text.find('+') + 1:text.find(')')])
        except ValueError:
            try:
                additional_attack = int(text[text.find('-'):text.find(')')])
            except ValueError:
                logging.error(traceback.format_exc())
                additional_attack = 0
    elif mes.text.find('⚡Lucky Defender!') != -1:
        critical = 1
        if guild_tag in list(guilds_chat_ids):
            sentinel_critical(bot, update)
        text = mes.text.partition('🛡')[2]
        try:
            additional_defense = int(text[text('+') + 1:text.find(')')])
        except ValueError:
            try:
                additional_defense = int(text[text.find('-'):text.find(')')])
            except ValueError:
                logging.error(traceback.format_exc())
                additional_defense = 0
    elif mes.text.find('🔱Guardian angel') != -1:
        guardian = 1
        if guild_tag in list(guilds_chat_ids):
            sentinel_critical(bot, update)
        text = mes.text.partition('🛡')[2]
        try:
            additional_defense = int(text[text.find('+') + 1:text.find(')')])
        except ValueError:
            try:
                additional_defense = int(text[text.find('-'):text.find(')')])
            except ValueError:
                logging.error(traceback.format_exc())
                additional_defense = 0

    request = "INSERT INTO reports(user_id, battle_id, date_in, report_attack, report_defense," \
              " report_lvl, report_exp, report_gold, report_stock, critical_strike, guardian_angel," \
              " additional_attack, additional_defense) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"
    cursor.execute(request,
                   (row[0], battle_id, time.strftime('%Y-%m-%d %H:%M:%S'),
                    attack, defense, lvl, exp, gold, stock, critical, guardian,
                    additional_attack, additional_defense))

    # bot.send_message(chat_id=-1001197381190, text='Репорт успешно учтён для пользователя @' + mes.from_user.username)
    try:
        bot.send_message(chat_id=update.message.from_user.id,
                         text='Репорт учтён. Спасибо!')
    except TelegramError:
        pass
    now = datetime.datetime.now(tz=moscow_tz).replace(
        tzinfo=None) - datetime.datetime.combine(
            datetime.datetime.now().date(), datetime.time(hour=0))
    if now < datetime.timedelta(hours=1):
        remaining_time = datetime.timedelta(hours=1) - now
        time_from_battle = datetime.timedelta(hours=8) - remaining_time
    else:
        time_from_battle = now - datetime.timedelta(hours=1)
        while time_from_battle > datetime.timedelta(hours=8):
            time_from_battle -= datetime.timedelta(hours=8)

    time_from_receiving_report = datetime.datetime.now(tz=moscow_tz).replace(
        tzinfo=None) - forward_message_date

    if False and time_from_receiving_report < time_from_battle:
        #   Репорт с последней битвы -- отключено из-за спама в чаты
        if mes.text.find("]") > 0:
            guild_tag = str(mes.text[2:mes.text.find(']')].upper())
            guild_reports = reports_count.get(guild_tag)
            if guild_reports is None:
                guild_reports = GuildReports(guild_tag)
            current_report = Report(
                mes.from_user.id, mes.text[0], mes.text[1:].partition('⚔')[0],
                lvl, exp, gold, stock, attack, defense,
                datetime.datetime.now(moscow_tz).replace(tzinfo=None))
            guild_reports.add_report(current_report)
            reports_count.update({guild_tag: guild_reports})
            chat_id = guilds_chat_ids.get(guild_tag)
            if chat_id is not None:
                percent = (guild_reports.num_reports /
                           guild_reports.num_players) * 100
                response = "Репорт от <b>{0}</b> принят.\nВсего сдало репортов <b>{1}</b> человек, это <b>{2:.2f}</b>% " \
                           "от общего числа\n".format(current_report.nickname, guild_reports.num_reports,
                                                      percent)
                if guild_reports.num_reports == 1:
                    response += '{0} \n \n 🏅 Первый репорт в гильдии!'.format(
                        response)
                if percent == 100:
                    response += "Все сдали репорты! Какие вы лапочки!"

                else:
                    if time_from_battle > datetime.timedelta(hours=1):
                        response += "Всё ещё не сдали репорты:\n"
                        for user in guild_reports.users:
                            if not user.report_sent:
                                response += "<b>{0}</b>,    ".format(
                                    user.username)
                        response = response[:-5]  # Обрезаю последнюю запятую

                    else:
                        return  # В первый час бот не сообщает о репорте в чат
                try:
                    bot.sync_send_message(chat_id=chat_id,
                                          text=response,
                                          parse_mode='HTML')
                except TelegramError:
                    bot.send_message(chat_id=admin_ids[0],
                                     text=response,
                                     parse_mode='HTML')
Esempio n. 19
0
def g_all_attack(bot, update):
    mes = update.message
    num_attacking_guilds = int(mes.text.split(' ')[1])
    args = [mes.text.split(' ')[2]]
    request = "SELECT COUNT(1) FROM users WHERE guild = %s"
    request2 = "SELECT username, user_attack FROM users WHERE guild = %s"
    for i in range (1, num_attacking_guilds):
        args.append(mes.text.split(' ')[i + 2])
        request += " OR guild = %s"
        request2 += " OR guild = %s"

    request2 += " ORDER BY user_attack DESC"
    num_guilds = int(mes.text.split(' ')[num_attacking_guilds + 2])
    cursor.execute(request, tuple(args))
    row = cursor.fetchone()

    num_users = int(row[0])

    users = []

    cursor.execute(request2, tuple(args))
    row = cursor.fetchone()
    total_attack = 0
    i = 0
    while row:
        total_attack += int(row[1])
        users.append(User_for_attack(row[0], int(row[1]), -1))
        i += 1
        row = cursor.fetchone()

    ratio = mes.text.split(' ')[num_attacking_guilds + 3]
    ratios = ratio.split(':')
    sum_ratio = 0
    for i in range (0, num_guilds):
        sum_ratio += int(ratios[i])
    attacks = [int] * num_guilds
    for i in range (0, num_guilds):
        attacks[i] = int(ratios[i]) / sum_ratio * total_attack
    #       Здесь кончается верный кусок кода
    for i in range (0, num_users):
        min_remain = 100000000    #Перестанет работать, если вдруг суммарная атака достигнет этой величины
        min_number = 0
        flag = 0
        for j in range (0, num_guilds):
            remain = attacks[j] - users[i].attack
            if remain < min_remain and remain >= 0:
                min_remain = remain
                min_number = j
                flag = 1
        if flag: #  Есть свободное место под этого атакующего
            users[i].g_attacking = min_number
            attacks[min_number] = min_remain
        else:
            min_remain = -100000000
            for j in range(0, num_guilds):
                remain = attacks[j] - users[i].attack
                if remain > min_remain:
                    min_remain = remain
                    min_number = j
                    attacks[j] = remain
            users[i].g_attacking = min_number
    response = "Рассчёт распределения урона подготовлен:"
    for i in range (0, num_guilds):
        response += "\n" + str(i) + " гильдия:\n"
        guild_attack = 0
        for j in range (0, num_users):
            if users[j].g_attacking == i:
                response += "<b>" + users[j].username + "</b> ⚔" + str(users[j].attack) + "\n"
                guild_attack += users[j].attack
        response += "Total attack: ⚔" + str(guild_attack) + "\n"
    bot.send_message(chat_id=update.message.chat_id, text=response, parse_mode='HTML')