Ejemplo n.º 1
0
    def trigger_g(self, msg):
        "Usage: g <search term>. Prints title & short description of first google result."
        if len(msg.args) == 0:
            self.c.notice(msg.nick, "Please specify a search term")
            return

        url = 'http://ajax.googleapis.com/ajax/services/search/web'
        params = {'q': ' '.join(msg.args),
                  'v': 1.0}
        resp_json = requests.get(url, params=params).json()

        results = resp_json["responseData"]["results"]
        if len(results) == 0:
            self.c.privmsg(msg.channel, '{}: No results.'.format(' '.join(msg.args)))
            return
        top_res = results[0]

        print(top_res)
        url     = googl.get_short(top_res['url'], self.c.config)
        content = self.fix_text(top_res['content'])
        title   = self.fix_text(top_res['title'])

        message = u"\002\0032G\0034o\0038o\0032g\0033l\0034e\003 ::\002 {} \002::\002 {} \002::\002 {}".format(
            title,
            content,
            url)
        self.c.privmsg(msg.channel, message)
Ejemplo n.º 2
0
    def trigger_w(self, msg):
        "Usage: w <search term>. Prints a short description of the corresponding wikipedia article."
        if len(msg.args) == 0:
            self.c.notice(msg.nick, "Please specify a search term")
            return

        params = {'action':'opensearch', 'format':'xml', 'limit':'2', 'search':' '.join(msg.args)}

        resp = bss(requests.post("http://en.wikipedia.org/w/api.php", data=params).text, convertEntities=bs.HTML_ENTITIES)

        if resp.textTag:
            index = 1 if 'may refer to:' in resp.descriptionTag.string else 0
            info = resp.findAll('description')[index].string.strip()
            url = resp.findAll('url')[index].string
            message = u"\002Wikipedia ::\002 %s \002::\002 %s" % (info, googl.get_short(url,self.c.config))
            self.c.privmsg(msg.channel, message)
        else:
            self.c.privmsg(msg.channel, '%s: No articles were found.' % ' '.join(msg.args))
Ejemplo n.º 3
0
	def trigger_g(self, msg):
		"Usage: g <search term>. Prints title & short description of first google result."
		if len(msg.args) == 0:
			self.c.notice(msg.nick, "Please specify a search term")
			return

		url = "https://www.google.com.au/search?q=%s" % (urllib.quote_plus(' '.join(msg.args)),)
		req = urllib2.Request(url, None, {'User-agent':self.useragent})
		entry = bs(urllib2.urlopen(req), convertEntities=bs.HTML_ENTITIES).find('div', 'vsc')

		if not entry:
			self.c.privmsg(msg.channel, '%s: No entries were found.'%' '.join(msg.args))
			return

		url = googl.get_short(entry.find('a','l')['href'], self.c.config)
		message = "\002\0032G\0034o\0038o\0032g\0033l\0034e\003 ::\002 %s \002::\002 %s \002::\002 %s" % (
			self.tag2string(entry.find('a','l')),
			self.tag2string(entry.find('span','st')),
			url,)
		self.c.privmsg(msg.channel, message)
Ejemplo n.º 4
0
    def trigger_g(self, msg):
        "Usage: g <search term>. Prints title & short description of first google result."
        if len(msg.args) == 0:
            self.c.notice(msg.nick, "Please specify a search term")
            return

        url = 'http://ajax.googleapis.com/ajax/services/search/web'
        params = {'q': ' '.join(msg.args),
                  'v': 1.0}
        resp_json = requests.get(url, params=params).json

        results = resp_json["responseData"]["results"]
        if len(results) == 0:
            self.c.privmsg(msg.channel, '{}: No results.'.format(' '.join(msg.args)))
            return
        top_res = results[0]

        url = googl.get_short(top_res['url'], self.c.config)

        message = u"\002\0032G\0034o\0038o\0032g\0033l\0034e\003 ::\002 %s \002::\002 %s \002::\002 %s" % (
            fixentities(top_res['titleNoFormatting']),
            fixentities(unicode(re.sub("</?b>", "\002", top_res['content']))),
            url)
        self.c.privmsg(msg.channel, message)
Ejemplo n.º 5
0
    def trigger_tx(self, msg):
        "Usage: tx <expression>. Prints a link to a graphical representation of the supplied LaTeX expression."

        url = "http://www.texify.com/$%s$" % urllib.quote(' '.join(msg.args))
        self.c.privmsg(msg.channel, 'LaTeX :: %s' % googl.get_short(url, self.c.config))
Ejemplo n.º 6
0
    def trigger_wa(self, msg):
        "Usage: wa <query>. Prints the top result from WolframAlpha."
        if len(msg.args) == 0:
            self.controller.notice(msg.nick, "Please specify a query")
            return

        # Set up the required data for the query
        querydata = {'appid' : self.appid,
                     'input' : ' '.join(msg.args),
                     'format': 'plaintext'}
        if self.location is not None:
            querydata['location'] = self.location
        if self.latlong is not None:
            querydata['latlong'] = self.latlong
        if self.units is not None:
            querydata['units'] = self.units

        # Perform the query and form XML Tree
        response = self.session.post(self.queryurl, data=querydata)
        tree = ElementTree.XML(response.text.encode('utf-8'))

        # Check for error
        if tree.get('error') == 'true':
            self.controller.privmsg(msg.channel, '{} Error.'.format(self.prefix))
            return

        # Interpretation may or may not differ from query
        interpretation = ''

        # Check for didyoumeans, when the query is derp and requires a different interpretation
        if tree.get('success') == 'false':
            didyoumeans_list = []
            # Get alternatives
            for didyoumeans in tree.iterfind('didyoumeans'):
                for didyoumean in didyoumeans.iterfind('didyoumean'):
                    didyoumeans_list.append(didyoumean.text)
            # Try alternatives
            for try_next in didyoumeans_list:
                querydata['input'] = try_next
                response = self.session.post(self.queryurl, data=querydata)
                tree = ElementTree.XML(response.text.encode('utf-8'))
                if tree.get('error') == 'true':
                    self.controller.privmsg(msg.channel, '{} Error.'.format(self.prefix))
                    return
                # When a proper result has been obtained:
                if tree.get('success') == 'true':
                    # Set the interpretation and continue on
                    interpretation = try_next
                    break
            else:
                # There were no suitable alternatives
                self.controller.privmsg(msg.channel, '{} Could not interpret input.'.format(self.prefix))
                return

        # Can be more than one result so store a list
        results = []

        # Iterate through all 'pod' elements
        for pod in tree.iterfind('pod'):
            #print pod.get('title')
            if pod.get('primary') == 'true' or pod.get('title') == 'Result':
                # If it is a primary pod (good result) check through subpods
                result = ''
                subpod_count = pod.get('numsubpods')
                for subpod in pod.iterfind('subpod'):
                    # Only take primary subpods/lone subpods
                    if subpod.get('primary') == 'true' or subpod_count == '1':
                        result = subpod.findtext('plaintext')
                        if '\n' in result:
                            result = result.replace('\n',' ')
                        if len(result) > 100:
                            result = result[:result.find(' ',100)] + '...'
                        if len(result) > 200:
                            result = result[:200] + '...'
                        #print '--',result
                # Get the title for output and add to results
                podtitle = pod.get('title')
                if result == '' and subpod_count > 1:
                    result = pod.iterfind('subpod').next().findtext('plaintext')
                    result += '. ' + str(int(subpod_count) - 1) + ' other forms'
                results.append((podtitle, result))
            # If WA interprets the query differently, use it
            if pod.get('title') == 'Input interpretation':
                for subpod in pod.iterfind('subpod'):
                    interpretation = subpod.findtext('plaintext')
                    #print 'int -', interpretation

        if '\n' in interpretation:
            interpretation = interpretation.replace('\n',' ')
        if len(interpretation) > 100:
            interpretation = interpretation[:interpretation.find(' ',100)] + '...'
        if len(interpretation) > 200:
            interpretation = interpretation[:200] + '...'
        # Notify of use of alternate interpretation
        if interpretation != '':
            self.controller.privmsg(msg.channel, '{} Interpreting as `{}\'.'.format(self.prefix, interpretation))

        # Add all results to messages and send at once
        messages = []
        for result in results:
            messages.append('{} {} \002::\002 {}'.format(self.prefix, result[0], result[1]))
        if not results:
            messages.append('{} No primary results.'.format(self.prefix))

        # Add a goo.gl url to last result
        messages[-1] += ' \002::\002 '
        messages[-1] += googl.get_short('http://www.wolframalpha.com/input/?i=%s' % urllib.quote_plus(' '.join(msg.args).encode('utf-8')), self.controller.config)

        for message in messages:
            self.controller.privmsg(msg.channel, message)