Skip to content

Instantly share code, notes, and snippets.

@madzak
Created December 15, 2011 18:42
Show Gist options
  • Save madzak/1482278 to your computer and use it in GitHub Desktop.
Save madzak/1482278 to your computer and use it in GitHub Desktop.
#!/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()
@benjaminws
Copy link

@sleekslush
Copy link

I was thinking the same thing, actually.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment