Пример #1
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    Plugin.load()

    line = readline()
    while line:
        for plugin in Plugin.plugins:
            on_message = getattr(plugin, "on_message")
            response = plugin.on_message({'text':line, 'speaker_id':1, 'room':'test'})
            if response:
                print(response)
        line = readline()
Пример #2
0
def main():
    logging.basicConfig(level=logging.DEBUG)
    Plugin.load()

    line = readline()
    while line:
        for plugin in Plugin.plugins:
            on_message = getattr(plugin, "on_message")
            response = plugin.on_message({
                'text': line,
                'speaker_id': 1,
                'room': 'test'
            })
            if response:
                print(response)
        line = readline()
Пример #3
0
        if m:
            result.append(m.group(1))
        m = self.re_gmap.search(q)
        if m:
            result.append('http://maps.google.com/maps/api/staticmap?zoom=15&size=640x320&markers=%s&sensor=false&n.gif' % m.group(1))
        m = self.re_img.findall(q)
        if m:
            for i in m:
                result.append(i)

        return "\n".join(result)

    def cmd_instagram(self, url):
        instagram = url + '/media/?size=l'
        logging.info('instagram: %s', instagram)
        url = urllib2.urlopen(instagram).geturl()
        logging.info('result: %r', url)
        return url

    def cmd_fetch(self, argv):
        url = '+'.join(argv)
        if re.match('^http(?s)://', url):
            logging.info('fetch: %r', url)
            f = urllib.urlopen(url)
            buf = f.read()
            logging.info('result: size: %d', len(buf))
            logging.debug('result: %r', buf[:512])
            return '%r' % buf[:512]

Plugin.register(Snippet())
Пример #4
0
from demjson import decode as decode_json


class Translate(Plugin):
    """Google translate Plugin for Lingrvant"""

    def help(self):
        """Help"""
        return """!T from|to text...
!T |to text...
Supported languages: Albanian, Arabic, Bulgarian, Chinese (Simplified and Traditional), Catalan, Croatian, Czech, Danish, Dutch, English, Estonian, Filipino, Finnish, French, Galician, German, Greek, Hebrew, Hindi, Hungarian, Indonesian, Italian, Japanese, Korean, Latvian, Lithuanian, Maltese, Norwegian, Persian, Polish, Portuguese, Romanian, Russian, Spanish, Serbian, Slovak, Slovenian, Swedish, Thai, Turkish, Ukrainian, Vietnamese"""

    def cmd_T(self, argv):
        """Translate query"""
        if argv == None or len(argv) < 2:
            return

        langpair = argv[0]
        query = ' '.join(argv[1:])
        params = {'v': '1.0', 'langpair':langpair, 'q': self.utf8_str(query)}
        url = 'http://ajax.googleapis.com/ajax/services/language/translate?'
        params = urllib.urlencode(params)
        f = urllib.urlopen(url + params)
        res = decode_json(f.read())
        if res['responseData']:
            return res['responseData']['translatedText']
        return res['responseDetails']


Plugin.register(Translate())
Пример #5
0
def main():
    Plugin.load()
    application = webapp.WSGIApplication([('/handler', LingrvantHandler),
                                          ('/(.*)', LingrvantHomepage)],
                                         debug=True)
    wsgiref.handlers.CGIHandler().run(application)
Пример #6
0
# Copyright (c) 2009 Naoki Hiroshima
# You can redistribute this and/or modify this under the same terms as Python.

import re
from lingrvant import Plugin


class System(Plugin):
    def help(self):
        """Show help"""
        return """!list
!help [module name]"""

    def cmd_help(self, argv):
        """!help handler."""
        if len(argv):
            for plugin in Plugin.plugins:
                if argv[0].lower() == plugin.name().lower():
                    return plugin.help()
        return self.help()

    def cmd_list(self, argv):
        """!list handler."""
        msg = []
        for plugin in Plugin.plugins:
            msg.append(plugin.name())
        return ", ".join(msg)


Plugin.register(System())
Пример #7
0
            for i in items:
                s.append(r[i])
            a.append('\n'.join(s))
        s = '\n.\n'.join(a)
        s = s.replace('<b>', '').replace('</b>', '')
        return self.decode_htmlentities(s)

    def decode_htmlentities(self, s):
        """ Written by http://github.com/sku """
        def substitute_entity(match):
            ent = match.group(3)
            if match.group(1) == "#":
                # decoding by number
                if match.group(2) == '':
                    # number is in decimal
                    return unichr(int(ent))
                elif match.group(2) == 'x':
                    # number is in hex
                    return unichr(int('0x' + ent, 16))
            else:
                # they were using a name
                cp = n2cp.get(ent)
                if cp: return unichr(cp)
                else: return match.group()

        entity_re = re.compile(r'&(#?)(x?)(\w+);')
        return entity_re.subn(substitute_entity, s)[0]


Plugin.register(Google())
Пример #8
0
    else:
      response = self.dispatch(text)
    return response

  def cmd_yf(self, symbol):
    chart = 'http://chart.finance.yahoo.com/z?s=%s&t=1y&q=l&l=on&z=l&p=m50,e200,v&.png' % symbol[0]
    q = self.get_quotes(symbol[0])
    if q:
      s = '%s\n%s (%s)\n%s %s (%s)\nP/E: %s' % (chart, q['name'], q['symbol'], q['last trade'], q['change'][0], q['change'][1], q['p/e'])
    else:
      s = chart
    return s

  def get_quotes(self, symbol):
    try:
      params = urllib.urlencode({'s': symbol, 'f':'snl1crx'})
      url = 'http://download.finance.yahoo.com/d/quotes.csv?'
      f = urllib.urlopen(url + params)
      res = f.read().rstrip().split(',')
      if int(res[2]) == 0: return
      # ['"LNKD"', '"LinkedIn Corporat"', '89.11', '"+12.72 - +16.65%"', '1046.44']
      return {'symbol': res[0].strip('"'),
              'name': res[1].strip('"'),
              'last trade': res[2],
              'p/e': res[4],
              'change': res[3].strip('"').split(' - ')}
    except:
      pass

Plugin.register(Yahoo())
Пример #9
0
def main():
  Plugin.load()
  application = webapp.WSGIApplication([('/handler', LingrvantHandler),
                                        ('/(.*)', LingrvantHomepage)],
                                       debug=True)
  wsgiref.handlers.CGIHandler().run(application)
Пример #10
0
            0]
        q = self.get_quotes(symbol[0])
        if q:
            s = '%s\n%s (%s)\n%s %s (%s)\nP/E: %s' % (
                chart, q['name'], q['symbol'], q['last trade'], q['change'][0],
                q['change'][1], q['p/e'])
        else:
            s = chart
        return s

    def get_quotes(self, symbol):
        try:
            params = urllib.urlencode({'s': symbol, 'f': 'snl1crx'})
            url = 'http://download.finance.yahoo.com/d/quotes.csv?'
            f = urllib.urlopen(url + params)
            res = f.read().rstrip().split(',')
            if int(res[2]) == 0: return
            # ['"LNKD"', '"LinkedIn Corporat"', '89.11', '"+12.72 - +16.65%"', '1046.44']
            return {
                'symbol': res[0].strip('"'),
                'name': res[1].strip('"'),
                'last trade': res[2],
                'p/e': res[4],
                'change': res[3].strip('"').split(' - ')
            }
        except:
            pass


Plugin.register(Yahoo())
Пример #11
0
  def get_signed_url(self, __url, **extra_params):
    return '%s?%s'%(__url, self.get_signed_body(__url, **extra_params))

  def get_signed_body(self, __url,**extra_params):
    kwargs = {
      'oauth_consumer_key': config.twitter_consumer_key,
      'oauth_signature_method': 'HMAC-SHA1',
      'oauth_version': '1.0',
      'oauth_timestamp': int(time()),
      'oauth_nonce': getrandbits(64),
      'oauth_token': config.twitter_oauth_token,
      }

    kwargs.update(extra_params)
    key = encode(config.twitter_consumer_secret) + '&' + encode(config.twitter_oauth_token_secret)
    message = '&'.join(map(encode, [
          'GET', __url, '&'.join(
            '%s=%s' % (encode(k), encode(kwargs[k])) for k in sorted(kwargs)
            )
          ]))

    kwargs['oauth_signature'] = hmac(
      key, message, sha1
      ).digest().encode('base64')[:-1]

    return urlencode(kwargs)


Plugin.register(Twitter())
Пример #12
0
            text = r['AbstractText']
        elif len(r['RelatedTopics']) > 0:
            text = r['RelatedTopics'][0]['Text']
            if 'FirstURL' in r['RelatedTopics'][0]:
                text += " " + r['RelatedTopics'][0]['FirstURL']
        elif len(r['Results']) > 0:
            text = r['Results'][0]['Text']
            if 'FirstURL' in r['Results'][0]:
                text += " " + r['Results'][0]['FirstURL']
        else:
            return 'dunno nuttin bout it'
        text += " - Powered by Duck Duck Go"
        if 'Image' in r:
            text += "\n" + r['Image']
        return text

    def query(self, property, argv):
        """Make a query to DuckDuckGo."""
        if argv == None:
            return

        query = ' '.join(argv)
        params = {'o': 'json', 'q': self.utf8_str(query)}
        url = 'http://duckduckgo.com/?'
        params = urllib.urlencode(params)
        f = urllib.urlopen(url + params)
        return decode_json(f.read())


Plugin.register(DuckDuckGo())
Пример #13
0
    def convert(self, src):
        src = self.normalize(src)
        arr = []
        skip = 0
        for pos in xrange(len(src)):
            if skip > 0:
                skip -= 1
                continue
            slen = 5
            f = False
            while slen:
                slen -= 1
                temp = src[pos:pos+slen]
                if not temp in HIRAGANYDIC: continue
                f = True
                kana = HIRAGANYDIC[temp]
                skip = 1 if slen == 2 else slen-1
                if slen == 2:
                    if kana == HIRAGANYDIC['tt'] or kana == HIRAGANYDIC['TT']:
                        skip = 0
                arr.append(str(kana))
                break

            if not f:
                arr.append(str(src[pos]))

        return ''.join(arr)


Plugin.register(Hiragany())
Пример #14
0
            text = r['AbstractText']
        elif len(r['RelatedTopics']) > 0:
            text = r['RelatedTopics'][0]['Text']
            if 'FirstURL' in r['RelatedTopics'][0]:
                text += " " + r['RelatedTopics'][0]['FirstURL']
        elif len(r['Results']) > 0:
            text = r['Results'][0]['Text']
            if 'FirstURL' in r['Results'][0]:
                text += " " + r['Results'][0]['FirstURL']
        else:
            return 'dunno nuttin bout it'
        text += " - Powered by Duck Duck Go"
        if 'Image' in r:
            text += "\n" + r['Image']
        return text

    def query(self, property, argv):
        """Make a query to DuckDuckGo."""
        if argv == None:
            return

        query = ' '.join(argv)
        params = {'o': 'json', 'q': self.utf8_str(query)}
        url = 'http://duckduckgo.com/?'
        params = urllib.urlencode(params)
        f = urllib.urlopen(url + params)
        return decode_json(f.read())


Plugin.register(DuckDuckGo())
Пример #15
0
            s = []
            for i in items:
                s.append(r[i])
            a.append('\n'.join(s))
        s = '\n.\n'.join(a)
        s = s.replace('<b>', '').replace('</b>', '')
        return self.decode_htmlentities(s)

    def decode_htmlentities(self, s):
        """ Written by http://github.com/sku """
        def substitute_entity(match):
            ent = match.group(3)
            if match.group(1) == "#":
                # decoding by number
                if match.group(2) == '':
                    # number is in decimal
                    return unichr(int(ent))
                elif match.group(2) == 'x':
                    # number is in hex
                    return unichr(int('0x'+ent, 16))
            else:
                # they were using a name
                cp = n2cp.get(ent)
                if cp: return unichr(cp)
                else: return match.group()
        entity_re = re.compile(r'&(#?)(x?)(\w+);')
        return entity_re.subn(substitute_entity, s)[0]


Plugin.register(Google())
Пример #16
0
        else:
            response = self.dispatch(text)
        return response

    def cmd_echo(self, argv):
        """!echo handler"""
        if re.match('^@[a-zA-Z]+$', argv[-1]):
            params = {
                'text': ' '.join(argv[:-1]).encode('utf-8'),
                'room': argv[-1][1:],
                'bot': config.bot_id,
                'bot_verifier': self.bot_verifier
            }
            url = 'http://lingr.com/api/room/say?' + urllib.urlencode(params)
            try:
                f = urllib2.urlopen(url)
                res = decode_json(f.read())
                if res['status'] == 'ok':
                    result = 'Posted'
                else:
                    result = res['detail']
            except Exception, e:
                result = str(e)
        else:
            result = ' '.join(argv)

        return result


Plugin.register(Echo())
Пример #17
0
        url = 'http://www.quotationspage.com/random.php3'
        params = {}
        params['number'] = 4
        params['collection[]'] = 'mgm'
        params['collection[]'] = 'motivate'
        params['collection[]'] = 'classic'
        params['collection[]'] = 'coles'
        params['collection[]'] = 'lindsly'
        params['collection[]'] = 'poorc'
        params['collection[]'] = 'altq'
        params['collection[]'] = '20thcent'
        params['collection[]'] = 'bywomen'
        params['collection[]'] = 'devils'
        params['collection[]'] = 'contrib'
        params = urllib.urlencode(params)
        f = urllib.urlopen(url, params)
        q = f.read()
        m = self.re_quote.search(q)
        if m:
            quote = self.remove_tags(m.group(1))
            author = self.remove_tags(m.group(2))
            return "%s --- %s" % (quote, author)
        return 'no quote found'

    def remove_tags(self, html):
        """Remove HTML tags and leading/trailing spaces."""
        return self.re_tag.sub('', html).strip()


Plugin.register(QOTD())
Пример #18
0
        if m:
            result.append(
                'http://maps.google.com/maps/api/staticmap?zoom=15&size=640x320&markers=%s&sensor=false&n.gif'
                % m.group(1))
        m = self.re_img.findall(q)
        if m:
            for i in m:
                result.append(i)

        return "\n".join(result)

    def cmd_instagram(self, url):
        instagram = url + '/media/?size=l'
        logging.info('instagram: %s', instagram)
        url = urllib2.urlopen(instagram).geturl()
        logging.info('result: %r', url)
        return url

    def cmd_fetch(self, argv):
        url = '+'.join(argv)
        if re.match('^http(?s)://', url):
            logging.info('fetch: %r', url)
            f = urllib.urlopen(url)
            buf = f.read()
            logging.info('result: size: %d', len(buf))
            logging.debug('result: %r', buf[:512])
            return '%r' % buf[:512]


Plugin.register(Snippet())
Пример #19
0
    def get_signed_url(self, __url, **extra_params):
        return '%s?%s' % (__url, self.get_signed_body(__url, **extra_params))

    def get_signed_body(self, __url, **extra_params):
        kwargs = {
            'oauth_consumer_key': config.twitter_consumer_key,
            'oauth_signature_method': 'HMAC-SHA1',
            'oauth_version': '1.0',
            'oauth_timestamp': int(time()),
            'oauth_nonce': getrandbits(64),
            'oauth_token': config.twitter_oauth_token,
        }

        kwargs.update(extra_params)
        key = encode(config.twitter_consumer_secret) + '&' + encode(
            config.twitter_oauth_token_secret)
        message = '&'.join(
            map(encode, [
                'GET', __url, '&'.join('%s=%s' % (encode(k), encode(kwargs[k]))
                                       for k in sorted(kwargs))
            ]))

        kwargs['oauth_signature'] = hmac(key, message,
                                         sha1).digest().encode('base64')[:-1]

        return urlencode(kwargs)


Plugin.register(Twitter())
Пример #20
0
# Copyright (c) 2009 Naoki Hiroshima
# You can redistribute this and/or modify this under the same terms as Python.

import re
from lingrvant import Plugin


class System(Plugin):
    def help(self):
        """Show help"""
        return """!list
!help [module name]"""

    def cmd_help(self, argv):
        """!help handler."""
        if len(argv):
            for plugin in Plugin.plugins:
                if argv[0].lower() == plugin.name().lower():
                    return plugin.help()
        return self.help()

    def cmd_list(self, argv):
        """!list handler."""
        msg = []
        for plugin in Plugin.plugins:
            msg.append(plugin.name())
        return ', '.join(msg)


Plugin.register(System())
Пример #21
0
        response = str(eval('(%s)' % text[:-1]))
      except:
        pass
    else:
      response = self.dispatch(text)
    return response

  def cmd_echo(self, argv):
    """!echo handler"""
    if re.match('^@[a-zA-Z]+$', argv[-1]):
      params = {'text':' '.join(argv[:-1]).encode('utf-8'),
                'room':argv[-1][1:],
                'bot':config.bot_id,
                'bot_verifier':self.bot_verifier}
      url = 'http://lingr.com/api/room/say?' + urllib.urlencode(params)
      try:
        f = urllib2.urlopen(url)
        res = decode_json(f.read())
        if res['status'] == 'ok':
          result = 'Posted'
        else:
          result = res['detail']
      except Exception, e:
        result = str(e)
    else:
      result = ' '.join(argv)

    return result

Plugin.register(Echo())