Skip to content

Instantly share code, notes, and snippets.

@rascul
Created February 4, 2016 06:35
Show Gist options
  • Save rascul/b8a42f2bf8106df94686 to your computer and use it in GitHub Desktop.
Save rascul/b8a42f2bf8106df94686 to your computer and use it in GitHub Desktop.
""" Google Plugin (yamms plugins.google) """
# Copyright 2015 Ray Schulz <https://rascul.io>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import HTMLParser
import json
from urllib import quote_plus
import requests
from pyaib.plugins import keyword
h = HTMLParser.HTMLParser()
@keyword('g')
def keyword_google(context, msg, trigger, args, kargs):
""" perform a google search """
# figure out first who to target and what the query is
target_user = ""
query = ""
if len(args) >= 3 and args[-2] == "|":
target_user = args[-1]
query = " ".join(args[:-2])
else:
query = " ".join(args)
# see if it's a lmgtfy link requested
if "lmgtfy" in kargs:
url = "http://lmgtfy.com/?q={0}".format(quote_plus(query))
if target_user:
msg.reply("{0}: {1}".format(target_user, url))
else:
msg.reply(url)
else:
search = requests.get("http://ajax.googleapis.com/ajax/services/search/web", params={"v": "1.0", "q": query})
res = json.loads(search.text)
if res["responseData"]["results"]:
url = res["responseData"]["results"][0]["unescapedUrl"]
title = res["responseData"]["results"][0]["titleNoFormatting"]
if target_user:
msg.reply("{0}: {1} - {2}".format(target_user, h.unescape(title), url))
else:
msg.reply("{0} - {1}".format(h.unescape(title), url))
else:
msg.reply("no results for {0}".format(query))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment