Beispiel #1
0
def arsenal_control(call):
    # print("arsenal_control")
    # print(call)
    message_id = call.inline_message_id
    user = User(call.from_user.id, call.from_user.first_name,
                call.from_user.username)
    log.debug("%s is trying to control arsenal check" % user)
    if not hlp.IsUserAdmin(user):
        bot.answer_callback_query(
            call.id, "Только офицеры могут управлять чеком арсенала!")
        log.error("Failed (not an admin)")
        return
    userChoice = call.data
    if userChoice == kb.ARS_CONTROL_OPTIONS[0]:  # stop
        if common.current_arscheck and message_id == common.current_arscheck.check_id:
            common.current_arscheck.DoEndArsenal()
            bot.edit_message_text(
                common.current_arscheck.GetText(),
                inline_message_id=common.current_arscheck.check_id,
                parse_mode="markdown")
            # unpin rage time message
            bot.unpin_all_chat_messages(common.warchat_id)
            bot.answer_callback_query(call.id, "🏁 Чек арсенала завершен")
            hlp.LogEvent("🏁 %s завершил чек арсенала" %
                         user.GetString(with_link=False))
            return
    log.error("Ars check not found!")
    bot.answer_callback_query(
        call.id, "Неверный чек арсенала! Пожалуйста, создайте новый")
Beispiel #2
0
def crystals_query_inline(q):
    # print("crystals_query_inline")
    # print(q)
    user = User(q.from_user.id, q.from_user.first_name, q.from_user.username)
    log.debug("%s is trying to create crystals check" % user)
    if not hlp.IsUserAdmin(user): # non-admins cannot post votes
        log.error("Failed (not an admin)")
        hlp.SendHelpNonAdmin(q)
        bot.answer_callback_query(q.id)
        return
    if hlp.CanStartNewCryscheck():
        ranges = common.settings.GetSetting("crystals_ranges")
        kb.SetupCrystalsKeyboard(maxvalue=ranges[0], step=ranges[1])
        res = types.InlineQueryResultArticle('cryscheck',
                                            title='Создать чек по кри',
                                            description='0 - %d, шаг %d' % ranges,
                                            input_message_content=types.InputTextMessageContent(ICON_CRYSTAL+" *Чек по кри*", parse_mode="markdown"),
                                            thumb_url="https://i.ibb.co/b7XSWQr/crystal.png",
                                            reply_markup=kb.KEYBOARD_CRYSTALS)
        bot.answer_inline_query(q.id, [res], is_personal=True, cache_time=2)
    else:
        log.error("Trying to setup another crystals check while current is not finished")
        error_text = "Уже имеется активный чек по кри"
        bot.answer_inline_query(q.id, [], is_personal=True, cache_time=2,
                                switch_pm_text=error_text, switch_pm_parameter="existing_crystals")
def precheck_query_inline(q):
    # print("precheck_query_inline")
    # print(q)
    user = User(q.from_user.id, q.from_user.first_name, q.from_user.username)
    log.debug("%s is trying to create pre-check" % user)
    if not hlp.IsUserAdmin(user):  # non-admins cannot post votes
        log.error("Failed (not an admin)")
        hlp.SendHelpNonAdmin(q)
        bot.answer_callback_query(q.id)
        return
    if hlp.CanStartNewPrecheck():
        res = types.InlineQueryResultArticle(
            'precheck',
            title='Создать чек перед ВГ',
            description='🗓✅💤❌',
            input_message_content=types.InputTextMessageContent(
                "📝 *Чек перед ВГ*", parse_mode="markdown"),
            thumb_url="https://i.ibb.co/G79HtRG/precheck.png",
            reply_markup=kb.KEYBOARD_PRECHECK)
        bot.answer_inline_query(q.id, [res], is_personal=True, cache_time=2)
    else:
        log.error(
            "Trying to setup another pre-check while current is not finished")
        error_text = "Уже имеется активный чек"
        bot.answer_inline_query(q.id, [],
                                is_personal=True,
                                cache_time=2,
                                switch_pm_text=error_text,
                                switch_pm_parameter="existing_precheck")
def numbers_query_inline(q):
    # print("numbers_query_inline")
    # print(q)
    user = User(q.from_user.id, q.from_user.first_name, q.from_user.username)
    log.debug("%s is trying to create numbers check" % user)
    if not hlp.IsUserAdmin(user):  # non-admins cannot post votes
        log.error("Failed (not an admin)")
        hlp.SendHelpNonAdmin(q)
        bot.answer_callback_query(q.id)
        return
    if hlp.CanStartNewBattle():
        log.error("Trying to setup numbers check with no current battle")
        error_text = "Отсутствует активный бой"
        bot.answer_inline_query(q.id, [],
                                is_personal=True,
                                cache_time=2,
                                switch_pm_text=error_text,
                                switch_pm_parameter="existing_battle")
        return
    res, numbers = hlp.IsNumbersQuery(q)
    if res:
        if hlp.CanStartNewNumbers():
            text = 'Добавить прогресс номеров'
            if len(numbers) == 1:
                text2 = 'по скринам (%s)' % numbers[0]
                kb.SetupNumbersKeyboard(count=int(numbers[0]))
            else:
                text2 = 'по игре (%s)' % ' '.join(str(num) for num in numbers)
                kb.SetupNumbersKeyboard(ingame_nums=numbers)
            res = types.InlineQueryResultArticle(
                'numbers',
                title=text,
                description=text2,
                input_message_content=types.InputTextMessageContent(
                    ICON_NUMBERS + " *Прогресс номеров*",
                    parse_mode="markdown"),
                thumb_url="https://i.ibb.co/JRRMLjv/numbers.png",
                reply_markup=kb.KEYBOARD_NUMBERS)
            bot.answer_inline_query(q.id, [res],
                                    is_personal=True,
                                    cache_time=2)
        elif not hlp.CanStartNewNumbers():
            log.error(
                "Trying to setup another numbers check while current has not reached 500/1000"
            )
            error_text = "Уже имеется активный чек номеров"
            bot.answer_inline_query(q.id, [],
                                    is_personal=True,
                                    cache_time=2,
                                    switch_pm_text=error_text,
                                    switch_pm_parameter="existing_numbers")
    else:
        log.error("Failed (invalid query)")
        error_text = "Неверный формат запроса"
        bot.answer_inline_query(q.id, [],
                                is_personal=True,
                                cache_time=2,
                                switch_pm_text=error_text,
                                switch_pm_parameter="existing_numbers")
def battle_control(call):
    # print("battle_control")
    # print(call)
    message_id = call.inline_message_id
    user = User(call.from_user.id, call.from_user.first_name,
                call.from_user.username)
    log.debug("%s is trying to control battle" % user)
    if not hlp.IsUserAdmin(user):
        bot.answer_callback_query(call.id,
                                  "Только офицеры могут управлять боем!")
        log.error("Failed (not an admin)")
        return
    userChoice = call.data
    need_send_notification = True
    if common.current_battle and message_id == common.current_battle.check_id:
        notification_text = ""
        if userChoice == kb.CHECK_CONTROL_OPTIONS[0]:  # roll
            common.current_battle.DoRollBattle()
            notification_text = ICON_ROLL + " Крутит"
            bot.edit_message_text(
                common.current_battle.GetText(),
                inline_message_id=common.current_battle.check_id,
                parse_mode="markdown",
                reply_markup=common.current_battle.keyboard)
            common.current_battle.BattleRollNotifyActiveUsers(except_user=user)
        elif userChoice == kb.CHECK_CONTROL_OPTIONS[1]:  # start
            common.current_battle.DoStartBattle()
            notification_text = ICON_SWORDS + " Бой начался"
            bot.edit_message_text(
                common.current_battle.GetText(),
                inline_message_id=common.current_battle.check_id,
                parse_mode="markdown",
                reply_markup=common.current_battle.keyboard)
            common.current_battle.BattleStartNotifyActiveUsers(
                except_user=user)
        elif userChoice == kb.CHECK_CONTROL_OPTIONS[2]:  # stop
            if not common.current_battle.is_started:  # if battle was cancelled - do not send notification
                need_send_notification = False
                notification_text = ICON_CANCEL + " Бой отменен"
            else:  # unpin other battle messages
                bot.unpin_all_chat_messages(common.warchat_id)
                need_send_notification = False  # disable annoying useless message
                notification_text = ICON_FINISH + " Бой завершен"
            reset_battlechecks(call)
            # do not notify about roll / stop
        if need_send_notification:
            bot.send_message(common.warchat_id,
                             notification_text + " (%s)" % user.GetString(),
                             parse_mode="markdown")
            log.debug("Battle status notification posted: %s" %
                      notification_text)
        hlp.LogEvent(notification_text +
                     " (%s)" % user.GetString(with_link=False))
        bot.answer_callback_query(call.id, notification_text)
        return
    log.error("Battle not found!")
    bot.answer_callback_query(call.id,
                              "Неверный чек боя! Пожалуйста, создайте новый")
def command_stat_backup(m):
    """
    Backup whole current statistic into pickle and json-readable files.
    Send files to user
    """
    user = [m.from_user.id, m.from_user.username, m.from_user.first_name]
    log.debug("User %d (%s %s) is requested statistics backup" % (*user, ))
    try:
        if not hlp.IsInPrivateChat(m):
            common.bot.delete_message(m.chat.id, m.message_id)
            hlp.SendHelpWrongChat(m.from_user.id, "/statbackup",
                                  "создать резервную копию статистики", True)
            return
    except:  # case if called from Statistic backup timeout. Could be ignored
        pass
    if not hlp.IsUserAdmin(m.from_user.id):
        hlp.SendHelpNonAdmin(m)
        return
    FILE_PREFIX = "GWBotStatistic"
    common.bot.send_message(m.from_user.id, "📥 Сохраняю статистику...")
    try:
        # dump pickle Statistic object
        with open(FILE_PREFIX + '.BAK', 'wb') as backup:
            pickle.dump(common.statistics, backup, pickle.HIGHEST_PROTOCOL)
            backup.close()
        # dump json Statistic object
        with open(FILE_PREFIX + '.txt', 'w') as backup_json:
            json.dump(common.statistics,
                      backup_json,
                      separators=(',', ': '),
                      cls=StatsEncoder,
                      indent=4,
                      ensure_ascii=False)
            backup_json.close()
        # send pickle
        common.bot.send_chat_action(m.from_user.id, "upload_document")
        with open(FILE_PREFIX + '.BAK', 'rb') as backup:
            common.bot.send_document(m.from_user.id,
                                     backup,
                                     caption="Файл-объект статистики").wait()
            backup.close()
        aws_stat_backup(FILE_PREFIX + '.BAK', burst=True)
        os.remove(FILE_PREFIX + '.BAK')
        # send json
        common.bot.send_chat_action(m.from_user.id, "upload_document")
        with open(FILE_PREFIX + '.txt', 'r') as backup_json:
            common.bot.send_document(
                m.from_user.id,
                backup_json,
                caption="JSON-описание статистики").wait()
            backup_json.close()
        os.remove(FILE_PREFIX + '.txt')
    except Exception as err:
        log.error("Backup statistics failed: ", str(err))
        common.bot.send_message(m.from_user.id,
                                ICON_CANCEL + " Ошибка сохранения статистики!")
def numbers_control(call):
    # print("numbers_control")
    # print(call)
    message_id = call.inline_message_id
    user = User(call.from_user.id, call.from_user.first_name,
                call.from_user.username)
    log.debug("%s is trying to control numbers check" % user)
    if not hlp.IsUserAdmin(user):
        bot.answer_callback_query(
            call.id, "Только офицеры могут управлять чеком номеров!")
        log.error("Failed (not an admin)")
        return
    userChoice = call.data
    if common.current_numcheck and message_id == common.current_numcheck.check_id:
        if userChoice == kb.NUMBERS_CONTROL_OPTIONS[0]:  # make 500
            common.current_numcheck.Do500()
            bot.edit_message_text(
                common.current_numcheck.GetText(),
                inline_message_id=common.current_numcheck.check_id,
                parse_mode="markdown",
                reply_markup=common.current_numcheck.keyboard)
            common.current_numcheck.CheckNotifyIfAchieved(user)
            bot.answer_callback_query(call.id, "Отмечено " + ICON_500)
            return
        elif userChoice == kb.NUMBERS_CONTROL_OPTIONS[1]:  # make 1000
            common.current_numcheck.Do1000()
            bot.edit_message_text(
                common.current_numcheck.GetText(),
                inline_message_id=common.current_numcheck.check_id,
                parse_mode="markdown",
                reply_markup=common.current_numcheck.keyboard)
            common.current_numcheck.CheckNotifyIfAchieved(user)
            bot.answer_callback_query(call.id, "Отмечено " + ICON_1000)
            return
        elif userChoice == kb.NUMBERS_CONTROL_OPTIONS[2]:  # stop
            common.current_numcheck.DoEndCheck()
            bot.edit_message_text(
                common.current_numcheck.GetText(),
                inline_message_id=common.current_numcheck.check_id,
                parse_mode="markdown")
            bot.answer_callback_query(call.id, "🏁 Чек номеров завершен")
            hlp.LogEvent("🏁 %s завершил чек номеров" %
                         user.GetString(with_link=False))
            return
        else:
            log.error("invalid action!")
            bot.answer_callback_query(
                call.id,
                "Неверныая команда! Пожалуйста, обратитесь к администратору бота"
            )
    log.error("Numbers check not found!")
    bot.answer_callback_query(
        call.id, "Неверный чек номеров! Пожалуйста, создайте новый")
def battle_query_inline(q):
    # print("battle_query_inline")
    # print(q)
    user = User(q.from_user.id, q.from_user.first_name, q.from_user.username)
    log.debug("%s is trying to create battle check" % user)
    if not hlp.IsUserAdmin(user):  # non-admins cannot post votes
        log.error("Failed (not an admin)")
        hlp.SendHelpNonAdmin(q)
        bot.answer_callback_query(q.id)
        return
    res, time, comment = hlp.IsCheckTimeQuery(q)
    if res:
        if hlp.CanStartNewBattle() or hlp.CanStopCurrentBattle():
            # stop current battle as the time is passed anyway
            # to help admin not doing exact battle stop but start another with auto-stopping the previous
            if hlp.CanStopCurrentBattle():
                q.data = kb.CHECK_CONTROL_OPTIONS[2]
                q.inline_message_id = common.current_battle.check_id
                battle_control(q)
            desc = ICON_CHECK + ICON_RAGE + ICON_FAST + ICON_ARS + ICON_THINK + ICON_CANCEL
            if comment:
                desc += "\n" + comment
            res = types.InlineQueryResultArticle(
                'battle',
                title='[%s] Создать чек на бой' % time,
                description=desc,
                input_message_content=types.InputTextMessageContent(
                    ICON_SWORDS + " *Бой*: %s" % time, parse_mode="markdown"),
                thumb_url="https://i.ibb.co/jb9nVCm/battle.png",
                reply_markup=kb.KEYBOARD_CHECK)
            bot.answer_inline_query(q.id, [res],
                                    is_personal=True,
                                    cache_time=2)
        else:
            log.error(
                "Trying to setup another battle while current is not finished")
            error_text = "Уже имеется активный бой в %0.2d:%0.2d" % (
                *common.current_battle.GetTime(start=True), )
            bot.answer_inline_query(q.id, [],
                                    is_personal=True,
                                    cache_time=2,
                                    switch_pm_text=error_text,
                                    switch_pm_parameter="existing_battle")
    else:
        log.error("Failed (invalid query)")
        error_text = "Неверный формат запроса"
        bot.answer_inline_query(q.id, [],
                                is_personal=True,
                                cache_time=2,
                                switch_pm_text=error_text,
                                switch_pm_parameter="existing_battle")
Beispiel #9
0
def arsenal_query_inline(q):
    # print("arsenal_query_inline")
    # print(q)
    user = User(q.from_user.id, q.from_user.first_name, q.from_user.username)
    log.debug("%s is trying to create arsenal check" % user)
    if not hlp.IsUserAdmin(user):  # non-admins cannot post votes
        log.error("Failed (not an admin)")
        hlp.SendHelpNonAdmin(q)
        bot.answer_callback_query(q.id)
        return
    if hlp.CanStartNewBattle():
        log.error("Trying to setup arsenal check with no current battle")
        error_text = "Отсутствует активный бой"
        bot.answer_inline_query(q.id, [],
                                is_personal=True,
                                cache_time=2,
                                switch_pm_text=error_text,
                                switch_pm_parameter="existing_battle")
        return
    res, time = hlp.IsArsQuery(q)
    if res:
        if hlp.CanStartNewArs():
            res = types.InlineQueryResultArticle(
                'arsenal',
                title='Добавить прогресс арсенала',
                description=ICON_ARS + ' |████--| Х/120\nЯрость в %s' % time,
                input_message_content=types.InputTextMessageContent(
                    ICON_ARS + " *Прогресс арсенала:* 0/120",
                    parse_mode="markdown"),
                thumb_url="https://i.ibb.co/WfxPRks/arsenal.png",
                reply_markup=kb.KEYBOARD_ARS)
            bot.answer_inline_query(q.id, [res],
                                    is_personal=True,
                                    cache_time=2)
        else:
            log.error(
                "Trying to setup another arsenal check while current has not been fired"
            )
            error_text = "Уже имеется активный чек арсенала"
            bot.answer_inline_query(q.id, [],
                                    is_personal=True,
                                    cache_time=2,
                                    switch_pm_text=error_text,
                                    switch_pm_parameter="existing_arsenal")
    else:
        bot.answer_inline_query(q.id, [],
                                is_personal=True,
                                cache_time=2,
                                switch_pm_text="Неверный формат запроса",
                                switch_pm_parameter="existing_arsenal")
Beispiel #10
0
def crystals_control(call):
    # print("crystals_control")
    # print(call)
    user = User(call.from_user.id, call.from_user.first_name, call.from_user.username)
    log.debug("%s is trying to control crystals check" % user)
    if not hlp.IsUserAdmin(user):
        bot.answer_callback_query(call.id, "Только офицеры могут управлять чеком!")
        log.error("Failed (not an admin)")
        return
    userChoice = call.data
    if userChoice == kb.CRYSTALS_CONTROL_OPTIONS[0]: # stop
        common.current_cryscheck.DoEndCryscheck()
        bot.edit_message_text(common.current_cryscheck.GetText(), inline_message_id=common.current_cryscheck.check_id, 
                              parse_mode="markdown")
        bot.answer_callback_query(call.id, "🏁 Чек завершен")
        return
    log.error("Crystals check not found!")
    bot.answer_callback_query(call.id, "Неверный чек по кри! Пожалуйста, создайте новый")
def command_stat_restore(m):
    """
    Restore whole current statistic from pickle file (command help part).
    """
    user = [m.from_user.id, m.from_user.username, m.from_user.first_name]
    log.debug("User %d (%s %s) is requested statistics restore" % (*user, ))
    if not hlp.IsInPrivateChat(m):
        common.bot.delete_message(m.chat.id, m.message_id)
        hlp.SendHelpWrongChat(m.from_user.id, "/statrestore",
                              "восстановить статистику из резервной копии",
                              True)
        return
    if not hlp.IsUserAdmin(m.from_user.id):
        hlp.SendHelpNonAdmin(m)
        return
    common.bot.send_message(
        m.from_user.id,
        "🗄 Чтобы восстановить статистику, пришлите файл резервной копии статистики в формате _.BAK_",
        parse_mode="markdown")
    def GetText(self):
        text = self.GetHeader()
        if self.is_rolling:
            text += "⏳ *Поиск:* %0.2d:%0.2d\n" % (self.time["roll"].hour,
                                                  self.time["roll"].minute)
        text += "❗ Бой начался ❗\n" * (self.is_started
                                       and not self.is_postponed)
        if self.is_postponed:
            text += "🛑 Бой"
            if self.is_started:
                text += " завершился "
            else:
                text += " отменен "
            text += "в %0.2d:%0.2d 🛑\n" % (self.time["end"].hour,
                                           self.time["end"].minute)

        if len(self.checks) + len(self.rages) + len(self.fasts) > 0:
            text += "\n" + "*%d идут:*\n" % (len(self.checks) +
                                             len(self.rages) + len(self.fasts))
        for user, count in self.checks.items():
            text += ICON_CHECK + " "
            text += (ICON_OFFICER + " ") * hlp.IsUserAdmin(user)
            text += self.GetNominatedPrefix(user)
            text += user.GetString()
            text += self.GetPlusNumericSuffix(count) + "\n"

        for user, count in self.rages.items():
            text += ICON_RAGE + " "
            text += (ICON_OFFICER + " ") * hlp.IsUserAdmin(user)
            text += self.GetNominatedPrefix(user)
            text += user.GetString()
            text += self.GetPlusNumericSuffix(count) + "\n"

        for user, count in self.fasts.items():
            text += ICON_FAST + " "
            text += (ICON_OFFICER + " ") * hlp.IsUserAdmin(user)
            text += self.GetNominatedPrefix(user)
            text += user.GetString()
            text += self.GetPlusNumericSuffix(count) + "\n"

        if len(self.arsenals) > 0:
            text += "\n" + "*%d в арс:*\n" % len(self.arsenals)
        for user, count in self.arsenals.items():
            text += ICON_ARS + " "
            text += (ICON_OFFICER + " ") * hlp.IsUserAdmin(user)
            text += self.GetNominatedPrefix(user)
            text += user.GetString()
            text += self.GetPlusNumericSuffix(count) + "\n"

        if len(self.thinking) > 0:
            text += "\n" + "*%d думают:*\n" % len(self.thinking)
        for user, _ in self.thinking.items():
            text += ICON_THINK + " "
            text += (ICON_OFFICER + " ") * hlp.IsUserAdmin(user)
            text += self.GetNominatedPrefix(user)
            text += user.GetString() + "\n"

        if len(self.cancels) > 0:
            text += "\n" + "*%d не идут:*\n" % len(self.cancels)
        for user, _ in self.cancels.items():
            text += ICON_CANCEL + " "
            text += (ICON_OFFICER + " ") * hlp.IsUserAdmin(user)
            text += self.GetNominatedPrefix(user)
            text += user.GetString() + "\n"

        if len(self.lates) > 0:
            text += "\n" + "*%d опоздали:*\n" % len(self.lates)
        for user, count in self.lates.items():
            text += ICON_LATE + " "
            text += (ICON_OFFICER + " ") * hlp.IsUserAdmin(user)
            text += self.GetNominatedPrefix(user)
            text += user.GetString()
            text += self.GetPlusNumericSuffix(count) + "\n"

        return text