Esempio n. 1
0
def attackCommand(bot, update):
    response = update.message.text[1:len(update.message.text)]
    stats = "Рассылка пинов началась в <b>{0}</b>\n\n".format(time.ctime())

    bot.send_message(chat_id=update.message.chat_id, text=stats, parse_mode = 'HTML')
    request = "select chat_id, pin_enabled, disable_notification from guilds where orders_enabled = '1'"
    cursor.execute(request)
    row = cursor.fetchone()
    orders_sent = 0
    while row:
        bot.send_order(order_id=globals.order_id, chat_id=row[0], response=response, pin_enabled=row[1], notification=not row[2])
        row = cursor.fetchone()
        orders_sent += 1
    response = ""
    orders_OK = 0
    orders_failed = 0
    while orders_OK + orders_failed < orders_sent:
        current = order_backup_queue.get()
        if current.order_id == globals.order_id:
            if current.OK:
                orders_OK += 1
            else:
                orders_failed += 1
                response += current.text
        else:
            # order_backup_queue.put(current)
            logging.warning("Incorrect order_id, received {0}, now it is {1}".format(current.order_id, globals.order_id))

    globals.order_id += 1
    stats = "Выполнено в <b>{0}</b>, отправлено в <b>{1}</b> чатов, " \
            "ошибка при отправке в <b>{2}</b> чатов\n\n".format(time.ctime(), orders_OK, orders_failed) + response
    bot.send_message(chat_id=update.message.chat_id, text=stats, parse_mode = 'HTML')
    return
Esempio n. 2
0
def remove_order(bot, update):
    mes = update.message
    deferred_id = int(mes.text.partition("@")[0].split("_")[2])
    current_order = None
    for order in deferred_orders:
        if order.deferred_id == deferred_id:
            current_order = order
            deferred_orders.remove(order)
            break
    request = "delete from deferred_orders where deferred_id = %s"
    cursor.execute(request, (deferred_id,))
    try:
        current_order.job.schedule_removal()
    except AttributeError:
        bot.send_message(chat_id = mes.chat_id, text="Приказ существует?")
        return
    bot.send_message(chat_id=mes.chat_id, text="Приказ успешно отменён")
    pult = Pult.get_pult(None, Pult.last_pult_id)
    if pult is None:
        return
    new_text = pult.get_text()
    reply_markup = pult.get_reply_markup()
    bot.editMessageText(chat_id=pult.chat_id, message_id=pult.id, text=new_text + "\n\n{0}".format(
                datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None).strftime("%d/%m/%y %H:%M:%S")),
                        reply_markup=reply_markup, parse_mode='HTML')
Esempio n. 3
0
def refill_deferred_orders():
    logging.info("Refilling deferred orders...")
    request = "select order_id, time_set, target, defense, tactics, deferred_id, divisions, potions from deferred_orders"
    cursor.execute(request)
    row = cursor.fetchone()
    cursor2 = conn.cursor()
    while row:
        time_to_send = row[1]
        target = row[2]
        castle_target = castles[target]
        defense = row[3]
        defense_target = None
        if defense is not None:
            defense_target = defense_to_order[defense]
        tactics = row[4]
        deferred_id = row[5]
        divisions = row[6]
        potions = row[7]
        now = datetime.datetime.now(tz=local_tz).replace(tzinfo=None)
        print(now, time_to_send)
        if now > time_to_send:
            request = "delete from deferred_orders where deferred_id = %s"
            cursor2.execute(request, (row[5],))
        else:
            context = [CALLBACK_CHAT_ID, castle_target, defense_target, tactics, divisions, potions, deferred_id]
            j = job.run_once(send_order_job, time_to_send.astimezone(local_tz).replace(tzinfo = None), context=context)
            current = DeferredOrder(row[5], globals.order_id, divisions, time_to_send, castle_target, defense_target, tactics, potions, j)
            deferred_orders.append(current)
        row = cursor.fetchone()
    logging.info("Orders refilled")
Esempio n. 4
0
def pult_send(bot, update):
    globals.logs += "{} - @{} Нажал \"Отправить\"" \
                      "\n".format(datetime.datetime.now(tz=moscow_tz).strftime("%d/%m/%y %H-%M-%S"),
                                  update.callback_query.from_user.username)
    mes = update.callback_query.message
    pult = Pult.get_pult(mes.chat_id, mes.message_id)
    pult_status = pult.status
    target = pult_status.get("target")
    time_to_send = pult_status.get("time")
    tactics_num = pult_status.get("tactics")
    potions = pult.potions_active.copy()
    if target == -1:
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Необходимо выбрать цель")
        return
    divisions = pult_status.get("divisions").copy()
    if not any(divisions):
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Необходимо выбрать дивизион")
        return
    if divisions[len(divisions) - 1]:
        divisions = "ALL"
    elif divisions[pult.all_attackers_division_num] is True:
        for i in range(pult.all_attackers_division_num):
            divisions[i] = True
    print(divisions)
    castle_target = castles[target]
    defense = pult_status.get("defense")
    defense_target = defense_to_order[defense]
    tactics_target = tactics_to_order[tactics_num]
    if pult.variant:
        # Создание варианта битвы
        i = int(time.time() % (24 * 60 * 60))  # id уникален в течении суток
        while Pult.variants and i in Pult.variants:
            i += 1
        current = DeferredOrder(i, globals.order_id, divisions, time_to_send,
                                castle_target, defense_target, tactics_target,
                                potions, None)
        pult.variants.update({i: current})
        bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                                text="Вариант создан.")
        return
    if time_to_send < 0 and pult.deferred_time is None:
        # Мгновенная отправка приказа
        send_order(bot=bot,
                   chat_callback_id=mes.chat_id,
                   divisions=divisions,
                   castle_target=castle_target,
                   defense=defense_target,
                   tactics=tactics_target,
                   potions=potions)
        return
    # Планирование отложки
    if pult.deferred_time is not None:
        time_to_send = pult.deferred_time
    else:
        next_battle = count_next_battle_time()
        logging.info("Next battle : {0}".format(next_battle))
        next_battle_time = next_battle.time()
        if time_to_send == 0:  # Мгновенная отправка, но с подстановкой времени в пин
            send_order(bot=bot,
                       chat_callback_id=mes.chat_id,
                       divisions=divisions,
                       castle_target=castle_target,
                       defense=defense_target,
                       tactics=tactics_target,
                       time=next_battle_time,
                       potions=potions)
            bot.answerCallbackQuery(callback_query_id=update.callback_query.id)
            return
        time_to_send = next_battle - times_to_time[time_to_send]
        time_to_send = moscow_tz.localize(time_to_send).astimezone(
            local_tz).replace(tzinfo=None)
    #------------------------------------------------------------------------------------------------------- TEST ONLY
    #time_to_send = datetime.datetime.now(tz=moscow_tz).replace(tzinfo=None).replace(hour=16, minute=31, second=0)
    #-------------------------------------------------------------------------------------------------------
    if divisions == "ALL":
        divisions = []
        for i in range(len(divisions_const)):
            divisions.append(False)
        divisions[-1] = True
    request = "insert into deferred_orders(order_id, time_set, target, defense, tactics, divisions, potions) values " \
              "(%s, %s, %s, %s, %s, %s, %s) returning deferred_id"
    cursor.execute(request, (globals.order_id, time_to_send, target, defense,
                             tactics_target, divisions, potions))
    row = cursor.fetchone()

    context = [
        mes.chat_id, castle_target, defense_target, tactics_target, divisions,
        potions, row[0]
    ]
    j = job.run_once(send_order_job,
                     time_to_send.astimezone(local_tz).replace(tzinfo=None),
                     context=context)

    current = DeferredOrder(row[0], globals.order_id, divisions, time_to_send,
                            castle_target, defense_target, tactics_target,
                            potions, j)
    deferred_orders.append(current)

    logging.info("Deffered successful on {0}".format(time_to_send))
    bot.answerCallbackQuery(callback_query_id=update.callback_query.id,
                            text="Приказ успешно отложен")
    new_text = Pult.get_text()
    reply_markup = rebuild_pult("None", pult, None)
    bot.editMessageText(chat_id=mes.chat_id,
                        message_id=mes.message_id,
                        text=new_text + "\n\n{0}".format(
                            datetime.datetime.now(tz=moscow_tz).replace(
                                tzinfo=None).strftime("%d/%m/%y %H:%M:%S")),
                        reply_markup=reply_markup,
                        parse_mode='HTML')