Created
June 12, 2018 18:58
-
-
Save sadlerjw/d7db4b037d4dfdd4057754faeb6eeb9c to your computer and use it in GitHub Desktop.
Python script to generate a link to an HSReplay.net deck, based on a string of text (for example, a tweet) containing a Hearthstone deck code.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
import binascii | |
import urllib | |
import re | |
import sys | |
def nextVarInt(fromIndex, bytes): | |
shift = 0 | |
result = 0 | |
index = fromIndex | |
while True: | |
byte = ord(bytes[index]) | |
result |= (byte & 0x7f) << shift | |
shift += 7 | |
index += 1 | |
if (not (byte & 0x80)) or index >= len(bytes): | |
break | |
return (result, index) | |
def urlFromDeckCode(deckCode): | |
binary = binascii.a2b_base64(deckCode) | |
reserved = ord(binary[0]) | |
(version, index) = nextVarInt(1, binary) | |
(format, index) = nextVarInt(index, binary) | |
cardCount = 0 | |
cards = [] | |
(heroesLength, index) = nextVarInt(index, binary) | |
for i in range(heroesLength): | |
(hero, index) = nextVarInt(index, binary) | |
(singlesLength, index) = nextVarInt(index, binary) | |
for i in range(singlesLength): | |
(single, index) = nextVarInt(index, binary) | |
cards.append(single) | |
cardCount += 1 | |
(doublesLength, index) = nextVarInt(index, binary) | |
for i in range(doublesLength): | |
(double, index) = nextVarInt(index, binary) | |
cards.append(double) | |
cards.append(double) | |
cardCount += 2 | |
(nCopiesLength, index) = nextVarInt(index, binary) | |
for i in range(nCopiesLength): | |
(copies, index) = nextVarInt(index, binary) | |
(card, index) = nextVarInt(index, binary) | |
cardCount += copies | |
for x in range(copies): | |
cards.append(card) | |
cardListString = reduce(lambda ongoing, y: ongoing + str(y) + ",", cards, "")[:-1] | |
url = "https://hsreplay.net/decks/#includedCards=" + urllib.quote(cardListString, safe = '') | |
return url | |
tweet = sys.argv[1] | |
# Find the deck code. We assume the first string with 30 or more | |
# consecutive characters without whitespace is it. | |
match = re.search("\\S{30,}", tweet) | |
if match != None: | |
deckCode = match.group(0) | |
url = urlFromDeckCode(deckCode) | |
print url | |
else: | |
print "" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment