コード例 #1
0
    async def summoner_info(self, ctx, passed_name: str = None):
        """Pass a name for that summoner's info, no name for your own if registered. """
        if passed_name is None:
            summoner_name_dict = summoner_names.find_one(
                {'discord_name': ctx.author.name})
            summoner = Summoner(name=summoner_name_dict['summoner_name'],
                                region=region)
        else:
            # currently, except not being reached
            try:
                summoner = Summoner(name=passed_name, region=region)
                summoner.level  # simple call to api to trigger exception if not found
            except NotFoundError:
                await ctx.send("Summoner could not be found")
                return

        formatted_summoner_name = summoner.name.replace(' ', '%20')

        # create embed object
        embed = discord.Embed(
            title=f'{summoner.name}\'s Summoner Stats',
            url=f'https://na.op.gg/summoner/userName={formatted_summoner_name}',
            description=
            f'Display of summoner information, click on link for op.gg page.')

        # Add summoner icon thumbnail to embed
        embed.set_thumbnail(url=summoner.profile_icon.url)

        # level field
        embed.add_field(name="Level", value=summoner.level)

        # TO DO: Add prettified champ masteries to the embed

        await ctx.send(embed=embed)
コード例 #2
0
def test_summonersrift_map():
    summoner = Summoner(name='Kalturi', region='NA')
    match = summoner.match_history(queues=[Queue.ranked_solo_fives])[0]
    for frame in match.timeline.frames:
        for event in frame.events:
            if event.type == 'CHAMPION_KILL':
                SummonersRiftArea.from_position(event.position)
コード例 #3
0
ファイル: league.py プロジェクト: Snowcola/roosterbot
    async def game(self, ctx, person):
        """Shows the current game and who is in it"""
        try:
            player = Summoner(name=person, region="NA")
            match = player.current_match()
            gametype = match.queue
            blue_team = match.blue_team().participants
            red_team = match.red_team().participants
            duration = match.duration

            data = []
            data.append(["Red Team", "Blue Team"])

            for x in range(len(red_team)):
                data.append(
                    [red_team[x].summoner.name, blue_team[x].summoner.name])

            table = SingleTable(data)
            response = f""" Current Game:

            **{person} is {duration} into a {gametype.value} game**\n\n```{table.table}```"""

            await self.bot.send_message(ctx.message.channel, response)

        except ValueError as e:
            await self.bot.say(f"Something went wrong there :(")
            print(e)
コード例 #4
0
def collectMatches():
    summoner = Summoner(name="Ung5r",
                        region="NA")  # A default summoner to pull matches from
    patchNo = Patch.from_str('8.2', region="NA")

    # Create some sorted lists to store the IDs of players and matches being analyzed.
    # Match info can only be pulled on a player basis so we'll have to pull each player
    # from a match to then get further match info.
    unpulledSummonerIDS = SortedList([summoner.id])
    pulledSummonerIDS = SortedList()
    unpulledMatchIDS = SortedList()
    pulledMatchIDS = SortedList()

    matchesList = []

    while unpulledSummonerIDS and len(pulledMatchIDS) < 5000:
        newSummonerID = random.choice(unpulledSummonerIDS)
        try:
            newSummoner = Summoner(id=newSummonerID, region="NA")
        except:
            print("Unable to retrieve new summoner, retrying in 10s")
            time.sleep(10)
            newSummoner = Summoner(id=newSummonerID, region="NA")
        matches = filterHistory(newSummoner, patchNo)
        try:
            unpulledMatchIDS.update([
                match.id for match in matches
                if match.id not in unpulledMatchIDS
            ])
        except:
            print("Unable to add to unpulled matches, retrying in 10s")
            time.sleep(10)
            unpulledMatchIDS.update([
                match.id for match in matches
                if match.id not in unpulledMatchIDS
            ])
        unpulledSummonerIDS.remove(newSummonerID)
        pulledSummonerIDS.add(newSummonerID)

        while unpulledMatchIDS:
            newMatchID = random.choice(unpulledMatchIDS)
            try:
                newMatch = Match(id=newMatchID, region="NA")
            except:
                print("Unable to retrieve new match, retrying in 10s")
                time.sleep(10)
                newMatch = Match(id=newMatchID, region="NA")
            for participant in newMatch.participants:
                if participant.summoner.id not in pulledSummonerIDS and participant.summoner.id not in unpulledSummonerIDS:
                    unpulledSummonerIDS.add(participant.summoner.id)
            unpulledMatchIDS.remove(newMatchID)
            if newMatchID not in pulledMatchIDS:
                pulledMatchIDS.add(newMatchID)

    # Populate the list of matches by match ID
    for entry in pulledMatchIDS:
        matchesList.append(kass.get_match(id=entry, region="NA"))

    return matchesList
コード例 #5
0
ファイル: mastery_table.py プロジェクト: jchristgit/ducky
    async def summoner_add(self, ctx: commands.Context, region: as_region, *,
                           name: str) -> None:
        """Add a summoner to the mastery sidebar."""

        summoner = Summoner(region=region, name=name)
        summoner_id = await asyncio.get_event_loop().run_in_executor(
            None, lambda: summoner.id)  # noblock event loop
        async with db_cursor(self.dsn) as cursor:
            query = ("INSERT INTO summoners (guild_id, platform, id) "
                     "VALUES (%s, %s, %s) "
                     "ON CONFLICT DO NOTHING")
            await cursor.execute(
                query,
                (
                    ctx.message.guild.id,
                    region.platform.value.casefold(),
                    summoner_id,
                ),
            )

            if cursor.rowcount:
                print(
                    f"{ctx.message.author} added {name} on {region.value} for {ctx.message.guild.name}"
                )
                await ctx.channel.send(":ok_hand: summoner added")
            else:
                await ctx.channel.send(":x: summoner already added")
コード例 #6
0
ファイル: league.py プロジェクト: Snowcola/roosterbot
    async def matches(self, ctx, person, num_games: int = 10):
        """Gets match history of a summoner

        Usage:
            !matches snowcola 15
        """
        summoner = Summoner(name=person, region="NA")
        match_history = summoner.match_history
        match_history = match_history[:num_games]
        await self.bot.say("Digging through the chronicles of Runeterra...")

        data = []
        data.append(
            ["W/L", "Champion", "K/D/A", "Multikill", "CS", "Gold Earned"])
        for match in match_history:
            result = ""
            champ = match.participants[summoner].champion.name
            stats = match.participants[summoner].stats
            k = stats.kills
            d = stats.deaths
            a = stats.assists
            spree = self.convertMultikill(stats.largest_multi_kill)
            cs = stats.total_minions_killed + stats.neutral_minions_killed
            gold = "{:,}".format(stats.gold_earned)

            if match.participants[summoner].team.win:
                result = "Win "
            else:
                result = "Loss"
            data.append([result, champ, f"{k}/{d}/{a}", spree, cs, gold])

        table = SingleTable(data)

        await self.bot.say(f"ahh here it is! \n\n```{table.table}```")
コード例 #7
0
 async def set(self, ctx, region: str):
     """Set your server's default region"""
     try:
         Summoner(name="", region=region)
     except ValueError:
         embed = discord.Embed(
             title="Error!",
             description="{0} is not a valid region!".format(region),
             colour=0xCA0147)
         utils.footer(ctx, embed)
         await ctx.send("", embed=embed)
         return
     db = database.Database('guilds.db')
     try:
         region_found = db.find_entry(ctx.guild.id)
         db.close_connection()
         embed = discord.Embed(
             title="Error!",
             description="{0} is already {1}'s default region!".format(
                 region_found, ctx.guild.name),
             colour=0xCA0147)
         utils.footer(ctx, embed)
         await ctx.send("", embed=embed)
     except TypeError:
         db.add_entry(ctx.guild.id, region)
         db.close_connection()
         embed = discord.Embed(
             title="Success!",
             description="{0} set as {1}'s default region!".format(
                 region, ctx.guild.name),
             colour=0x1AFFA7)
         utils.footer(ctx, embed)
         await ctx.send("", embed=embed)
コード例 #8
0
ファイル: explore.py プロジェクト: traiyn/abcdtft
def main():

    summoner = input("Please enter a summoner's name: ")
    with open('secret.json') as f:
        api_key = json.load(f)['riot-key']

    cass.set_riot_api_key(api_key)
    summoner = cass.get_summoner(name=summoner, region=REGION)
    match_history = Summoner(name=summoner.name, region=REGION).match_history(
        begin_time=Patch.from_str("9.1", region=REGION).start)
    match_info_rows = []
    for match in match_history:
        match_info = {}
        match_info['id'] = match.id
        match_info['queue_id'] = match.queue.id
        match_info['patch'] = match.patch
        match_info['creation'] = match.creation
        match_info['champion'] = match.participants[summoner].champion.name
        match_info['win'] = match.participants[summoner].team.win
        match_info['kills'] = match.participants[summoner].stats.kills
        match_info['deaths'] = match.participants[summoner].stats.deaths
        match_info['assists'] = match.participants[summoner].stats.assists
        match_info['kda'] = match.participants[summoner].stats.kda
        match_info_rows.append(match_info)

    match_history_df = pd.DataFrame(match_info_rows)
    match_history_df.set_index('id')
    # all_champions = cass.Champions(region=REGION)
    # sub_test(api_key)
    print(match_history_df)

    filename = summoner + '_matchhistory.csv'
    filepath = os.path.join('data', filename)

    match_history_df.to_csv(filepath)
コード例 #9
0
    async def check_verification(self, guild, author, summoner_name,
                                 expected_verification):
        try:
            summoner = Summoner(name=summoner_name)
            verification_string = summoner.verification_string
            summoner_name = summoner.name
            if (expected_verification == verification_string):
                await author.send(self.command_texts["correctVerification"])
                await self.discord_service.change_member_nickname(
                    author, summoner_name)
                await self.discord_service.give_role(
                    guild, author, self.settings["verified_role"])
                self.verify_pending.remove(author)
            else:
                wrong_text = self.command_texts["wrongVerification"].format(
                    verification_string, expected_verification)
                await author.send(wrong_text)
                self.verify_pending.remove(author)
                await self.wait_and_verify(guild, author, summoner_name,
                                           expected_verification)

        except APIRequestError as e:
            await author.send(str(e))
            self.verify_pending.remove(author)
        except Exception as e:
            await author.send(
                self.command_texts["noVerification"].format(summoner_name))
            self.verify_pending.remove(author)
            await self.wait_and_verify(author, author, summoner_name,
                                       expected_verification)
コード例 #10
0
    async def masteryrole(self, ctx: commands.Context, region: as_region, *,
                          name: str) -> None:
        """Assign a role for your mastery score."""

        async with db_cursor(self.dsn) as cursor:
            await cursor.execute(
                "SELECT id FROM champions WHERE guild_id = %s",
                (ctx.message.guild.id, ))
            champion_row = await cursor.fetchone()
            if champion_row is None:
                await ctx.channel.send(
                    ":x: no champion configured for this guild")
                return

        champion = Champion(id=champion_row[0], region=region)
        summoner = Summoner(name=name, region=region)
        masterygetter = functools.partial(
            cassiopeia.get_champion_mastery,
            champion=champion,
            summoner=summoner,
            region=region,
        )
        loop = asyncio.get_event_loop()
        mastery = await loop.run_in_executor(None, masterygetter)
        matching_role = find_matching_role(mastery.points)
        print(f"giving {ctx.message.author} role {matching_role} for "
              f"{mastery.points:,} points on {name} in {region.value}")
        await ctx.message.author.add_roles(
            discord.Object(id=matching_role),
            reason=
            f"mastery score of {mastery.points:,} on {name} in {region.value}",
        )
        await ctx.send(":ok_hand: role added!")
コード例 #11
0
def main():
    # Pull the data
    champion_roles = pull_data()

    # Use individual champions
    darius = Champion(name='Darius', region='NA')
    leesin = Champion(name='Lee Sin', region='NA')
    syndra = Champion(name='Syndra', region='NA')
    draven = Champion(name='Draven', region='NA')
    braum = Champion(name='Braum', region='NA')
    champions = [darius, leesin, syndra, draven, braum]

    roles = get_champion_roles(champions,
                               top=darius,
                               champion_roles=champion_roles)
    print({role.name: champion.name for role, champion in roles.items()})

    # Use Cassiopeia's match.blue_team and/or match.red_team objects
    summoner = Summoner(name="Kalturi", region="NA")
    for match in summoner.match_history:
        roles = get_team_roles(match.blue_team, champion_roles)
        print({role.name: champion.name for role, champion in roles.items()})

        roles = get_team_roles(match.red_team, champion_roles)
        print({role.name: champion.name for role, champion in roles.items()})

        break
コード例 #12
0
def get_spectator_matches(df, champions_data):
    featured_matches = cass.get_featured_matches(region="EUW")
    starting_patch = Patch.from_str("9.16", region="EUW")

    for new_match in featured_matches:
        if new_match.queue.id == 420 and df[df['match_id'] ==
                                            new_match.id].shape[0] == 0:
            match = {'match_id': int(new_match.id)}
            participants = new_match.blue_team.participants + new_match.red_team.participants
            for (p, id) in zip(participants, range(1, 11)):
                current_summoner = Summoner(id=p.summoner.id, region="EUW")

                match[f'{id}_kda'], match[f'{id}_winrate'] = get_average_kda(
                    current_summoner, starting_patch,
                    new_match.creation.shift(minutes=-10), p.champion.id)

                cm = cass.get_champion_mastery(champion=p.champion.id,
                                               summoner=current_summoner,
                                               region="EUW")
                match[f'{id}_cm_points'] = int(cm.points)

                champion_data = champions_data[champions_data['name'] ==
                                               p.champion.name].winrate
                match[f'{id}_champion_winrate'] = champion_data.iloc[0]

            match_series = pd.Series(match)

            df = df.append(match_series, ignore_index=True)
            df.to_csv('spectator_data.csv', index=None, header=True)
コード例 #13
0
def print_summoner(name: str, region: str):
    summoner = Summoner(name=name, region=region)
    print("Name:", summoner.name)
    print("ID:", summoner.id)
    print("Account ID:", summoner.account_id)
    print("Level:", summoner.level)
    print("Revision date:", summoner.revision_date)
コード例 #14
0
 async def update(self, ctx, region: str):
     """Update your server's default region"""
     try:
         Summoner(name="", region=region)
     except ValueError:
         embed = discord.Embed(
             title="Error!",
             description="{0} is not a valid region!".format(region),
             colour=0xCA0147)
         utils.footer(ctx, embed)
         await ctx.send("", embed=embed)
         return
     db = database.Database('guilds.db')
     try:
         db.find_entry(ctx.guild.id)
         db.update_entry(ctx.guild.id, region)
         db.close_connection()
         embed = discord.Embed(
             title='Success!',
             description="Set {0} as {1}'s default region!".format(
                 region, ctx.guild.name),
             colour=0x1AFFA7)
         utils.footer(ctx, embed)
         await ctx.send("", embed=embed)
     except TypeError:
         db.close_connection()
         embed = discord.Embed(
             title="Error!",
             description="A default region for this server has not been set!",
             colour=0xCA0147)
         utils.footer(ctx, embed)
         await ctx.send("", embed=embed)
コード例 #15
0
ファイル: league.py プロジェクト: Snowcola/roosterbot
    async def winrate(self, ctx, person):
        """Gets winrate for a player over the past week"""
        summoner = Summoner(name=person, region="NA")
        await self.bot.say("It will take me a moment to do the math...")

        wins = 0

        last_week = datetime.datetime.now() - datetime.timedelta(weeks=1)
        year = last_week.year
        month = last_week.month
        day = last_week.day
        matchhistory = cass.MatchHistory(summoner=summoner,
                                         begin_time=arrow.Arrow(
                                             year, month, day),
                                         end_time=arrow.now())

        total_games = len(matchhistory)

        for match in matchhistory:
            if match.participants[summoner].team.win:
                wins += 1

        winrate = round(wins / total_games * 100)

        await self.bot.send_message(
            ctx.message.channel,
            f"{person} has a win rate of **{winrate}%** with {wins} wins over {total_games} games this week. "
        )
コード例 #16
0
def test_match_history_7():
    region = "NA"
    summoner = Summoner(name="Kalturi", region=region)
    match_history = cass.get_match_history(summoner=summoner,
                                           seasons={Season.season_8},
                                           queues={Queue.ranked_solo_fives},
                                           begin_time=arrow.get(2016, 12, 1))
    assert len(match_history) > 0
コード例 #17
0
ファイル: league.py プロジェクト: Snowcola/roosterbot
    async def rank(self, ctx, person):
        """Gets the current rank of a summoner"""

        summoner = Summoner(name=person, region="NA")
        positions = summoner.league_positions
        rank = f"{positions.fives.tier} {positions.fives.division}"

        await self.bot.say(f"{person} is in **{rank}**")
コード例 #18
0
def print_newest_match(name: str, region: str):
    summoner = Summoner(name=name, region=region)

    match_history = summoner.match_history
    match = match_history[0]
    print('Match ID:', match.id)

    print(match.timeline.frame_interval)
コード例 #19
0
def test_match_history_3():
    region = "NA"
    summoner = Summoner(name="Kalturi", region=region)
    match_history = cass.get_match_history(summoner=summoner,
                                           queues={Queue.ranked_solo_fives},
                                           begin_time=arrow.get(2017, 2, 7),
                                           end_time=arrow.get(2017, 2, 14))
    assert len(match_history) == 16
コード例 #20
0
def test_from_match():
    summoner = Summoner(name="Kalturi", region="NA")
    match_history = summoner.match_history

    match = match_history[0]
    timeline = match.timeline
    for frame in timeline.frames[:-1]:
        for pf in frame.participant_frames.values():
            print(pf.position.location)
コード例 #21
0
    async def display_game_summary(message: Message) -> None:
        summoner_name = re.compile("/gamesummary (.*)").match(
            message.content).group(1)
        summoner = Summoner(name=summoner_name, region="NA")
        player_match_history = summoner.match_history()

        output = "```"
        output += "{:>18} {:>14} {:>14} {:>15} {:>16}".format(
            "SUMMONER", "KILLS", "DEATHS", "ASSISTS", "KDA") + "\n"
        output += LeagueClientHelper.display_team_info(
            player_match_history[0].blue_team.participants)
        output += "----------------------------------------------------------------------------------\n"
        output += LeagueClientHelper.display_team_info(
            player_match_history[0].red_team.participants)

        output += "```"
        await message.channel.send(output)
        Logger.log('Outputting Game Summary for: {summoner_name}')
コード例 #22
0
    async def display_game_pregame_summary(message: Message) -> None:
        summoner_name = re.compile("/pregamesummary (.*)").match(
            message.content).group(1)
        summoner = Summoner(name=summoner_name, region="NA")
        player_match_history = summoner.current_match()

        output = "```"
        output += "{:>18} {:>14} {:>14} {:>15}".format(
            "SUMMONER", "CHAMPION", "SOLO RANK", "FLEX RANK") + "\n"
        output += LeagueClientHelper.display_team_pregame_info(
            player_match_history.blue_team.participants)
        output += "----------------------------------------------------------------------------------\n"
        output += LeagueClientHelper.display_team_pregame_info(
            player_match_history.red_team.participants)

        output += "```"
        await message.channel.send(output)
        Logger.log('Outputting Game Summary for: {summoner_name}')
コード例 #23
0
 async def display_best_champs(message: Message) -> None:
     summoner_name = message.content[12:]
     bestchamps_message = "**Best champs for " + summoner_name + ":**\n"
     summoner = Summoner(name=summoner_name, region="NA")
     good_with = summoner.champion_masteries.filter(
         lambda cm: cm.level >= 5)
     bestchamps_message += ", ".join([cm.champion.name for cm in good_with])
     await message.channel.send(bestchamps_message)
     Logger.log("Outputting Best Champ")
コード例 #24
0
def test_match_history_1():
    region = "NA"
    summoner = Summoner(name="Kalturi",
                        account=34718348,
                        id=21359666,
                        region=region)
    match_history = cass.get_match_history(summoner=summoner,
                                           queues={Queue.ranked_solo_fives})
    assert len(match_history) > 400
コード例 #25
0
def test_match_history_2():
    region = "NA"
    summoner = Summoner(name="Kalturi", region=region)
    match_history = cass.get_match_history(
        summoner=summoner,
        seasons={Season.season_8},
        queues={Queue.ranked_solo_fives},
        begin_time=arrow.now().shift(days=-140),
        end_time=arrow.now())
    assert len(match_history) > 0
コード例 #26
0
def get_spectator_matches():
    featured_matches = cass.get_featured_matches("NA")
    for match in featured_matches:
        print(match.region, match.id)

    match = featured_matches[0]
    a_summoner_name = match.blue_team.participants[0].summoner_name
    summoner = Summoner(name=a_summoner_name, region=match.region)
    current_match = summoner.current_match
    print(current_match.map)
コード例 #27
0
def print_summoner(name: str, region: str):
    summoner = Summoner(name=name, region=region)
    print("Name:", summoner.name)
    print("ID:", summoner.id)
    print("Account ID:", summoner.account.id)
    print("Level:", summoner.level)
    print("Revision date:", summoner.revision_date)
    print("Profile icon ID:", summoner.profile_icon.id)
    print("Profile icon name:", summoner.profile_icon.name)
    print("Profile icon URL:", summoner.profile_icon.url)
    print("Profile icon image:", summoner.profile_icon.image)
コード例 #28
0
ファイル: roletest.py プロジェクト: timewindergg/Rewind
def main():
    champion_roles = get_data()

    summoner = Summoner(name="ASRV", region="NA")
    match = cass.get_current_match(summoner=summoner, region="NA")
    roles = get_team_roles(match.blue_team, champion_roles)
    print({role.name: champion.name for role, champion in roles.items()})

    roles = get_team_roles(match.red_team, champion_roles)
    print({role.name: champion.name for role, champion in roles.items()})
    return
コード例 #29
0
def test_match_history_6():
    region = "NA"
    summoner = Summoner(name="Kalturi",
                        account=34718348,
                        id=21359666,
                        region=region)
    match_history = cass.get_match_history(summoner=summoner,
                                           queues={Queue.ranked_solo_fives},
                                           begin_time=arrow.get(2016, 12, 1),
                                           end_time=arrow.get(2016, 12, 30))
    assert len(match_history) > 0
コード例 #30
0
def main():
    champion_roles = get_data()

    summoner = Summoner(name="Kalturi", region="NA")
    for match in summoner.match_history:
        roles = get_team_roles(match.blue_team, champion_roles)
        print({role.name: champion.name for role, champion in roles.items()})

        roles = get_team_roles(match.red_team, champion_roles)
        print({role.name: champion.name for role, champion in roles.items()})
    return