summaryrefslogtreecommitdiff
path: root/steamrelationships/sr.py
blob: a9d81193ab202e3843b56c022599e0347284464a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import requests
import json

class SteamRelationships:
    session = requests.Session()        # Session object so repeated querries to steam's api use the same TCP connection
    scanlist = []                       # To be populated by recurse()

    def __init__(self, webapikey, timeout=30) -> None:
        '''
        (str/int) webapikey - Steam dev api key required to use Steam's ISteamUser/GetFriendList interface
        (int/float) timeout (Default: 30) - Seconds to wait before timing out a request.
        '''
        self.webapikey = webapikey
        self.timeout = timeout

    def _getFriendsList(self, steamid64 = None) -> dict:
        # example url: http://api.steampowered.com/ISteamUser/GetFriendList/v0001/?key=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&steamid=76561197960435530&relationship=friend
        if not steamid64:
            print("Requested id must not be blank")
            return

        # Format url and make a request
        url = "https://api.steampowered.com/ISteamUser/GetFriendList/v0001/"
        options = {"key": self.webapikey, "steamid": steamid64, "relationship": "friend"}

        response = self.session.get(url, params=options, timeout=self.timeout) # GET should be as secure as POST because ssl is being used

        # TODO: Implement proper error checking so that this doesn't just break if someone has a private friends list
        if response.status_code == requests.codes.ok:
            return response.json()

        return None

    def parseFriendsList(self, friendslist = None) -> list:
        if not friendslist:
            return None

        final = []
        for friend in friendslist['friendslist']['friends']:
            final.append(friend['steamid'])

        return final

    def recursive_scan(self, startid = None, recurselevel = 2) -> list:
        # Scan an initial id, then populate a list with the scans of each friend
        scans = {}
        alreadyscanned = []

        # Start the scan and collect the first user's friend list
        scans[startid] = self.parseFriendsList(self._getFriendsList(startid))
        alreadyscanned.append(startid)

        # Scan the current scanid's friends and append them to the list
        for friend in scans[startid]:
            if friend not in alreadyscanned:
                scans[friend] = self.parseFriendsList(self._getFriendsList(friend))
                alreadyscanned.append(friend)

        #TODO: Find way to repeat this by recurse level

        return scans