Created
December 15, 2011 18:42
-
-
Save madzak/1482278 to your computer and use it in GitHub Desktop.
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/env python | |
import sys, random, re, urllib, urllib2, json | |
def process_msg(line): | |
image_me = re.compile("(image|im)( me)? (.*)", re.IGNORECASE).match(line) | |
animate_me = re.compile("animate me (.*)", re.IGNORECASE).match(line) | |
if image_me: | |
return fetch_image(image_me.group(3)) | |
elif animate_me: | |
return fetch_image("animated " + animate_me.group(1)) | |
else: | |
sys.exit() | |
def fetch_image(query): | |
try: | |
images = fetch_results(query) | |
except urllib2.URLError: | |
return "Nothing out there buddy, sorry." | |
return images[random.randrange(0,len(images))]["unescapedUrl"] | |
def fetch_results(query): | |
url = "http://ajax.googleapis.com/ajax/services/search/images" | |
values = { | |
"v": "1.0", | |
"rsz": "8", | |
"q": query | |
} | |
response = urllib2.urlopen("{}?{}".format(url, urllib.urlencode(values))) | |
results = json.loads(response.read()) | |
return results["responseData"]["results"] | |
def main(): | |
msg = sys.argv[1] | |
print process_msg(msg) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was thinking the same thing, actually.