Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import requests
- import json
- import time
- import re
- try:
- import sys
- from IPython.core.ultratb import AutoFormattedTB
- sys.excepthook = AutoFormattedTB()
- except ImportError:
- print('IPython is not installed. Colored Traceback will not be populated.')
- try:
- import pyperclip
- except ImportError:
- print('"pyperclip" is not installed. "Box1.copy2clipboard()" does not work in the case.')
- fo = open("gameresult.txt", "w")
- fo.write("\n")
- googleAPI = 'AIzaSyBOTinxILMHDJ2IT4Uu5_6zaLWqB2_rLLM'
- TOPRULE = ' ┌─────────────────────────────────────┐'
- MIDRULE = ' ├─────────────────────────────────────┤'
- BOTRULE = ' └─────────────────────────────────────┘'
- L = '│'
- D = '.'
- H = '─'
- def shorten_url(url, api_key=googleAPI):
- post_url = 'https://www.googleapis.com/urlshortener/v1/url?key={}'.format(api_key)
- payload = {'longUrl': url}
- headers = {'content-type': 'application/json'}
- r = requests.post(post_url, data=json.dumps(payload), headers=headers)
- return r.json()
- def get_url_from_gameid(gameid, short_url=None):
- ret = {}
- ret['stats-url'] = 'https://acs.leagueoflegends.com/v1/stats/game/' + gameid
- ret['long-url'] = 'http://matchhistory.na.leagueoflegends.com/en/#match-details/' + gameid + '&tab=stats'
- if short_url is None:
- ret['short-url'] = shorten_url(ret['long-url'])['id']
- else:
- ret['short-url'] = short_url
- return ret
- class SquareDigitNumber(object):
- ON = "[1;33m█[m"
- OFF = " "
- binary = {'0': (ON, ON, ON, ON, OFF, ON, ON, OFF, ON, ON, OFF, ON, ON, ON, ON),
- '1': (OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON),
- '2': (ON, ON, ON, OFF, OFF, ON, ON, ON, ON, ON, OFF, OFF, ON, ON, ON),
- '3': (ON, ON, ON, OFF, OFF, ON, ON, ON, ON, OFF, OFF, ON, ON, ON, ON),
- '4': (ON, OFF, ON, ON, OFF, ON, ON, ON, ON, OFF, OFF, ON, OFF, OFF, ON),
- '5': (ON, ON, ON, ON, OFF, OFF, ON, ON, ON, OFF, OFF, ON, ON, ON, ON),
- '6': (ON, ON, ON, ON, OFF, OFF, ON, ON, ON, ON, OFF, ON, ON, ON, ON),
- '7': (ON, ON, ON, OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON, OFF, OFF, ON),
- '8': (ON, ON, ON, ON, OFF, ON, ON, ON, ON, ON, OFF, ON, ON, ON, ON),
- '9': (ON, ON, ON, ON, OFF, ON, ON, ON, ON, OFF, OFF, ON, ON, ON, ON),
- ' ': (OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF, OFF)}
- def __init__(self, d, filled='0'):
- self.d = d
- self.filled = filled
- @classmethod
- def _display(cls, d, lineno=11):
- startno = (lineno - 5) // 2
- s = ''
- tup = cls.binary[d]
- for _ in range(startno):
- yield cls.OFF * 3
- for i in range(15):
- s += tup[i]
- if i == 0:
- continue
- if i % 3 == 2:
- # s += '\n'
- yield s
- s = ''
- for _ in range(startno):
- yield cls.OFF * 3
- def display(self, lineno=11):
- for seq in zip(*(self._display(d, lineno) for d in '{:{filled}2}'.format(self.d, filled=self.filled))):
- yield ' '.join(seq)
- class Player():
- def __init__(self, char, stats):
- self.char = char
- self.kill = stats['kills']
- self.death = stats['deaths']
- self.assist = stats['assists']
- self.damage = stats['totalDamageDealtToChampions']
- self.tank = stats['totalDamageTaken']
- self.gold = stats['goldEarned']
- self.cs = stats['totalMinionsKilled'] + stats['neutralMinionsKilled']
- self.firstBlood = stats['firstBloodKill']
- self.KP = []
- class ANSIColor(object):
- ENDC = '\033[m'
- START = '\033'
- def __init__(self, color_code):
- self.code = color_code
- def __call__(self, text):
- return self.START + self.code + text + self.ENDC
- BLUE = ANSIColor('[1;34m')
- RED = ANSIColor('[1;31m')
- CYAN = ANSIColor('[1;36m')
- PURPLE = ANSIColor('[;35m')
- GREEN = ANSIColor('[1;32m')
- YELLOW = ANSIColor('[1;33m')
- BRAZIL = ANSIColor('[1;33;42m')
- BLUE_TEAM = ANSIColor('[46m')
- PURPLE_TEAM = ANSIColor('[45m')
- BLUE_FRAME = ANSIColor('[0;34;44m')
- RED_FRAME = ANSIColor('[0;31;41m')
- BLUExYELLOW = ANSIColor('[1;33;44m')
- REDxYELLOW = ANSIColor('[1;33;41m')
- class Box1(object):
- def __init__(self, team1, team2, gameid, short_url=None):
- self.urls = get_url_from_gameid(gameid, short_url=short_url)
- self.team1 = team1
- self.team2 = team2
- res = requests.get(self.urls['stats-url'])
- self._database = json.loads(res.text)
- self._PlayerS = [None] * 10
- GameVer = self._database['gameVersion']
- reschamp = requests.get(
- 'http://ddragon.leagueoflegends.com/cdn/%s.1/data/en_US/champion.json' % '.'.join(GameVer.split('.')[:2]))
- champions = json.loads(reschamp.text)['data']
- self._champbase = {int(champions[key]['key']): key for key in champions}
- @property
- def ANSIlines(self):
- players = [p['player']['summonerName'] for p in self._database['participantIdentities']]
- BlueBans = [None] * 5
- for i in range(5):
- BlueBans[i] = self._champbase[self._database['teams'][0]['bans'][i]['championId']]
- RedBans = [None] * 5
- for i in range(5):
- RedBans[i] = self._champbase[self._database['teams'][1]['bans'][i]['championId']]
- Parc = self._database['participants']
- for z in Parc:
- j = int(z['participantId']) - 1
- player = Player(self._champbase[z['championId']], z['stats'])
- self._PlayerS[j] = player
- lines = []
- ########################################### PAGE 1↓ ###################################
- lines.append(TOPRULE)
- for blocks in zip(self._winner_label(self._database['teams'][0]['win']),
- self._team_label(self.team1, 0),
- self._team_label(self.team2, 1),
- self._winner_label(self._database['teams'][1]['win'])):
- lines.append(' ' + L + ''.join(blocks) + L)
- blue_kills = SquareDigitNumber(
- sum(self._database['participants'][i]['stats']['kills'] for i in range(5))).display(11)
- purple_kills = SquareDigitNumber(
- sum(self._database['participants'][i]['stats']['kills'] for i in range(5, 10))).display(11)
- lines.append(' ' + L + ' ' * 3 + next(blue_kills) + ' ' * 19 + ' ' + PURPLE(L) + ' ' + ' ' * 19 + next(
- purple_kills) + ' ' * 3 + L)
- for i in range(5):
- lines.append(' ' + L + ' ' * 3 + next(blue_kills) + ' ' * 4 + CYAN('{:>15}'.format(players[i])) + ' ' + \
- (PURPLE(L) if i != 2 else 'vs') + \
- ' ' + RED('{:<15}'.format(players[i + 5])) + ' ' * 3 + next(purple_kills) + ' ' * 4 + L)
- lines.append(' ' + L + ' ' * 3 + next(blue_kills) + ' ' * 19 + ' ' + PURPLE(L) + ' ' + ' ' * 18 + next(
- purple_kills) + ' ' * 4 + L)
- lines.append(' ' + L + ' ' * 74 + L)
- for blocks in zip(self._game_time_label(), self._match_history_label(), self._game_duration_label()):
- lines.append(' ' + '{F} {line} {F}'.format(F=L, line=''.join(blocks)))
- lines.append(BOTRULE)
- lines.append('')
- ########################### ↑PAGE 1 PAGE 2↓ ###################################
- lines.append(' ' + BLUE_FRAME(D * 38) + RED_FRAME(D * 38) + ' ')
- lines.append(' ' + BLUE_FRAME(D) + '{:<44}'.format(BLUE_TEAM(self.team1)) + BLUE_FRAME(D) + \
- RED_FRAME(D) + '{:<44}'.format(PURPLE_TEAM(self.team2)) + RED_FRAME(D) + ' ')
- lines.append(
- ' ' + BLUExYELLOW(' Champion' + ' ' * 7 + 'K D A' + ' ' * 4 + 'CS' + ' ' * 3 + 'Gold' + ' ' * 2) + \
- REDxYELLOW(' Champion' + ' ' * 7 + 'K D A' + ' ' * 4 + 'CS' + ' ' * 3 + 'Gold' + ' ' * 2))
- lines.append(' ' + BLUE_FRAME(D) + BLUE(H * 18) + BLUE_FRAME(D) + RED_FRAME(D) + RED(H * 18) + RED_FRAME(D))
- for i in range(5):
- lines.append(' ' + BLUE_FRAME(D) + CYAN('{:<36}'.format(players[i])) + BLUE_FRAME(D) + \
- RED_FRAME(D) + RED('{:<36}'.format(players[i + 5])) + RED_FRAME(D) + ' ')
- lines.append(' ' + BLUE_FRAME(D) +
- ('{:<14}{:2} {:2} {:2} {:4} {:7,}'.format(''.join(self._PlayerS[i].char),
- self._PlayerS[i].kill,
- self._PlayerS[i].death,
- self._PlayerS[i].assist,
- self._PlayerS[i].cs, self._PlayerS[i].gold)) + \
- BLUE_FRAME(D) + RED_FRAME(D) + \
- ('{:<14}{:2} {:2} {:2} {:4} {:7,}'.format(''.join(self._PlayerS[i + 5].char),
- self._PlayerS[i + 5].kill,
- self._PlayerS[i + 5].death,
- self._PlayerS[i + 5].assist,
- self._PlayerS[i + 5].cs, self._PlayerS[i + 5].gold))
- + RED_FRAME(D) + ' ')
- lines.append(' ' + BLUE_FRAME(D) + BLUE(H * 18) + BLUE_FRAME(D) + RED_FRAME(D) + RED(H * 18) + RED_FRAME(D))
- lines.append(' ' + BLUE_FRAME(D) + 'Towers:' + '{:<5}'.format(self._database['teams'][0]['towerKills']) +\
- 'Inhibitors:' + '{:<13}'.format(self._database['teams'][0]['inhibitorKills']) + BLUE_FRAME(D) +\
- RED_FRAME(D) + 'Towers:' + '{:<5}'.format(self._database['teams'][1]['towerKills']) +\
- 'Inhibitors' + ':{:<13}'.format(self._database['teams'][1]['inhibitorKills']) + RED_FRAME(D))
- lines.append(' ' + BLUE_FRAME(D) + 'Dragon:' + '{:<5}'.format(self._database['teams'][0]['dragonKills']) +\
- 'RiftHerald:' + '{:<4}'.format(self._database['teams'][0]['riftHeraldKills']) +\
- 'Baron:' + '{:<3}'.format(self._database['teams'][0]['baronKills']) + BLUE_FRAME(D) +\
- RED_FRAME(D) + 'Dragon:' + '{:<5}'.format(self._database['teams'][1]['dragonKills']) +\
- 'RiftHerald:' + '{:<4}'.format(self._database['teams'][1]['riftHeraldKills']) +\
- 'Baron:' + '{:<3}'.format(self._database['teams'][1]['baronKills'])+ RED_FRAME(D))
- lines.append(' ' + BLUE_FRAME(D) + BLUE(H * 18) + BLUE_FRAME(D) + RED_FRAME(D) + RED(H * 18) + RED_FRAME(D))
- lines.append(' ' + BLUE_FRAME(D) + BLUExYELLOW('Bans:') + ' ' * 7 + \
- '{:<12}'.format(BlueBans[0]) + '{:<12}'.format(BlueBans[1]) + BLUE_FRAME(D) + \
- RED_FRAME(D) + REDxYELLOW('Bans:') + ' ' * 7 + \
- '{:<12}'.format(RedBans[0]) + '{:<12}'.format(RedBans[1]) + RED_FRAME(D))
- lines.append(' ' + BLUE_FRAME(D) + '{:<12}'.format(BlueBans[2]) + '{:<12}'.format(BlueBans[3]) +
- '{:<12}'.format(BlueBans[4]) + BLUE_FRAME(D) + RED_FRAME(D) + '{:<12}'.format(RedBans[2]) +
- '{:<12}'.format(RedBans[3]) + '{:<12}'.format(RedBans[4]) + RED_FRAME(D))
- lines.append(' ' + BLUE_FRAME(D * 38) + RED_FRAME(D * 38) + ' ')
- lines.append('')
- ########################### ↑PAGE 2 PAGE 3↓ ###################################
- lines.append(BLUE(TOPRULE))
- lines.append(' ' + BLUE(L) + '{:<82}'.format(BLUE_TEAM(self.team1)) + BLUE(L))
- lines.append(' ' + BLUE(L) + BLUExYELLOW('Player' + ' ' * 11 + 'KP% Gold GP% Damage DP% D/G% Tank TP% ')+ BLUE(L))
- lines.append(BLUE(MIDRULE))
- KillA = 0
- KillB = 0
- TotalGoldA = 0
- TotalGoldB = 0
- TotalDamageA = 0
- TotalDamageB = 0
- TotalTankA = 0
- TotalTankB = 0
- for k in range(5):
- KillA += self._PlayerS[k].kill
- KillB += self._PlayerS[k + 5].kill
- TotalGoldA += self._PlayerS[k].gold
- TotalGoldB += self._PlayerS[k + 5].gold
- TotalDamageA += self._PlayerS[k].damage
- TotalDamageB += self._PlayerS[k + 5].damage
- TotalTankA += self._PlayerS[k].tank
- TotalTankB += self._PlayerS[k + 5].tank
- for i in range(5):
- if KillA == 0:
- self._PlayerS[i].KP = 0
- else:
- self._PlayerS[i].KP = (self._PlayerS[i].kill + self._PlayerS[i].assist) / KillA
- lines.append(' ' + BLUE(L) + CYAN('{:<15}'.format(players[i])) +
- ('{:6.1%} {:7,} {:6.1%} {:7,} {:6.1%} {:6.1%} {:7,} {:6.1%}'
- .format(self._PlayerS[i].KP,
- self._PlayerS[i].gold, self._PlayerS[i].gold/TotalGoldA,self._PlayerS[i].damage,
- self._PlayerS[i].damage / TotalDamageA, self._PlayerS[i].damage / self._PlayerS[i].gold,
- self._PlayerS[i].tank, self._PlayerS[i].tank / TotalTankA) ) + ' ' + BLUE(L))
- lines.append(' ' + BLUE(L) + BRAZIL('Total'+' ' * 9 + 'Kills:' + '{:<2}'.format(KillA) + ' ' * 5 + 'Gold:' +
- '{:<7,}'.format(TotalGoldA) + ' ' * 4 +'Damage:' + '{:<7,}'.format(TotalDamageA) + ' '*17)+ BLUE(L))
- lines.append(BLUE(MIDRULE))
- lines.append(' ' + RED(L) + '{:<82}'.format(PURPLE_TEAM(self.team2)) + RED(L))
- lines.append(' ' + RED(L) + REDxYELLOW(
- 'Player' + ' ' * 11 + 'KP% Gold GP% Damage DP% D/G% Tank TP% ') + RED(L))
- lines.append(RED(MIDRULE))
- for i in range(5):
- if KillB == 0:
- self._PlayerS[i+5].KP = 0
- else:
- self._PlayerS[i+5].KP = (self._PlayerS[i+5].kill + self._PlayerS[i+5].assist) / KillB
- lines.append(' ' + RED(L) + RED('{:<15}'.format(players[i+5])) +
- ('{:6.1%} {:7,} {:6.1%} {:7,} {:6.1%} {:6.1%} {:7,} {:6.1%}'
- .format(self._PlayerS[i+5].KP,
- self._PlayerS[i+5].gold, self._PlayerS[i+5].gold / TotalGoldB, self._PlayerS[i+5].damage,
- self._PlayerS[i+5].damage / TotalDamageB,
- self._PlayerS[i+5].damage / self._PlayerS[i+5].gold,
- self._PlayerS[i+5].tank, self._PlayerS[i+5].tank / TotalTankB)) + ' ' + RED(L))
- lines.append(' ' + RED(L) + BRAZIL('Total' + ' ' * 9 + 'Kills:' + '{:<2}'.format(KillB) + ' ' * 5 + 'Gold:' +
- '{:<7,}'.format(TotalGoldB) + ' ' * 4 + 'Damage:' + '{:<7,}'.format(
- TotalDamageB) + ' ' * 17) + RED(L))
- lines.append(RED(BOTRULE))
- lines.append('')
- return lines
- def ANSI(self):
- return "\n".join(self.ANSIlines)
- def copy2clipboard(self):
- pyperclip.copy(self.ANSI())
- def _game_time_label(self):
- # Width: 16
- # Height: 4
- yield '{:^16}'.format('Version {}'.format('.'.join(self._database['gameVersion'].split('.')[:2])))
- yield ' ' * 16
- yield '☆{:^12}★'.format(time.strftime('%Y %m/%d', time.gmtime(self._database['gameCreation'] / 1e3)))
- yield ' ' * 16
- def _match_history_label(self):
- # Width: 40
- # Height: 4
- yield '{:^40}'.format('Match History')
- yield ' ' * 40
- yield '{:^40}'.format(self.urls['short-url'])
- yield ' ' * 40
- def _game_duration_label(self):
- # Width: 16
- # Heigth: 4
- m, s = divmod(self._database['gameDuration'], 60)
- yield ' ─────┐'
- yield ' │Game time│'
- yield ' │{:^9}│'.format('{:02}:{:02}'.format(m, s))
- yield ' └───── '
- def _winner_label(self, is_winner):
- # Width: 10
- # Height: 3
- if is_winner.upper() == 'WIN':
- yield BRAZIL('┌───┐')
- yield BRAZIL(L + 'WIN' + L)
- yield BRAZIL('└───┘')
- else:
- yield ' ' * 10
- yield ' ' * 10
- yield ' ' * 10
- @staticmethod
- def _team_label(team, side):
- # Width: 27
- # Height: 3
- if side == 0:
- colorize = BLUE_TEAM
- else:
- colorize = PURPLE_TEAM
- yield ' ' * 27
- q, r = divmod(27 - len(team), 2)
- yield ' ' * q + colorize(team) + ' ' * (q + r)
- yield ' ' * 27
- if __name__ == '__main__':
- import argparse
- parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
- parser.add_argument('game_id', nargs=1,
- help='game-id of the game')
- parser.add_argument('--short-url', default=None,
- help='link to the "Match History" which will display in the box. If it is not given, a "google short URL" will be automatically generated. An API Key from google is needed for this function. See https://developers.google.com/url-shortener/v1/getting_started.')
- parser.add_argument('--teams', '-t', nargs=2, default=['Blue', 'Purple'],
- help='The names of the two teams.')
- parser.add_argument('--copy2clipboard', '-c', action='store_true',
- help='Copy the box to clipboard. "pyperclip" module is required for this function.')
- args = parser.parse_args()
- b = Box1(team1=args.teams[0], team2=args.teams[1], gameid=args.game_id[0], short_url=args.short_url)
- if not args.copy2clipboard:
- #print(b.ANSI())
- fo.write(b.ANSI())
- print('Text has been produced in gameresult.txt.')
- else:
- b.copy2clipboard()
- print('Text has been copied to clipboard.')
- fo.close()
Advertisement
Add Comment
Please, Sign In to add comment