def handle(self, state_changer: StateChanger,
               request_container: RequestContainer):
        update = request_container.request.update
        message_text = update.message.text if update.message else None

        self.counter += 1
        request_container.add_template_reply(
            Template.constant(MessageContent('StateA handled this request')),
            {'counter': self.counter})

        if message_text == 'SwitchB':
            state_changer.change(StateB(), request_container)
        elif message_text == 'SwitchDefault':
            state_changer.change(None, request_container)
    def test_without_buttons(self):
        text = 'Hello, world!'
        template = Template.constant(MessageContent(text=text))

        bot_mock = Mock(spec=Bot)
        request = RequestFaker.message()
        ResponseReplyTemplate(template).send(bot_mock, request)

        bot_mock.send_message.assert_called_once()
        call_args = bot_mock.send_message.call_args
        args, kwargs = call_args

        self.assertEqual(args, (request.update.message.from_user.id, text))
        self.assertIsNone(kwargs.get('reply_markup'))
        self.assertEqual(kwargs['parse_mode'], 'html')
    def create_message(self, args: dict) -> MessageContent:
        user_id = args['user_id']
        sol1: Solution = args['sol1']
        sol2: Solution = args['sol2']
        or1, or2 = args['old_rating']
        nr1, nr2 = args['new_rating']
        verdict: GameVerdict = args['verdict']
        outcome = verdict.outcome

        def format_solution(s: Solution):
            return '👤{}'.format(
                s.name_as_html) if s.creator_id == user_id else s.name_as_html

        # Кто с кем (своё жирное)
        text = '<b>⚔️ Состоялась дуэль! ⚔️</b>\n'
        text += format_solution(sol1) + ' <i>VS</i> ' + format_solution(
            sol2) + '\n\n'

        # Кто победил
        if verdict.outcome == GameOutcome.FIRST_WIN:
            text += '<b>Победитель: </b> игрок 1, ' + format_solution(sol1)
        elif verdict.outcome == GameOutcome.TIE:
            text += '<b>Ничья</b>'
        else:
            text += '<b>Победитель: </b> игрок 2, ' + format_solution(sol2)
        text += '\n\n'

        # Изменение рейтинга
        text += '<b>Рейтинг</b>: '
        if or1 == nr1 and or2 == nr2:
            text += 'без изменений'
        else:

            def format_rating_change(old_r, new_r):
                if old_r is not None and new_r is not None:
                    delta = new_r - old_r
                    delta_str = ('+' + str(delta)) if delta > 0 else str(delta)
                    return f'{old_r} ➡️ {new_r} ({delta_str})'
                else:
                    return str(new_r)

            text += '\n'
            text += '<b>Игрок 1: </b>' + format_rating_change(or1, nr1) + '\n'
            text += '<b>Игрок 2: </b>' + format_rating_change(or2, nr2) + '\n'

        return MessageContent(text)
    def test_with_buttons(self):
        text = 'Hello, world!'
        template = Template.constant(MessageContent(text=text, buttons=[
            ['A', 'B'], ['C', 'D', 'E']
        ]))

        bot_mock = Mock(spec=Bot)
        request = RequestFaker.message()
        ResponseReplyTemplate(template).send(bot_mock, request)

        bot_mock.send_message.assert_called_once()
        call_args = bot_mock.send_message.call_args
        args, kwargs = call_args

        self.assertEqual(args, (request.update.message.from_user.id, text))
        self.assertIsInstance(kwargs['reply_markup'], ReplyKeyboardMarkup)
        self.assertEqual(kwargs['reply_markup'].keyboard, [['A', 'B'], ['C', 'D', 'E']])
        self.assertEqual(kwargs['parse_mode'], 'html')
    def create_message(self, args: dict) -> MessageContent:
        text = '<b>Игры:</b>\n\n'
        games: List[Game] = args['games']
        solutions: List[Solution] = args['solutions']
        game_name_to_solution = dict(
            map(lambda sol: (sol.game_name, sol), solutions))

        for game in games:
            text += game.display_name + ": "

            solution: Solution = game_name_to_solution.get(game.name)
            if solution is not None:
                text += solution.name_rating_as_html
            else:
                text += '<i>[нет решения]</i>'

            text += ', /i_' + game.name
            text += '\n'

        return MessageContent(text, buttons.default_set)
    def create_message(self, args: dict) -> MessageContent:
        game: Game = args['game']
        top_solutions: List[Solution] = args['top']
        solution: Optional[Solution] = args['solution']

        text = f'<b>🕹 {game.display_name}</b>\n\n'
        if solution:
            text += solution.name_rating_as_html + '\n'
            text += 'Язык: ' + solution.language_name + '\n'
        else:
            text += '<i>Решения нет</i>\n'

        text += '\n'
        for i, s in enumerate(top_solutions):
            index = i + 1
            text += '<b>#{}</b> {}\n{}\n'.format(index, s.name_rating_as_html,
                                                 s.create_link().to_command())

        return MessageContent(
            text, buttons.solution_actions_set
            if solution else buttons.no_solution_actions_set)
示例#7
0
 def create_message(self, args: dict) -> MessageContent:
     return MessageContent(self.fmt.format(**args), self.buttons)
示例#8
0
 def constant_html(text: str):
     return Template.constant(MessageContent(text))
 def create_message(self, args: dict) -> MessageContent:
     button_rows = group_by_k(
         3, list(map(lambda l: l.display_name, args['list'])))
     return MessageContent('Выбери язык твоего решения.', button_rows)
from app.bot import buttons
from app.bot.mvc import Template, MessageContent
from app.core import Game, GameOutcome
from app.core.checksys import GameVerdict
from app.model import Solution
from app.util import group_by_k

err_no_such_game = Template.constant_html('Такая игра не существует')
err_no_solution = Template.from_string_format(
    'У тебя нет решения для игры 🕹{name}!')

start_message = Template.constant(
    MessageContent(
        '''
Добро пожаловать, разработчик!

Здесь ты можешь показать всем свои навыки в разработке ИИ для пошаговых игр.
''', buttons.default_set))

main_message = Template.constant(
    MessageContent('''
Что ты хочешь узнать?
''', buttons.default_set))

about_bot = Template.constant(
    MessageContent(
        '''
<b>❓ О боте</b>

Этот бот сделан в качесте проекта по курсу проектирования ПО.
''', buttons.default_set))