diff --git a/bot.py b/bot.py index c18d1d6..8588367 100644 --- a/bot.py +++ b/bot.py @@ -1,6 +1,7 @@ import pydle import requests import random +import re host = "https://collectionapi.metmuseum.org/public/collection/v1/" @@ -8,24 +9,38 @@ host = "https://collectionapi.metmuseum.org/public/collection/v1/" r = requests.get(host + 'objects') objects = r.json()['objectIDs'] -def getArt(): - while True: - r = requests.get(host + 'objects/' + str(random.choice(objects))) +def getArt(term): + searchObjects = objects + if term: + query = {'q': term, 'hasImages': 'true'} + r = requests.get(host + 'search', params=query) + searchObjects = r.json()['objectIDs'] + + if not searchObjects or len(searchObjects) == 0: + return None + + tries = 10 + while tries > 0: + r = requests.get(host + 'objects/' + str(random.choice(searchObjects))) j = r.json() if j['primaryImage']: return j + tries -= 1 + return None # Simple echo bot. class RadioBot(pydle.Client): async def on_connect(self): await self.join('#dailybot') - await self.join('#dailybuild') + # await self.join('#dailybuild') async def on_message(self, target, source, message): # don't respond to our own messages, as this leads to a positive feedback loop if source != self.nickname: - if message.startswith(".art"): - art = getArt() + if re.match(r'^\.art\b', message): + art = getArt(message[len(".art"):].strip()) + if art is None: + await self.message(target, "No result") await self.message(target, '"' + art['title'] + '" ' + art['objectDate'] + ' ' + art['primaryImage']) client = RadioBot('ArtBot', realname='ArtBot')