示例#1
0
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,
                              "Неверный чек боя! Пожалуйста, создайте новый")
示例#2
0
 def StepNext(self, repeat=False):
     if not repeat:
         self.step += 1
     if self.step in [
             1, 4, 8
     ]:  # check start, need to re-send message to bring it bottom
         bot.delete_message(self.userid, self.message_id).wait()
     self.DemonstrateStep()
     if self.step != 13:
         reply = kb.KEYBOARD_GUIDE_NEXT
     else:
         reply = kb.KEYBOARD_GUIDE_FINISH
     if self.step in [
             1, 4, 8
     ]:  # check start, need to re-send message to bring it bottom
         msg = bot.send_message(self.userid,
                                self.guideline[self.step],
                                parse_mode="markdown",
                                reply_markup=reply).wait()
         self.message_id = msg.message_id
     else:
         bot.edit_message_text(self.guideline[self.step],
                               self.userid,
                               self.message_id,
                               parse_mode="markdown",
                               reply_markup=reply)
示例#3
0
def guide_step(call):
    # print("guide_step")
    # print(call)
    message_id = call.inline_message_id
    user = [
        call.from_user.id, call.from_user.username, call.from_user.first_name
    ]
    userChoice = call.data
    log.debug("User %d (%s %s) is trying step next for his guide" % (*user, ))
    if user[0] not in user_guiding.keys():
        bot.send_message(
            user[0],
            "Бот был перезапущен.\nПожалуйста, начните обучение заного, используя команду /guide."
        )
        log.error("Bot has been restarted, need to start over")
        return
    if call.data == kb.GUIDE_OPTIONS[-1]:  # finish
        bot.delete_message(user[0], user_guiding[user[0]].message_id)
        del user_guiding[user[0]]
        log.debug("Guide finish successful")
    else:
        user_guiding[user[0]].StepNext()
        log.debug("Guide next step")
示例#4
0
 def DemonstrateStep(self):
     # sample users
     sampleUser1 = User(582244665, None, "Nagibator9000")
     sampleUser2 = User(187678932, "Alex", "alex_mech")
     if self.step in [1, 4, 8]:  # check start
         if self.demonstration:
             # FIX: do we need this?
             # if isinstance(self.demonstration, Battle):
             #     self.demonstration.DoEndBattle()
             # elif isinstance(self.demonstration, Arsenal):
             #     self.demonstration.DoEndArsenal()
             # else:
             #     self.demonstration.DoEndCheck()
             bot.delete_message(self.userid, self.demonstration.check_id)
             del self.demonstration
         if self.step == 1:  # battle check
             self.demonstration = Battle("09 15")
             self.demonstration.CheckUser(sampleUser1,
                                          cb.CHECK_CHECK_CALLBACK)
             reply = kb.KEYBOARD_CHECK
         elif self.step == 4:  # arsenal check
             self.demonstration = Arsenal("09 15")
             reply = kb.KEYBOARD_ARS
         elif self.step == 8:  # numbers check
             kb.SetupNumbersKeyboard(count=9)
             self.demonstration = NumbersCheck(9)
             reply = kb.KEYBOARD_NUMBERS
         msg = bot.send_message(self.userid,
                                self.demonstration.GetText(),
                                parse_mode="markdown",
                                reply_markup=reply).wait()
         self.demonstration.SetMessageID(msg.message_id)
     elif self.step in [3, 7, 12]:  # last check example step
         # undo all example changes in checks to let user try him/herself
         if isinstance(self.demonstration, Battle):
             # do not undo battle checks, let them be examples
             reply = kb.KEYBOARD_CHECK
         elif isinstance(self.demonstration, Arsenal):
             self.demonstration.Increment(sampleUser1,
                                          cb.ARS_CANCEL_CALLBACK)
             self.demonstration.Increment(sampleUser2,
                                          cb.ARS_CANCEL_CALLBACK)
             reply = kb.KEYBOARD_ARS
         else:
             # no need to undo numbers check, even thouh we cannot undo 500 (yet?)
             reply = kb.KEYBOARD_NUMBERS
             pass
         bot.edit_message_text(self.demonstration.GetText(),
                               self.userid,
                               self.demonstration.check_id,
                               parse_mode="markdown",
                               reply_markup=reply)
     elif self.step == 2:  # battle check [buttons example]
         self.demonstration.CheckUser(sampleUser2, cb.CHECK_ARS_CALLBACK)
         self.demonstration.CheckUser(sampleUser2, cb.CHECK_ARS_CALLBACK)
         bot.edit_message_text(self.demonstration.GetText(),
                               self.userid,
                               self.demonstration.check_id,
                               parse_mode="markdown",
                               reply_markup=kb.KEYBOARD_CHECK)
     elif self.step in [5, 6, 9, 10, 11]:
         if self.step == 5:  # arsenal check [buttons example]
             self.demonstration.Increment(sampleUser1,
                                          cb.ARS_36_CALLBACK,
                                          notify=False)
             reply = kb.KEYBOARD_ARS
         elif self.step == 6:  # arsenal check [rage example]
             self.demonstration.Increment(sampleUser2,
                                          cb.ARS_FULL_CALLBACK,
                                          notify=False)
             reply = kb.KEYBOARD_ARS
         elif self.step == 9:  # numbers check [buttons example]
             self.demonstration.CheckUser(sampleUser1,
                                          cb.NUMBERS_5_CALLBACK)
             reply = self.demonstration.keyboard
         elif self.step == 10:  # numbers check [empty example]
             self.demonstration.CheckUser(sampleUser1,
                                          cb.NUMBERS_5_CALLBACK)
             self.demonstration.CheckUser(sampleUser1,
                                          cb.NUMBERS_5_CALLBACK)
             reply = self.demonstration.keyboard
         elif self.step == 11:  # numbers check [500 example]
             self.demonstration.Do500()
             reply = self.demonstration.keyboard
         bot.edit_message_text(self.demonstration.GetText(),
                               self.userid,
                               self.demonstration.check_id,
                               parse_mode="markdown",
                               reply_markup=reply)
     elif self.step == 13:  # finish step
         self.demonstration.DoEndCheck()
         bot.delete_message(self.userid, self.demonstration.check_id)
         del self.demonstration
示例#5
0
 def Start(self):
     msg = bot.send_message(self.userid,
                            self.guideline[self.step],
                            parse_mode="markdown",
                            reply_markup=kb.KEYBOARD_GUIDE_START).wait()
     self.message_id = msg.message_id
示例#6
0
def command_screens_ocr(m):
    # print("command_screens_ocr")
    # print(m)
    # do not resrtict sending screens into war chat, but process only ones sent privately
    user = [m.from_user.id, m.from_user.username, m.from_user.first_name]
    log.info("User %d (%s %s) is trying to process guild screens" % (*user, ))
    if not hlp.IsInPrivateChat(m):
        log.error("Failed: not in private chat. Ignored")
        return
    screen_params = {
        "id": m.photo[-1].file_id,
        "mid": m.message_id,
        "group": m.media_group_id,
        "user": m.from_user.id,
    }
    is_new_screens = False
    if screen_params["user"] not in screen_list:
        # if this user is new - create key for user
        log.debug("First user request, creating new user entry")
        screen_list[screen_params["user"]] = ScreenList(
            screen_params["group"], screen_params["user"])
        is_new_screens = True
    elif screen_params["group"] == None or \
         screen_params["group"] != screen_list[screen_params["user"]].media_group_id:
        # if user sent new screens album - create new ScreenList for this group replacing the old one
        log.debug("New screens album, creating new entry for user")
        del screen_list[screen_params["user"]]
        screen_list[screen_params["user"]] = ScreenList(
            screen_params["group"], screen_params["user"])
        is_new_screens = True
    if (is_new_screens):
        # send initial message for new request
        message = bot.send_message(
            screen_params["user"],
            screen_list[screen_params["user"]].GetText() +
            "\n_(обработка...)_",
            parse_mode="markdown").wait()
        # save message id
        screen_list[screen_params["user"]].SetMessageID(message.message_id)
    # download screen
    downloaded = bot.download_file(
        bot.get_file(screen_params["id"]).wait().file_path).wait()
    # save screen to file with name == id
    with open(screen_params["id"], 'wb') as screen_file:
        screen_file.write(downloaded)
        screen_file.close()

    # process image
    bot.edit_message_text(
        screen_list[screen_params["user"]].GetText() + "\n_(обработка...)_",
        chat_id=screen_params["user"],
        message_id=screen_list[screen_params["user"]].GetMessageID(),
        parse_mode="markdown")
    # send typing status to user to make him wait a bit
    bot.send_chat_action(screen_params["user"], 'typing')
    # process image
    names = ocr_core(screen_params["id"])
    # delete downloaded file
    os.remove(screen_params["id"])
    # update screen list with parsed nicknames
    screen_list[screen_params["user"]].AddScreen(screen_params["mid"], names)
    # update list message for user
    bot.edit_message_text(
        screen_list[screen_params["user"]].GetText(),
        chat_id=screen_params["user"],
        message_id=screen_list[screen_params["user"]].GetMessageID(),
        parse_mode="markdown")
示例#7
0
 def BattleStartNotifyActiveUsers(self, except_user=None):
     activeUsers = self.GetActiveUsers()
     for user in activeUsers:
         # do not notify user if checked for rage or is one preseed the button
         if user not in self.rages and user != except_user:
             bot.send_message(user._id, ICON_SWORDS + " Бой начинается!")
示例#8
0
 def BattleRollNotifyActiveUsers(self, except_user=None):
     activeUsers = self.GetActiveUsers()
     for user in activeUsers:
         # do not notify user if checked for rage or is one preseed the button
         if user not in self.rages and user != except_user:
             bot.send_message(user._id, ICON_ROLL + " Крутит!")
示例#9
0
def battle_check_user(call):
    # print("battle_check_user")
    # print(call)
    message_id = call.inline_message_id
    user = User(call.from_user.id, call.from_user.first_name,
                call.from_user.username)
    userChoice = call.data
    log.debug("%s is trying to vote for battle (%s)" %
              (user, userChoice.replace(cb.CHECK_CALLBACK_PREFIX, "")))
    if common.current_battle and message_id == common.current_battle.check_id:
        is_guide_training = False
        battle_object = common.current_battle
    elif user._id in common.user_guiding.keys(
    ):  # guide battle example workaround
        is_guide_training = True
        if common.user_guiding[user._id].IsTrainingStage(
        ):  # using check is allowed only at several steps of guide
            battle_object = common.user_guiding[user._id].demonstration
        else:
            log.error("Not at training stage, aborting")
            bot.answer_callback_query(
                call.id, "На данный момент использование чека недоступно")
            return
    else:
        battle_object = None
    if battle_object:
        ret = battle_object.CheckUser(user, userChoice)
        if ret or userChoice == cb.CHECK_LATE_CALLBACK:
            markup = kb.KEYBOARD_CHECK
            if battle_object.is_rolling:
                markup = kb.KEYBOARD_CHECK_ROLLED
            elif battle_object.is_started:
                markup = kb.KEYBOARD_LATE
            if is_guide_training:
                bot.edit_message_text(battle_object.GetText(),
                                      user._id,
                                      battle_object.check_id,
                                      parse_mode="markdown",
                                      reply_markup=markup)
            else:
                bot.edit_message_text(battle_object.GetText(),
                                      inline_message_id=message_id,
                                      parse_mode="markdown",
                                      reply_markup=markup)
            bot.answer_callback_query(call.id,
                                      battle_object.GetVotedText(userChoice))
            if userChoice == cb.CHECK_LATE_CALLBACK and ret and not is_guide_training:
                text = ICON_LATE + " %s пришел на бой!\n" % user.GetString()
                bot.send_message(common.warchat_id,
                                 text,
                                 parse_mode="markdown",
                                 disable_notification=True)
                log.debug("Battle user late notification posted")
        else:
            log.error("Failed")
            bot.answer_callback_query(
                call.id, "Вы уже проголосовали (%s)" %
                userChoice.replace(cb.CHECK_CALLBACK_PREFIX, ""))
        return
    log.error("Battle not found!")
    bot.answer_callback_query(call.id,
                              "Неверный чек боя! Пожалуйста, создайте новый")