Bladeren bron

first commit

Tobias Siegel 7 jaren geleden
bovenliggende
commit
b0f059e07a
5 gewijzigde bestanden met toevoegingen van 231 en 0 verwijderingen
  1. 53 0
      bot.py
  2. 2 0
      pubg_lablab/__init__.py
  3. 23 0
      pubg_lablab/constants.py
  4. 50 0
      pubg_lablab/core.py
  5. 103 0
      pubg_lablab/objects.py

+ 53 - 0
bot.py

@@ -0,0 +1,53 @@
+import pubg_lablab
+
+from uuid import uuid4
+from telegram.ext import MessageHandler, Filters, Updater, InlineQueryHandler
+from telegram import InlineQueryResultArticle, InputTextMessageContent, ParseMode
+
+bg = pubg_lablab.Battlegrounds('Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1NzdjYzFlMC1jM2UwLTAxMzYtOWJiZS02YjYxOGIyZjU5NzQiLCJpc3MiOiJnYW1lbG9ja2VyIiwiaWF0IjoxNTQxNTAxNzA1LCJwdWIiOiJibHVlaG9sZSIsInRpdGxlIjoicHViZyIsImFwcCI6InB1YmdfdGVsZWdyYW0ifQ.yANNOqbPTDA0aBxMvriJ35c6Fg2b2g7JC9esndsXKOg', 'pc_eu')
+def bot_query(bot, update):
+    query = update.inline_query.query
+    print(query)
+    allowed_users = ['Vogelstrauss', 'tsi_tsi', 'Ceelbee', 'Konfusio']
+    if query in allowed_users:
+        squad_lifetime_stats = bg.lifetime(bg.player(query).id).squad
+        out = query + " (Rounds: " + str(squad_lifetime_stats.roundsPlayed) + ")" \
+                    + "\nKills: " + str(squad_lifetime_stats.kills) \
+                    + "\nHeadshot Kills: " + str(squad_lifetime_stats.headshotKills) \
+                    + "\nAssists: " + str(squad_lifetime_stats.assists) \
+                    + "\nRoad Kills: " + str(squad_lifetime_stats.roadKills) \
+                    + "\nLongest Shot: " + str(squad_lifetime_stats.longestKill)
+        options = [
+            InlineQueryResultArticle(
+            id=uuid4(),
+            title="Total Kills",
+            input_message_content=InputTextMessageContent(out , parse_mode = "HTML"))
+        ]
+        print(options)
+    if query == 'rank':
+        toplist = {}
+        for i in allowed_users:
+            stats = bg.lifetime(bg.player(i).id).squad
+            toplist[i] = stats.kills
+        toplist = sorted(toplist.items(), key=lambda kv: kv[1], reverse=True)
+        out = "Ranking\n"
+        n = 1
+        for i in toplist:
+            out += str(n) + ". " + str(i[0]) + " - " + str(i[1]) + '\n'
+            n = n + 1
+        options = [
+            InlineQueryResultArticle(
+            id=uuid4(),
+            title="Ranking",
+            input_message_content=InputTextMessageContent(out , parse_mode = "HTML"))
+        ]
+
+    update.inline_query.answer(options, cache_time=0)
+
+
+updater = Updater(token='627697353:AAEuYCZSPfMg9ll0D0Gf3QhA9G21wJh97Wk')
+dispatcher = updater.dispatcher
+dispatcher.add_handler(InlineQueryHandler(bot_query))
+updater.start_polling(clean=True)
+print ("Running")
+updater.idle()

+ 2 - 0
pubg_lablab/__init__.py

@@ -0,0 +1,2 @@
+from .core import Battlegrounds
+from .constants import Region

+ 23 - 0
pubg_lablab/constants.py

@@ -0,0 +1,23 @@
+class Region:
+    """Class containing available regions."""
+    xbox_as = 'xbox-as'  # Asia
+    xbox_eu = 'xbox-eu'  # Europe
+    xbox_na = 'xbox-na'  # North America
+    xbox_oc = 'xbox-oc'  # Oceania
+    pc_krjp = 'pc-krjp'  # Korea / Japan
+    pc_na = 'pc-na'  # North America
+    pc_eu = 'pc-eu'  # Europe
+    pc_oc = 'pc-oc'  # Oceania
+    pc_kakao = 'pc-kakao'
+    pc_sea = 'pc-sea'  # South East Asia
+    pc_sa = 'pc-sa'  # South and Central America
+    pc_as = 'pc-as'  # Asia
+
+
+class Endpoint:
+    base = 'https://api.pubg.com'
+    matches = '/shards/{region}/matches'
+    match = '/shards/{region}/matches/{id}'
+    lifetime = '/shards/steam/players/{id}/seasons/lifetime'
+    player_lookup = '/shards/steam/players?filter[playerNames]={name}'
+    status = '/status'

+ 50 - 0
pubg_lablab/core.py

@@ -0,0 +1,50 @@
+from .constants import Endpoint
+from .objects import Match, Status, Player, Lifetime
+import requests
+
+class Battlegrounds:
+    def __init__(self, api_key, region):
+        self.api_key = api_key
+        self.region = region
+        self.session = Session(api_key)
+        self.playerIdCache = []
+
+    def matches(self):
+        json = self.session.get(Endpoint.matches.format(region=self.region))
+        return Match(json)
+
+    def player(self, player_name):
+        for player in self.playerIdCache:
+            if player.name == player_name:
+                print("looked up player id from cache")
+                return player
+        json = self.session.get(Endpoint.player_lookup.format(name=player_name))
+        self.playerIdCache.append(Player(json))
+        return Player(json)
+
+    def lifetime(self, player_id):
+        json = self.session.get(Endpoint.lifetime.format(id=player_id))
+        return Lifetime(json)
+
+    @staticmethod
+    def status():
+        response = requests.get(f'{Endpoint.base}{Endpoint.status}')
+        if response.status_code == 200:
+            return Status(response.json())
+        else:
+            response.raise_for_status()  # Update when we know of other responses
+
+class Session:
+    def __init__(self, api_key):
+        self.session = requests.Session()
+        self.session.headers.update({
+            'Authorization': api_key,
+            'Accept': 'application/vnd.api+json'
+        })
+
+    def get(self, endpoint):
+        response = self.session.get(f'{Endpoint.base}{endpoint}')
+        if response.status_code == 200:
+            return response.json()
+        else:
+            response.raise_for_status()

+ 103 - 0
pubg_lablab/objects.py

@@ -0,0 +1,103 @@
+class Base:
+    def __init__(self, data):
+        self.data = data
+
+    def __repr__(self):
+        return f'<{self.__class__.__name__} {self.__dict__}>'
+
+
+class Lifetime(Base):
+    class GameModeStats(Base):
+        def __init__(self, data):
+            super().__init__(data)
+            self.assists = self.data.get('assists')
+            self.kills = self.data.get('kills')
+            self.roundsPlayed = self.data.get('roundsPlayed')
+            self.headshotKills = self.data.get('headshotKills')
+            self.roadKills = self.data.get('roadKills')
+            self.longestKill = self.data.get('longestKill')
+            self.timeSurvived = self.data.get('timeSurvived')
+
+    def __init__(self, data):
+        super().__init__(data)
+        self.duo = Lifetime.GameModeStats(self.data.get('data').get('attributes').get('gameModeStats').get('duo'))
+        self.duofpp = Lifetime.GameModeStats(self.data.get('data').get('attributes').get('gameModeStats').get('duo-fpp'))
+        self.squad = Lifetime.GameModeStats(self.data.get('data').get('attributes').get('gameModeStats').get('squad'))
+        self.type = self.data.get('data').get('type')
+        self.assists = self.data.get('data').get('assists')
+        self.boosts = self.data.get('boosts')
+
+
+class Player(Base):
+    def __init__(self, data):
+        super().__init__(data)
+        self.id = self.data.get('data')[0].get('id')
+        self.name = self.data.get('data')[0].get('attributes').get('name')
+
+
+class Match(Base):
+    def __init__(self, data):
+        super().__init__(data)
+        self.id = self.data.get('id')
+        self.created_at = self.data.get('createdAt')
+        self.duration = self.data.get('duration')
+        self.rosters = self.roster_list()
+        # rounds
+        self.assets = self.asset_list()
+        # spectators
+        # stats
+        self.game_mode = self.data.get('gameMode')
+        self.patch_version = self.data.get('patchVersion')
+        self.title_id = self.data.get('titleId')
+        self.shard_id = self.data.get('shardId')
+        # tags
+
+    def roster_list(self):
+        return [Roster(data) for data in self.data.get('rosters')]
+
+    def asset_list(self):
+        return [Asset(data) for data in self.data.get('assets')]
+
+
+class Roster(Base):
+    def __init__(self, data):
+        super().__init__(data)
+        self.id = self.data.get('id')
+        # team
+        self.participants = self.participant_list()
+        # stats
+        self.won = self.data.get('won')
+        self.shard_id = self.data.get('shardId')
+
+    def participant_list(self):
+        return [Participant(data) for data in self.data.get('participants')]
+
+
+class Asset(Base):
+    def __init__(self, data):
+        super().__init__(data)
+        self.id = self.data.get('id')
+        self.title_id = self.data.get('titleId')
+        self.shard_id = self.data.get('shardId')
+        self.name = self.data.get('name')
+        self.description = self.data.get('description')
+        self.created_at = self.data.get('createdAt')
+        self.filename = self.data.get('filename')
+        self.content_type = self.data.get('contentType')
+        self.url = self.data.get('URL')
+
+
+class Participant(Base):
+    def __init__(self, data):
+        super().__init__(data)
+        self.id = self.data.get('id')
+        # stats
+        self.actor = self.data.get('actor')
+        self.shard_id = self.data.get('shardId')
+
+
+class Status(Base):
+    def __init__(self, data):
+        super().__init__(data)
+        self.id = self.data.get('data').get('id')
+        self.type = self.data.get('data').get('type')