Пример #1
0
    def get_players(self, nick_like):
        if nick_like == 'several':
            return None, [
                Player(nick='several1', phone='732422322'),
                Player(nick='several2', phone='732422323'),
                Player(nick='several3', phone='732422324')
            ]

        return None, []
Пример #2
0
    def player(self, name=None, phone=None, name_like=None):
        like = []
        for n in known_players:
            if name is not None and n == name:
                return [Player(nick=n, phone='79000000')]

            if name_like is not None and n.startswith(name_like):
                like.append(Player(nick=n, phone='79000000'))
        return like
Пример #3
0
    async def load_top_players(offset, count):
        res = await db.execute(Search.sql_load_top_players(offset, count))
        players = []
        for record in res:
            player_id, nick, phone, value, accuracy = record
            p = Player(player_id=player_id, nick=nick, phone=phone)
            p.set_rating(Rating(value, accuracy))
            players.append(p)

        return players
Пример #4
0
    async def post_nick(self, args: typing.Dict):
        logger.debug(f'post_nick {args}')
        request = valid_request_from_dict(AddNickRequest, args)

        if await self._search.load_player_by_nick(request.nick) is not None:
            raise RuntimeError(f'Player already exists: {request.nick}')

        p = Player(nick=request.nick, phone=request.phone)
        p.set_rating(self.ranking.initial_rating())
        await self._manage.save_player(p)
        return p.as_dict()
Пример #5
0
def test_add_4_known_players_and_set_scores():
    s = Session(backend=EmptyBackend(), text=Texts())

    for i in (('game', ''), ('game_player_confirm',
                             Player(nick='exists', phone='7823431')),
              ('game_player_confirm', Player(nick='exists', phone='7823432')),
              ('game_player_confirm', Player(nick='exists', phone='7823433')),
              ('game_player_confirm',
               Player(nick='exists', phone='7823434')), ('', 'not a number'),
              ('', '14'), ('', '15'), ('', '-1'), ('', '14'), ('', '13')):
        s.process_command(command=i[0],
                          user_input=i[1],
                          processing_message=sample_message)
Пример #6
0
    async def load_player_by_id(player_id):
        res = await db.execute(Search.sql_load_player_by_id(player_id))
        if len(res) == 0:
            logger.debug('load_player_by_nick None')
            return None

        player_id, nick, phone = res[0]
        p = Player(player_id=player_id, nick=nick, phone=phone)

        res = await db.execute(Search.sql_ratings(player_id))
        if len(res) > 0:
            p.set_rating(Rating(value=res[0][1], accuracy=res[0][2]))

        logger.debug(f'load_player_by_id {p}')
        return p
Пример #7
0
    async def load_players_nick_like(nick):
        res = await db.execute(Search.sql_load_players_nick_like(nick))

        players = []
        for record in res:
            player_id, nick, phone = record
            p = Player(player_id=player_id, nick=nick, phone=phone)

            res = await db.execute(Search.sql_ratings(player_id))
            if len(res) > 0:
                p.set_rating(Rating(value=res[0][1], accuracy=res[0][2]))

            players.append(p)

        logger.debug(f'load_players_nick_like {players}')
        return players
Пример #8
0
 def get_player(self, nick=None, phone=None):
     if nick == 'exists':
         return None, Player(nick=nick, phone=phone, rating=defaultRating)
     else:
         return {
             'error': f'Player not found: {nick}',
             'error_type': 'negative response'
         }, None
Пример #9
0
def test_send_contact_1_unknown_player():
    s = Session(backend=EmptyBackend(), text=Texts())

    for i in (('game', ''), ('game_player_confirm',
                             Player(nick='notexists', phone='7823435'))):
        s.process_command(command=i[0],
                          user_input=i[1],
                          processing_message=sample_message)
Пример #10
0
def test_add_1_known_and_1_unknown_player():
    s = Session(backend=EmptyBackend(), text=Texts())

    for i in (('game', ''), ('game_player_confirm',
                             Player(nick='exists',
                                    phone='7823434')), ('', 'unknown player'),
              ('game_new_player_phone', '79126632745')):
        s.process_command(command=i[0],
                          user_input=i[1],
                          processing_message=sample_message)
Пример #11
0
    def check_adding_player(self, user_input, processing_message=None):
        logger.debug('check_adding_player')
        if type(user_input) == Player:
            return (0, user_input)

        err, player = self.backend.get_player(nick=user_input)
        self._check_error_is_fatal(err, processing_message)
        if player is not None:
            return (0, player)
        else:
            return (1, Player(nick=user_input, phone=None))
def test_show_contacts():
    m = inline_query_text

    r = TelegramInteraction.parse_message(message=m, bot_name=bot_name)

    ti = TelegramInteraction()

    rsp = ti.show_contacts(
        as_reply=r.ids,
        contacts=[
            Player(nick='Jonny', phone='7123433'),
            Player(nick='B', phone='7123431'),
            Player(nick='Goode', phone='7123438')
        ]
    )

    assert rsp == TelegramOutMessage(
        method='answerInlineQuery',
        body={
            'inline_query_id': r.ids.inline_query_id,
            'results': json.dumps([{
                'type': 'contact',
                'id': '0',
                'phone_number': '7123433',
                'first_name': 'Jonny'
            },{
                'type': 'contact',
                'id': '1',
                'phone_number': '7123431',
                'first_name': 'B'
            },{
                'type': 'contact',
                'id': '2',
                'phone_number': '7123438',
                'first_name': 'Goode'
            }])
        }
    )
def test_parse_message_contact():
    m = message_contact

    r = TelegramInteraction.parse_message(message=m, bot_name=bot_name)
    assert r.ids.user_id == m['message']['from']['id']
    assert r.ids.message_id == m['message']['message_id']
    assert r.ids.inline_query_id is None
    assert r.ids.chat_id == m['message']['chat']['id']

    assert r.kind == 'message'
    assert r.command is None
    assert r.input.equal(
        Player(
            nick=m['message']['contact']['first_name'],
            phone=m['message']['contact']['phone_number']
        )
    )
Пример #14
0
async def test_all():
    g = None
    team_won = []
    team_lost = []
    try:
        # create players
        for i in range(0, 4):
            p = Player(nick=f'NewPlayer{i}')
            p.set_rating(Rating(value=1200, accuracy=0))
            await Manage.delete_player(p)
            await Manage.save_player(p)
            if i < 2:
                team_won.append(p)
            else:
                team_lost.append(p)

        g = Game(date=datetime.now(),
                 nicks_won=[p.nick for p in team_won],
                 nicks_lost=[p.nick for p in team_lost],
                 score_won=23,
                 score_lost=21)
        for p in team_won:
            g.set_rating_before(p.nick, p.get_rating())
            p.set_rating(Rating(value=1300, accuracy=0))
            g.set_rating_after(p.nick, p.get_rating())

        for p in team_lost:
            g.set_rating_before(p.nick, p.get_rating())
            p.set_rating(Rating(value=1100, accuracy=0))
            g.set_rating_after(p.nick, p.get_rating())

        await Manage.save_game(g)

        test_g = await Search.load_game_by_id(g.id)

        assert test_g.nicks_won == ['NewPlayer0', 'NewPlayer1']
        assert test_g.nicks_lost == ['NewPlayer2', 'NewPlayer3']

        for nick in test_g.nicks_won:
            assert test_g.rating_before(nick) == Rating(value=1200, accuracy=0)
            assert test_g.rating_after(nick) == Rating(value=1300, accuracy=0)

        for nick in test_g.nicks_lost:
            assert test_g.rating_before(nick) == Rating(value=1200, accuracy=0)
            assert test_g.rating_after(nick) == Rating(value=1100, accuracy=0)

        assert test_g.score_won == 23
        assert test_g.score_lost == 21

    finally:
        # clear
        await Manage.delete_game(g)
        for p in team_won + team_lost:
            await Manage.delete_player(p)
Пример #15
0
 async def get_players(self, args: typing.Dict):
     request = valid_request_from_dict(PlayersRequest, args)
     if request.nick_like == 'exists':
         return [Player(nick='exist').as_dict()]
     else:
         return []
Пример #16
0
def test_forget_player(server_credentials):
    host, port = server_credentials
    client = RestClient('localhost', 8080)
    err, response = client.forget_player(
        player=Player(nick='new', phone='731231213'))
    assert type(response).__name__ == 'Player'
Пример #17
0
 async def post_forget(self, args: typing.Dict):
     request = valid_request_from_dict(ForgetNickRequest, args)
     return Player(nick=request.nick).as_dict()
Пример #18
0
 async def post_nick(self, args: typing.Dict):
     request = valid_request_from_dict(AddNickRequest, args)
     if request.nick == 'new':
         return Player(nick='new', phone=request.phone).as_dict()
     else:
         raise RuntimeError(f'Player already exists: {request.nick}')
Пример #19
0
    def parse_message(message, bot_name='beachranks_bot'):
        kind = None
        input = None
        command = None
        ids = None

        if 'edited_message' in message or 'message' in message:
            kind = 'message'
            body = message['message']
            command = body['text'] if 'text' in body else None
            if 'contact' in body:
                input = Player(nick=body['contact']['first_name'],
                               phone=body['contact']['phone_number'])
            ids = MessageIds(user_id=body['from']['id'],
                             inline_query_id=None,
                             message_id=body['message_id'],
                             chat_id=body['chat']['id'])
        if 'inline_query' in message:
            kind = 'inline_query'
            body = message['inline_query']
            command = body['query']
            ids = MessageIds(user_id=body['from']['id'],
                             inline_query_id=body['id'],
                             message_id=None,
                             chat_id=None)
        if 'callback_query' in message:
            kind = 'callback_query'
            body = message['callback_query']
            command = body['data']
            ids = MessageIds(user_id=body['from']['id'],
                             inline_query_id=None,
                             message_id=None,
                             chat_id=body['message']['chat']['id'])

        if kind is None:
            print(f'ERROR: unknown message format {message}')
            return

        if command is not None:
            logger.log(0, f'parsing command \'{command}\'')
            m = re.search(f'^(@{bot_name} |)(\/\w*|)(@{bot_name}|)(\s*)(.*)',
                          command)

            if input is None and m is not None:
                input = m.group(5)

            if input is not None and len(input) == 0 and len(m.group(4)) == 0:
                input = None

            if m is not None:
                command = m.group(2)
                if command is not None:
                    command = re.search('\/(\w*)', command)
                    if command is not None:
                        command = command.group(1)

        logger.log(0, f'command \'{command}\' input \'{input}\'')

        # if something wrong, it throws exception

        return TelegramInMessage(kind=kind,
                                 command=command,
                                 input=input,
                                 ids=ids)
Пример #20
0
async def test_all():
    # create players
    team_won = []
    team_lost = []
    g = None
    try:
        for i in range(0, 4):
            p = Player(nick=f'NewPlayer{i}', phone=f'7916123456{i}')
            p.set_rating(Rating(value=1200 + i, accuracy=1))
            if i < 2:
                team_won.append(p)
            else:
                team_lost.append(p)

            await Manage.delete_player(p)
            await Manage.save_player(p)

        # find players LIKE
        players = await Search.load_players_nick_like('New')
        assert len(players) == 4

        players = await Search.load_players_nick_like('NewNotExists')
        assert len(players) == 0

        # game
        g = Game(date=datetime.now(), nicks_won=[p.nick for p in team_won], nicks_lost=[p.nick for p in team_lost],
                 score_won=15, score_lost=10)
        for p in team_won:
            g.set_rating_before(p.nick, p.get_rating())
            p.set_rating(Rating(value=p.get_rating().value + 100, accuracy=p.get_rating().accuracy))
            g.set_rating_after(p.nick, p.get_rating())
            await Manage.save_player(p)

        for p in team_lost:
            g.set_rating_before(p.nick, p.get_rating())
            p.set_rating(Rating(value=p.get_rating().value - 100, accuracy=p.get_rating().accuracy))
            g.set_rating_after(p.nick, p.get_rating())
            await Manage.save_player(p)

        await Manage.save_game(g)

        # find game
        res = await Search.games(player=team_lost[0])
        assert res[0].id == g.id

        # find games vs
        res = await Search.games(player=team_won[0], vs_players=[team_lost[0]])
        assert len(res) == 1
        assert res[0].id == g.id

        # not find games vs
        res = await Search.games(player=team_lost[0], vs_players=[team_lost[1]])
        assert len(res) == 0

        # find games with
        res = await Search.games(player=team_lost[1], with_players=[team_lost[0]])
        assert len(res) == 1
        assert res[0].id == g.id

        # not find games with
        res = await Search.games(player=team_lost[0], with_players=[team_won[1]])
        assert len(res) == 0

        # find games vs and with
        res = await Search.games(player=team_lost[0], vs_players=[team_won[0]], with_players=[team_lost[1]])
        assert len(res) == 1
        assert res[0].id == g.id

        # not find games vs
        res = await Search.games(player=team_lost[1], vs_players=[team_won[1]], with_players=[team_won[0]])
        assert len(res) == 0

        res = await Search.games(player=team_lost[0], vs_players=[team_lost[1]], with_players=[team_lost[1]])
        assert len(res) == 0

    finally:
        # clear
        await Manage.delete_game(g)
        for player in team_lost + team_won:
            await Manage.delete_player(player)
Пример #21
0
def steam(steam_id: int, key: str):
    # some hardcoded stuff for testing

    log.info("Starting import for player %d", steam_id)

    # Import player data
    response = get(
        "http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key="
        + str(key) + "&steamids=" + str(steam_id))
    player_details = response.json()

    player: Player = Player.get_or_create({
        'steam_id':
        steam_id,
        'name':
        player_details["response"]["players"][0]["personaname"]
    })[0]

    # Import all games with playtime > 0
    response = get(
        "http://api.steampowered.com/IPlayerService/GetOwnedGames/v0001/?key="
        + key + "&steamid=" + str(steam_id) + "&format=json")
    all_games = response.json()

    app_ids = {}
    # Put played games into list
    for game_detail in all_games["response"]["games"]:
        # if game_detail["playtime_forever"] > 0:
        app_ids[game_detail["appid"]] = True

    log.info("Fetching existing games..")

    # Retrieve all games, that are already in the graph
    games: NodeSet = Game.nodes.filter(steam_app_id__in=list(app_ids.keys()))

    # Make sure, the player exists before we continue
    player.save()

    log.info("Building relationships to existing games...")

    # Loop through existing games
    # ignore for now
    owned_games = list(map(lambda game: game.steam_app_id, player.games.all()))

    for game in games:
        # only add the game if its not already owned
        if game.steam_app_id not in owned_games:
            player.games.connect(game)

        # And remove it from the fetch list
        app_ids[game.steam_app_id] = False

    log.info("Fetching game info from non-existing games...")

    for app_id, need_to_fetch in app_ids.items():
        if need_to_fetch:
            log.info("Game %d not yet found in graph. Fetching from API...",
                     app_id)

            db.begin()

            # Fetch from Steam
            game = import_game(app_id, key)

            # make sure its saved before establishing the relationship
            game.save()

            player.games.connect(game)

            db.commit()

    log.info("Saving player...")
Пример #22
0
 async def get_player(self, args: typing.Dict):
     request = valid_request_from_dict(PlayerRequest, args)
     if request.nick == 'exists':
         return Player(nick='exist').as_dict()
     else:
         raise RuntimeError(f'Player not found: {request.nick}')
Пример #23
0
def test_get_player_found_2(server_credentials):
    host, port = server_credentials
    client = RestClient('localhost', 8080)
    err, response = client.get_player(Player(nick='exists'))
    assert type(response).__name__ == 'Player'