コード例 #1
0
ファイル: csgo.py プロジェクト: Onmius/Toastbot
async def csgo(cmd, message, args):
    csgo_input = ' '.join(args)

    try:
        api = WebAPI(SteamAPI)
        userID = api.call('ISteamUser.ResolveVanityURL', vanityurl=csgo_input, url_type=1)['response']['steamid']
        stats = api.call('ISteamUserStats.GetUserStatsForGame', steamid=userID, appid='730')['playerstats']['stats']
        summary = api.call('ISteamUser.GetPlayerSummaries', steamids=userID)['response']['players'][0]

        nickname = str(summary['personaname'])
        v = 'value'
        n = 'name'
        total_kills = 0
        total_deaths = 0
        total_time_played = 0
        total_kills_knife = 0
        total_kills_headshot = 0
        total_shots_fired = 0
        total_shots_hit = 0
        total_rounds_played = 0
        total_mvps = 0
        total_matches_won = 0
        total_matches_played = 0

        for stat in stats:
            nam = stat[n]
            val = stat[v]
            if nam == 'total_kills':
                total_kills = val
            elif nam == 'total_deaths':
                total_deaths = val
            elif nam == 'total_time_played':
                total_time_played = val
            elif nam == 'total_kills_knife':
                total_kills_knife = val
            elif nam == 'total_kills_headshot':
                total_kills_headshot = val
            elif nam == 'total_shots_fired':
                total_shots_fired = val
            elif nam == 'total_shots_hit':
                total_shots_hit = val
            elif nam == 'total_rounds_played':
                total_rounds_played = val
            elif nam == 'total_mvps':
                total_mvps = val
            elif nam == 'total_matches_won':
                total_matches_won = val
            elif nam == 'total_matches_played':
                total_matches_played = val

        kdr = total_kills / total_deaths
        accuracy = total_shots_hit / total_shots_fired
        total_matches_lost = total_matches_played - total_matches_won
        win_percent = total_matches_won / total_matches_played

        out = '```haskell'
        out += '\nNickname: ' + nickname
        out += '\nPlaytime: ' + str(total_time_played // 3600) + ' Hours'
        out += '\nKills: ' + str(total_kills)
        out += '\nDeaths: ' + str(total_deaths)
        out += '\nKill/Death Ratio: ' + "{0:.2f}".format(kdr)
        out += '\nShots Fired: ' + str(total_shots_fired)
        out += '\nShots Hit: ' + str(total_shots_hit)
        out += '\nAccuracy: ' + "{0:.2f}".format(accuracy * 100) + '%'
        out += '\nHeadshots: ' + str(total_kills_headshot)
        out += '\nKnife Kills: ' + str(total_kills_knife)
        out += '\nRounds Played: ' + str(total_rounds_played)
        out += '\nTotal MVPs: ' + str(total_mvps)
        out += '\nMatches Played: ' + str(total_matches_played)
        out += '\nMatches Won: ' + str(total_matches_won)
        out += '\nMatches Lost: ' + str(total_matches_lost)
        out += '\nWin Percentage: ' + "{0:.2f}".format(win_percent * 100) + '%'
        out += '\n```'

        await cmd.bot.send_message(message.channel, out)

    except Exception as e:
        cmd.log.error(e)
        await cmd.bot.send_message(message.channel, 'Something went wrong or the user was not found.')
コード例 #2
0
async def csgo(cmd, message, args):
    if not args:
        return
    csgo_input = ' '.join(args)

    try:
        api = WebAPI(SteamAPI)
        userID = api.call('ISteamUser.ResolveVanityURL',
                          vanityurl=csgo_input,
                          url_type=1)['response']['steamid']
        stats = api.call('ISteamUserStats.GetUserStatsForGame',
                         steamid=userID,
                         appid='730')['playerstats']['stats']
        summary = api.call('ISteamUser.GetPlayerSummaries',
                           steamids=userID)['response']['players'][0]

        nickname = str(summary['personaname'])
        avatar_url = str(summary['avatarfull'])
        v = 'value'
        n = 'name'
        stat_bases = {
            "total_kills": 0,
            "total_deaths": 0,
            "total_time_played": 0,
            "total_kills_knife": 0,
            "total_kills_headshot": 0,
            "total_shots_fired": 0,
            "total_shots_hit": 0,
            "total_rounds_played": 0,
            "total_mvps": 0,
            "total_matches_won": 0,
            "total_matches_played": 0
        }

        for stat in stats:
            nam = stat[n]
            val = stat[v]
            if nam in stat_bases:
                stat_bases[nam] = val

        kdr = stat_bases['total_kills'] / stat_bases['total_deaths']
        accuracy = stat_bases['total_shots_hit'] / stat_bases[
            'total_shots_fired']
        total_matches_lost = stat_bases['total_matches_played'] - stat_bases[
            'total_matches_won']
        win_percent = stat_bases['total_matches_won'] / stat_bases[
            'total_matches_played']

        data = {
            'Playtime':
            str(stat_bases['total_time_played'] // 3600) + ' Hours',
            'Kills': str(stat_bases['total_kills']),
            'Deaths': str(stat_bases['total_deaths']),
            'Kill/Death Ratio': "{0:.2f}".format(kdr),
            'Shots Fired': str(stat_bases['total_shots_fired']),
            'Shots Hit': str(stat_bases['total_shots_hit']),
            'Accuracy': "{0:.2f}".format(accuracy * 100) + '%',
            'Headshots': str(stat_bases['total_kills_headshot']),
            'Knife Kills': str(stat_bases['total_kills_knife']),
            'Rounds Played': str(stat_bases['total_rounds_played']),
            'Total MVPs': str(stat_bases['total_mvps']),
            'Matches Played': str(stat_bases['total_matches_played']),
            'Matches Won': str(stat_bases['total_matches_won']),
            'Matches Lost': str(total_matches_lost),
            'Win Percentage': "{0:.2f}".format(win_percent * 100) + '%'
        }
        embed = discord.Embed(color=0x1ABC9C)
        embed.set_author(name=nickname, icon_url=avatar_url, url=avatar_url)
        for unit in data:
            embed.add_field(name=unit, value=data[unit])
        await cmd.bot.send_message(message.channel, None, embed=embed)

    except Exception as e:
        cmd.log.error(e)
        await cmd.bot.send_message(
            message.channel, 'Something went wrong or the user was not found.')
コード例 #3
0
    def accept_gifts(self):
        gifts = self.web_account.get_pending_gifts()

        if type(gifts) == enums.WebAccountResult:
            log.error(
                u'Could not accept pending gifts. Received {}'.format(repr(gifts))
            )

            return gifts

        log.info(u'Found {0} pending gifts'.format(len(gifts)))

        for gift in gifts:
            if not gift.gift_javascript:
                log.error(u'Unable to find gift javascript object')

                continue

            matches = re.findall(
                r'BuildHover\( .*, ({.*}), .*\)',
                gift.gift_javascript,
                re.DOTALL
            )

            if not len(matches):
                log.error(u'Regex failed to retrieve gift javascript object')

                continue

            gift_object = json.loads(matches[0])

            log.info(
                u'Found pending gift {0} from {1} ({2})'.format(
                    gift_object.get('name'),
                    gift.from_username,
                    gift.from_link
                )
            )

            match = re.match(
                r'^https?://steamcommunity.com/(?P<type>profiles|id|gid|groups)/(?P<value>.*)/?$',
                gift.from_link
            )

            if not match:
                log.error(u'Could not match steamcommunity URL from {}'.format(gift.from_link))

                continue

            if match.group('type') == 'profiles':
                sender_steam_id = match.group('value')
            else:
                api = WebAPI(backend_config.STEAM_API_KEY)

                api_result = api.call(
                    'ISteamUser.ResolveVanityURL',
                    vanityurl=match.group('value'),
                    url_type=1,
                    format='json'
                )

                if (
                    not api_result.get('response') or
                    api_result.get('response').get('success') != 1
                ):
                    log.error(
                        u'Unable to resolve sender steamid, ResolveVanityURL returned {}'.format(
                            api_result
                        )
                    )

                    continue
                else:
                    sender_steam_id = api_result.get('response').get('steamid')

            if not gift.accept_button or 'UnpackGift' in gift.accept_button:
                log.info(u'Gift cannot be accepted to inventory')

                log.info(
                    u'Declining gift id {0} to sender id {1}'.format(
                        gift_object.get('id'),
                        sender_steam_id
                    )
                )

                result = self.web_account.decline_gift(
                    gift_object.get('id'),
                    sender_steam_id
                )

                if result != EResult.OK:
                    log.error(
                        u'Could not accept gift id {0}. Received {1}'.format(
                            gift_object,
                            repr(result)
                        )
                    )

            elif 'ShowAcceptGiftOptions' in gift.accept_button:
                log.info(
                    u'Accepting gift id {0} to gift inventory'.format(
                        gift_object.get('id')
                    )
                )

                result = self.web_account.accept_gift(
                    gift_object.get('id'),
                    sender_steam_id
                )

                if result != EResult.OK:
                    log.error(
                        u'Could not accept gift id {0}. Received {1}'.format(
                            gift_object,
                            repr(result)
                        )
                    )
コード例 #4
0
def get_profiles(steamid):
    ids = ""
    # if arg is string, expect single steam64id
    if type(steamid) == str:
        ids = steamid
    # if arg is int, generate n random steam64ids
    elif type(steamid) == int:
        # [NEEDS IMPROVED]
        # this isn't random, nor conclusive method of generating steamids
        for i in range(0, steamid):
            ids = ids + ",%s" % SteamID(id=randint(1, 1000000000),
                                        type="Individual",
                                        universe="Public",
                                        instance=1).as_64
    # get player info via steam WebAPI (100 max)
    s_api_key = environ['STEAM_API_KEY']
    steam_api = WebAPI(key=s_api_key)
    players = steam_api.call('ISteamUser.GetPlayerSummaries',
                             steamids=ids)['response']['players']
    # return empty profile only for single steamid scan
    if not players and len(steamid) == 17:
        # empty profile
        p = Profile(steamid, 0, 0, 0, 0, 0, 0)
        p.steamid_found = False
        return [p]
    # build profile objects
    profiles = []
    for p in players:
        try:
            # profile is configured
            state = p["profilestate"]
        except:
            # profile is not configured
            state = 0
        try:
            # this attribute is missing from some profiles, unsure why
            tc = p["timecreated"]
        except:
            # handle gracefully
            tc = 0
        try:
            # create profile object
            profiles.append(
                Profile(p["steamid"], p["communityvisibilitystate"], state,
                        p["personaname"], p["profileurl"], p["avatar"], tc))
        except Exception as e:
            # if no steam64id, discard
            if str(e) == "'steamid'":
                continue
    # if profile is configured and public
    for p in profiles:
        if p.profilestate == 1 and p.communityvisibilitystate == 3:
            # get attributes from community profile
            p.summary, p.vacBanned, p.tradeBanState, p.links = get_community_profile(
                p.steamid)
    # commit profiles to db
    for p in profiles:
        db = connect_db()
        db.execute(
            "INSERT INTO profiles (steamid, communityvisibilitystate, profilestate, personaname, profileurl, avatar, timecreated, summary, vacBanned, tradeBanState) "
            "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s) "
            "ON DUPLICATE KEY UPDATE updated_at=NOW()",
            (p.steamid, p.communityvisibilitystate, p.profilestate,
             p.personaname, p.profileurl, p.avatar, p.timecreated, p.summary,
             p.vacBanned, p.tradeBanState))
        db.close()
    return profiles