Skip to content

Commit

Permalink
Implemented partial matches!
Browse files Browse the repository at this point in the history
  • Loading branch information
giovinazzo-kevin committed Aug 14, 2016
1 parent 001dd37 commit 9c1cc0c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 19 deletions.
30 changes: 22 additions & 8 deletions teslcardbot/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,10 @@ class Card:
JSON_DATA = []
KEYWORDS = ['Prophecy', 'Breakthrough', 'Guard', 'Regenerate', 'Charge', 'Ward', 'Shackle',
'Lethal', 'Pilfer', 'Last Gasp', 'Summon', 'Drain']
PARTIAL_MATCH_END_LENGTH = 20

@staticmethod
def get_random_card(name):
def get_fake_card(name):
boolshit_values = ['None', 'Undefined', 'Null', 'False', '💩', '#ERR', '0', '???', '!?']

def rv(v=boolshit_values):
Expand Down Expand Up @@ -69,6 +70,16 @@ def _extract_keywords(text):
break
return remove_duplicates(keywords)

@staticmethod
def _fetch_data_partial(name):
i = 0
matches = ['', '']
while len(matches) > 1 and i <= Card.PARTIAL_MATCH_END_LENGTH:
matches = [s for s in Card.JSON_DATA if s['name'].lower().startswith(name[:i].lower())]
i += 1

return None if len(matches) == 0 else matches[0]

@staticmethod
def get_info(name):
name = Card._escape_name(name)
Expand All @@ -85,13 +96,14 @@ def get_info(name):
# If JSON_DATA hasn't been populated yet, try to do it now or fail miserably.
if len(Card.JSON_DATA) <= 0:
Card.preload_card_data()
assert(len(Card.JSON_DATA) > 0)
assert (len(Card.JSON_DATA) > 0)

data = Card._fetch_data_partial(name)

data = next((c for c in Card.JSON_DATA if Card._escape_name(c['name']) == name), None)
if data is None:
return None

img_url = Card.CARD_IMAGE_BASE_URL.format(name)
img_url = Card.CARD_IMAGE_BASE_URL.format(Card._escape_name(data['name']))
# Unlikely, but possible?
if not Card._img_exists(img_url):
img_url = Card.CARD_IMAGE_404_URL
Expand Down Expand Up @@ -144,7 +156,8 @@ def __str__(self):
url=self.img_url,
type=self.type.title(),
mana=self.cost,
stats='{} - {}/{}'.format(self.cost, self.power, self.health) if self.type == 'creature' else '{} - ?/?'.format(self.cost),
stats='{} - {}/{}'.format(self.cost, self.power,
self.health) if self.type == 'creature' else '{} - ?/?'.format(self.cost),
keywords=', '.join(map(str, self.keywords)) + '' if len(self.keywords) > 0 else 'None',
text=self.text if len(self.text) > 0 else 'This card\'s name isn\'t in the database. Possible typo?'
)
Expand Down Expand Up @@ -196,10 +209,11 @@ def build_response(self, cards):
for name in cards:
card = Card.get_info(name)
if card is None:
card = Card.get_random_card(name)
card = Card.get_fake_card(name)
response += '{}\n'.format(str(card))

did_you_know = random.choice(['Hover the camera emoji to read a card\'s text!'])
did_you_know = random.choice(['You can hover the camera emoji to read a card\'s text!',
'I can do partial matches now!'])
auto_word = random.choice(['automatically', 'automagically'])

response += '\n**Did you know?** _{}_\n\n' \
Expand Down Expand Up @@ -229,7 +243,7 @@ def start(self, batch_limit=10, buffer_size=1000):
except praw.errors.HTTPException:
self.log('Reddit seems to be down! Aborting.')
return

for s in new_submissions:
self._process_submission(s)
# The bot will also save submissions it replies to to prevent double-posting.
Expand Down
29 changes: 18 additions & 11 deletions teslcardbot/tests/unit_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ class TestParsingFunctions(unittest.TestCase):

def setUp(self):
self.bot = TESLCardBot(author='TestParsingFunctions', target_sub='TESLCardBotTesting')
Card.preload_card_data()

def test_find_card_mentions(self):
# Make sure the basic functioning works
Expand All @@ -19,6 +20,20 @@ def test_escape_card_name(self):
self.assertEqual(Card._escape_name('Bl-ood, _-"\' Drag;on'), 'blooddragon')
self.assertEqual(Card._escape_name('{{{HOHO}}}}}'), 'hoho')

def test_extract_keywords(self):
self.assertEqual(Card._extract_keywords('Charge'),['Charge'])
self.assertEqual(Card._extract_keywords('Charge, Pilfer'),['Charge', 'Pilfer'])
self.assertEqual(Card._extract_keywords('cHaRge. dRaIn'),['Charge', 'Drain'])
self.assertEqual(Card._extract_keywords('Summon: Ayy lmao'),['Summon'])
self.assertEqual(Card._extract_keywords('Charge. Last Gasp: rip 2016'),['Charge', 'Last Gasp'])
self.assertEqual(Card._extract_keywords('Summon: Summon a minion with Guard.'),['Summon'])

def test_fetch_data_partial(self):
self.assertEqual(Card._fetch_data_partial('tyr')['name'], 'Tyr')
self.assertEqual(Card._fetch_data_partial('lesser')['name'], 'Lesser Ward')
self.assertEqual(Card._fetch_data_partial('gortwog')['name'], 'Gortwog gro-Nagorm')
self.assertEqual(Card._fetch_data_partial('Breton Conjurer')['name'], 'Breton Conjurer')

def test_get_info(self):
Card.preload_card_data()

Expand All @@ -30,17 +45,9 @@ def test_get_info(self):
'| Creature | 4 - 5/4 | Prophecy, Breakthrough, Guard '
'| Strength/Willpower | Legendary')

self.assertEqual(str(Card.get_info('lesser ward')), '[📷](http://www.legends-decks.com/img_cards/'
'lesserward.png "Give a creature a Ward.") Lesser Ward | '
'Action | 0 - ?/? | None | Intelligence | Common')

def test_extract_keywords(self):
self.assertEqual(Card._extract_keywords('Charge'),['Charge'])
self.assertEqual(Card._extract_keywords('Charge, Pilfer'),['Charge', 'Pilfer'])
self.assertEqual(Card._extract_keywords('cHaRge. dRaIn'),['Charge', 'Drain'])
self.assertEqual(Card._extract_keywords('Summon: Ayy lmao'),['Summon'])
self.assertEqual(Card._extract_keywords('Charge. Last Gasp: rip 2016'),['Charge', 'Last Gasp'])
self.assertEqual(Card._extract_keywords('Summon: Summon a minion with Guard.'),['Summon'])
self.assertEqual(str(Card.get_info('lesser w')), '[📷](http://www.legends-decks.com/img_cards/'
'lesserward.png "Give a creature a Ward.") Lesser Ward | '
'Action | 0 - ?/? | None | Intelligence | Common')


if __name__ == '__main__':
Expand Down

0 comments on commit 9c1cc0c

Please sign in to comment.