Ejemplo n.º 1
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
      user = ircMsg.user
      m = IRCMessage()
      definiciones = []
      message = ' '.join(ircMsg.msg.split())
      term = re.sub('^!temblor ', '', message)
      url = "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_day.geojson"
      f = requests.get( url )
      data = json.loads(f.text)

      for feature in data['features']:
        cadena = feature['properties']['place']
        
        if cadena.upper().find( term.upper() ) != -1 :
          definiciones.append( feature )

      size = len( definiciones )
      temblo = definiciones[ randint( 0, size ) ]
      fecha_t = datetime.fromtimestamp( temblo[ 'properties' ][ 'time' ] / 1000 )
      fecha = fecha_t.strftime( '%d/%M/%Y %H:%m:%s')
      
      respuesta = '' + str( temblo[ 'properties' ][ 'mag' ] ) + ' | ' + temblo[ 'properties' ][ 'place' ] +  ' | ' + fecha + ' | '+ temblo[ 'properties' ][ 'url' ] 
      m.msg = respuesta
      m.channel = ircMsg.channel
      m.user = user
      m.directed = True
      return m
Ejemplo n.º 2
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        
        command = ircMsg.msg.split(' ')
        command_type = command[1]
        
        irc_msg = IRCMessage()
        irc_msg.channel = ircMsg.channel
        irc_msg.user = ircMsg.user
        irc_msg.directed = True
        
        try:
            args = command[2]
        
            func = self.function_dict[command_type]

            if args != '' or args is not None:
                print args;
                irc_msg.msg = func(args)

            else:
                irc_msg.msg = func('help')
                
        except:
            irc_msg.msg =  self.help(None)
            logging.error('Error processing commands')
            
        return irc_msg
Ejemplo n.º 3
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        definiciones = []
        message = ' '.join(ircMsg.msg.split())
        path = re.sub('^!tiny ', '', message)
        if not path:
            path = message
        print path
        if not path.startswith('http'):
            path = '%s%s' % ('http://', path)

        payload = {'url': path}
        url = "http://tinyurl.com/api-create.php?"

        f = requests.get(url, params=payload)
        data = f.text

        if data == '':
            respuesta = 'No se pudo transformar la url marica'
        else:
            respuesta = data

        m.msg = respuesta
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 4
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        definiciones = []
        message = ' '.join(ircMsg.msg.split())

        cal = subprocess.Popen(['calendar'], stdout=subprocess.PIPE)
        wc = subprocess.Popen(['wc', '-l'],
                              stdin=cal.stdout,
                              stdout=subprocess.PIPE)
        num = wc.communicate()
        numero = int(num[0])
        numero = randint(0, numero)
        cal = subprocess.Popen(['calendar'], stdout=subprocess.PIPE)
        head = subprocess.Popen(['head', '-' + str(numero)],
                                stdin=cal.stdout,
                                stdout=subprocess.PIPE)
        tail = subprocess.Popen(['tail', '-1'],
                                stdin=head.stdout,
                                stdout=subprocess.PIPE)
        resp = tail.communicate()
        if len(resp) > 0:
            respuesta = resp[0]
        else:
            respuesta = ''
        #calendar | wc -l ; calendar | head -rand | tail -1
        m.msg = '' + respuesta
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 5
0
 def execute(self, ircMsg, userRole, *args, **kwargs):
     user = ircMsg.user
     m = IRCMessage()
     definiciones = []
     message = ' '.join(ircMsg.msg.split())
     
     cal = subprocess.Popen( [ 'calendar' ], stdout=subprocess.PIPE )
     wc = subprocess.Popen( [ 'wc', '-l' ], stdin=cal.stdout, stdout=subprocess.PIPE )
     num = wc.communicate()
     numero = int( num[0] )
     numero = randint( 0, numero )
     cal = subprocess.Popen( [ 'calendar'], stdout=subprocess.PIPE )
     head = subprocess.Popen( [ 'head', '-' + str( numero ) ], stdin=cal.stdout, stdout=subprocess.PIPE )
     tail = subprocess.Popen( [ 'tail', '-1' ], stdin=head.stdout, stdout=subprocess.PIPE )
     resp = tail.communicate();
     if len( resp ) > 0 :
       respuesta = resp[ 0 ]
     else:
       respuesta = ''
     #calendar | wc -l ; calendar | head -rand | tail -1
     m.msg = '' + respuesta
     m.channel = ircMsg.channel
     m.user = user
     m.directed = True
     return m
Ejemplo n.º 6
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        definiciones = []
        message = ' '.join(ircMsg.msg.split())
        term = re.sub('^!urbano ', '', message)

        payload = {'term': term}
        url = "http://www.urbandictionary.com/define.php?"

        f = requests.get(url, params=payload)
        data = f.text

        soup = BeautifulSoup(data)
        tag = soup.find_all('div', attrs={'class': 'definition'})

        for tagita in tag:
            if type(tagita.string) != types.NoneType:
                definiciones.append(tagita.string.strip())

        respuesta = definiciones[randint(0, len(definiciones) - 1)]

        m.msg = respuesta
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 7
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
      user = ircMsg.user
      m = IRCMessage()
      definiciones = []
      message = ' '.join(ircMsg.msg.split())
      term = re.sub('^!urbano ', '', message)

      payload = {'term': term  }
      url = "http://www.urbandictionary.com/define.php?"    

      f = requests.get( url, params=payload)
      data = f.text

      soup = BeautifulSoup( data )
      tag = soup.find_all('div', attrs={'class' : 'definition' } )

      for tagita in tag:
        if type(tagita.string) != types.NoneType :
          definiciones.append( tagita.string.strip() )

      respuesta = definiciones[ randint( 0, len( definiciones ) - 1 ) ]

      m.msg = respuesta
      m.channel = ircMsg.channel
      m.user = user
      m.directed = True
      return m
Ejemplo n.º 8
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
      user = ircMsg.user
      m = IRCMessage()
      term = ' '.join(ircMsg.arguments)

      try:
        temblo = self.get_quake(term)
      except Exception as e:
        ircMsg.msg = e.args[0]
        return ircMsg

      ## Converting UNIX timestamp to human readable time.
      date_t = datetime.fromtimestamp(temblo['properties']['time'] / 1000)
      date = date_t.isoformat()

      response_string = "Quake in: {0} | Magnitude: {1} | Time: {2} | URI: {3}".format(
          temblo[ 'properties' ][ 'place' ],
          temblo[ 'properties' ][ 'mag' ],
          date,
          temblo[ 'properties' ][ 'url' ]
        )
      m.msg = response_string
      m.channel = ircMsg.channel
      m.user = user
      m.directed = True
      return m
Ejemplo n.º 9
0
    def execute(self, ircMsg, userRole, *args, **kwargs):

        command = ircMsg.msg.split(' ')
        command_type = command[1]

        irc_msg = IRCMessage()
        irc_msg.channel = ircMsg.channel
        irc_msg.user = ircMsg.user
        irc_msg.directed = True

        try:
            args = command[2]

            func = self.function_dict[command_type]

            if args != '' or args is not None:
                print args
                irc_msg.msg = func(args)

            else:
                irc_msg.msg = func('help')

        except:
            irc_msg.msg = self.help(None)
            logging.error('Error processing commands')

        return irc_msg
Ejemplo n.º 10
0
 def execute(self, ircMsg, userRole, *args, **kwargs):
   user = ircMsg.user
   m = IRCMessage()
   message = ' '.join(ircMsg.msg.split())
   lista_articulos = self.devolver_lista_de(self.baseurl)
   hp=randint(0,len(lista_articulos)-1)
   m.msg=''+lista_articulos[hp][2][:228] + '...... publicado el: ' + lista_articulos[hp][3] + ' en la seccion ' + lista_articulos[hp][9]
   m.channel = ircMsg.channel
   m.user = user
   m.directed = True
   return m
Ejemplo n.º 11
0
 def execute(self, ircMsg, userRole, *args, **kwargs):
     user = ircMsg.user
     m = IRCMessage()
     message = ' '.join(ircMsg.msg.split())
     lista_articulos = self.devolver_lista_de(self.baseurl)
     hp = randint(0, len(lista_articulos) - 1)
     m.msg = '' + lista_articulos[hp][
         2][:228] + '...... publicado el: ' + lista_articulos[hp][
             3] + ' en la seccion ' + lista_articulos[hp][9]
     m.channel = ircMsg.channel
     m.user = user
     m.directed = True
     return m
Ejemplo n.º 12
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user

        toko = ircMsg.tokens[0]
        factz = self.db.get_factz(unicode(toko))

        m = IRCMessage()
        m.msg = "{}".format(factz)
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        logging.debug("Queried factz :{0}".format(factz))
        return m
Ejemplo n.º 13
0
 def execute(self, ircMsg, userRole, *args, **kwargs):
     user = ircMsg.user
     m = IRCMessage()
     definiciones = []
     message = ' '.join(ircMsg.msg.split())
     
     p = subprocess.Popen(["fortune", "-a", "-n", "160", "-s"], stdout=subprocess.PIPE)
     output, err = p.communicate()
     #TODO manejar err
     m.msg = output
     m.channel = ircMsg.channel
     m.user = user
     m.directed = True
     return m
Ejemplo n.º 14
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
      user = ircMsg.user
      m = IRCMessage()
      definiciones = []
      message = ' '.join(ircMsg.msg.split())
      topic = re.sub('^!preguntar ', '', message)

      respuesta = self.get_question( topic  )

      m.msg = respuesta
      m.channel = ircMsg.channel
      m.user = user
      m.directed = True
      return m
Ejemplo n.º 15
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
    user = ircMsg.user
    m = IRCMessage()
    conn = kwargs["connection"]
    m.msg = unicode()
    all_rows = conn.execute("select * from users").fetchall()
    choice = random.choice(all_rows)
    m.msg = "The selected user is {0}".format(choice[0])

    m.channel = ircMsg.channel
    m.user = user
    m.directed = True
    logging.debug("User: {0} hit the DB".format(user))
    return m
Ejemplo n.º 16
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()

        m.msg = unicode()
        all_rows = conn.execute("select * from users").fetchall()
        choice = random.choice(all_rows)
        m.msg = "The selected user is {0}".format(choice[0])

        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        logging.debug("User: {0} hit the DB".format(user))
        return m
Ejemplo n.º 17
0
 def testIsInitialized(self):
   self.assertTrue(self.m.is_initialized())
   q = IRCMessage()
   self.assertFalse(q.is_initialized())
   ## Message with no channel should be false.
   q.channel = "#"
   q.msg = "notempty"
   self.assertFalse(q.is_initialized())
   ## Adding directed testing.
   q.channel = self.channel
   q.directed = True
   self.assertFalse(q.is_initialized())
   q.user = self.user
   self.assertTrue(q.is_initialized())
Ejemplo n.º 18
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        definiciones = []
        message = ' '.join(ircMsg.msg.split())
        topic = re.sub('^!preguntar ', '', message)

        respuesta = self.get_question(topic)

        m.msg = respuesta
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 19
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        m = IRCMessage()
        # Genera URL de letras
        letrarandom = lambda: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[random.randint(
            0, 25)]
        # Parsea html de una URL
        sopa = lambda url: BeautifulSoup(
            requests.get(url).content, 'html.parser'
        )  # , from_encoding="utf-8")
        # URL random para encontrar autores
        urlautoresrandom = "http://www.proverbia.net/citasautores.asp?letra=" + letrarandom(
        )
        # Sopa de autores
        sopa_de_autores = sopa(urlautoresrandom)
        # Hacer la link al autor
        links_de_autores = sopa_de_autores.find(
            id='citasautores').find_all('a')
        hrefs_de_autores = map(lambda l: l.get('href'), links_de_autores)
        link_a_autor = "http://www.proverbia.net/" + hrefs_de_autores[
            random.randint(0,
                           len(hrefs_de_autores) - 1)]

        logging.debug("Link a autor: {0}".format(link_a_autor))

        # Cuentas mas de una pagina el autor? Formar la URL
        numero_de_paginas = len(
            sopa(link_a_autor).find(id="paginas").find_all("a"))
        link_a_pagina = link_a_autor

        if numero_de_paginas > 1:
            npage_random = random.randint(1, numero_de_paginas)

            ## Encontrar pagina
            link_a_pagina = link_a_autor + "&page=" + unicode(npage_random)
            logging.debug("Link a pagina: %s" % link_a_pagina)

        # Con la URL de la pagina, formarla
        sopa_de_citas = sopa(link_a_pagina)
        citas = sopa_de_citas.find_all('blockquote')
        cita = citas[random.randint(0, len(citas) - 1)].text.strip()
        autor = sopa_de_citas.find('h1').text.strip()
        profesion = sopa_de_citas.find(id='bio').text.strip()
        texto = u"« {cita} » - {autor} : {profesion}".format(
            cita=cita, autor=autor, profesion=profesion)
        m.channel = ircMsg.channel
        m.user = ircMsg.user
        m.directed = True
        logging.debug(u"Proverbia: {0}".format(texto))
        m.msg = texto
        return m
Ejemplo n.º 20
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        definiciones = []
        message = ' '.join(ircMsg.msg.split())

        p = subprocess.Popen(["fortune", "-a", "-n", "160", "-s"],
                             stdout=subprocess.PIPE)
        output, err = p.communicate()
        #TODO manejar err
        m.msg = output
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 21
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
      user = ircMsg.user
      m = IRCMessage()
      message = ' '.join(ircMsg.msg.split())
      numero = re.sub('^!xkcd ', '', message)

      if numero.isdigit():
        respuesta = self.get_comic( numero )
      else:
        respuesta = self.get_current()

      m.msg = respuesta
      m.channel = ircMsg.channel
      m.user = user
      m.directed = True
      return m
Ejemplo n.º 22
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        message = ' '.join(ircMsg.msg.split())
        numero = re.sub('^!xkcd ', '', message)

        if numero.isdigit():
            respuesta = self.get_comic(numero)
        else:
            respuesta = self.get_current()

        m.msg = respuesta
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 23
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        url = 'http://feeds.reuters.com/reuters/topNews'

        req = requests.get(url)
        tree = ETree.fromstring(req.text.encode("UTF-8"))
        tag_list = tree.findall("./channel/item")
        tagita = choice(tag_list)
        respuesta = u"{} | {}".format(tagita.find("title").text, tagita.find("link").text)

        m.msg = respuesta
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 24
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
      user = ircMsg.user
      m = IRCMessage()
      url = 'http://hosted2.ap.org/atom/APDEFAULT/3d281c11a96b4ad082fe88aa0db04305'

      f = requests.get( url )
      data = f.text
      soup = BeautifulSoup( data )
      tag = soup.find_all( 'entry' )
      tagita = tag[ randint( 0, len( tag ) -1 ) ]
      respuesta = tagita.title.string.encode( 'utf8')  + ' | ' + tagita.link[ 'href' ].encode( 'utf8' )
      
      m.msg = respuesta
      m.channel = ircMsg.channel
      m.user = user
      m.directed = True
      return m
Ejemplo n.º 25
0
  def execute(self, ircMsg, userRole):
    user = ircMsg.user
    if user == self.last_user:
      self.counter += 1
    else:
      self.counter = 0
      self.last_user = user

    m = IRCMessage()
    if self.counter > self.threshold:
      #TODO: localize
      m.msg = "yarr, it's the {0} time you've called me!".format(self.counter)
    else:
      m.msg = "pong"
    m.channel = ircMsg.channel
    m.user = user
    m.directed = True
    return m
Ejemplo n.º 26
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        url = 'http://feeds.reuters.com/reuters/topNews'

        req = requests.get(url)
        tree = ETree.fromstring(req.text.encode("UTF-8"))
        tag_list = tree.findall("./channel/item")
        tagita = choice(tag_list)
        respuesta = u"{} | {}".format(
            tagita.find("title").text,
            tagita.find("link").text)

        m.msg = respuesta
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 27
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
    user = ircMsg.user
    if user == self.last_user:
      self.counter += 1
    else:
      self.counter = 0
      self.last_user = user

    self.db.put_ping(unicode(user), ircMsg.t)
    m = IRCMessage()
    if self.counter > self.threshold:
      #TODO: localize
      m.msg = "yarr, it's the {0} time you've called me!".format(self.counter)
    else:
      m.msg = "pong"
    m.channel = ircMsg.channel
    m.user = user
    m.directed = True
    logging.debug("User: {0} pinged".format(user))
    return m
Ejemplo n.º 28
0
    def execute(self, ircMsg, userRole, *args, **kwargs):

        command = ircMsg.msg.split(' ')
        command_type = command[1]

        irc_msg = IRCMessage()
        irc_msg.channel = ircMsg.channel
        irc_msg.user = ircMsg.user
        irc_msg.directed = True

        try:

            func = self.func_dict[command_type]
            irc_msg.msg = func(command)

        except:
            irc_msg.msg = self.help(None)
            logging.error("Error processing commands")
            logging.debug(sys.exc_info()[1])
        return irc_msg
Ejemplo n.º 29
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
      user = ircMsg.user
      m = IRCMessage()
      definiciones = []
      message = ' '.join(ircMsg.msg.split())
      board = re.sub('^!4chan ', '', message)
      
      existe = self.get_boards( board )
      respuesta = ''
      if existe :
        respuesta = self.get_threads( board )
        respuesta = 'Te recomiendo este thread ' + respuesta
      else :
        respuesta = 'Ese board mierda no existe'

      m.msg = respuesta
      m.channel = ircMsg.channel
      m.user = user
      m.directed = True
      return m
Ejemplo n.º 30
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
    m = IRCMessage()
    # Genera URL de letras
    letrarandom = lambda : 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'[random.randint(0,25)]
    # Parsea html de una URL
    sopa = lambda url: BeautifulSoup(requests.get(url).content, 'html.parser')# , from_encoding="utf-8")
    # URL random para encontrar autores
    urlautoresrandom = "http://www.proverbia.net/citasautores.asp?letra="+letrarandom()
    # Sopa de autores
    sopa_de_autores = sopa(urlautoresrandom)
    # Hacer la link al autor
    links_de_autores = sopa_de_autores.find(id='citasautores').find_all('a')
    hrefs_de_autores = map(lambda l: l.get('href'), links_de_autores)
    link_a_autor = "http://www.proverbia.net/"+hrefs_de_autores[random.randint(0,len(hrefs_de_autores)-1)]

    logging.debug("Link a autor: {0}".format(link_a_autor))

    # Cuentas mas de una pagina el autor? Formar la URL
    numero_de_paginas = len(sopa(link_a_autor).find(id="paginas").find_all("a"))
    link_a_pagina = link_a_autor

    if numero_de_paginas > 1:
        npage_random = random.randint(1,numero_de_paginas)

        ## Encontrar pagina
        link_a_pagina = link_a_autor + "&page=" + unicode(npage_random)
        logging.debug("Link a pagina: %s" % link_a_pagina)

    # Con la URL de la pagina, formarla
    sopa_de_citas = sopa(link_a_pagina)
    citas = sopa_de_citas.find_all('blockquote')
    cita = citas[random.randint(0,len(citas)-1)].text.strip()
    autor = sopa_de_citas.find('h1').text.strip()
    profesion = sopa_de_citas.find(id='bio').text.strip()
    texto = u"« {cita} » - {autor} : {profesion}".format(cita=cita, autor=autor, profesion=profesion)
    m.channel = ircMsg.channel
    m.user = ircMsg.user
    m.directed = True
    logging.debug(u"Proverbia: {0}".format(texto))
    m.msg = texto
    return m
Ejemplo n.º 31
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        if user == self.last_user:
            self.counter += 1
        else:
            self.counter = 0
            self.last_user = user

        self.db.put_ping(unicode(user), ircMsg.t)
        m = IRCMessage()
        if self.counter > self.threshold:
            #TODO: localize
            m.msg = "yarr, it's the {0} time you've called me!".format(
                self.counter)
        else:
            m.msg = "pong"
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        logging.debug("User: {0} pinged".format(user))
        return m
Ejemplo n.º 32
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
      user = ircMsg.user
      m = IRCMessage()
      definiciones = []
      split_msg = ircMsg.arguments
      try:
        #TODO: fix more languages for wiki plugin
        if split_msg[0] in ['es', 'en', 'de', 'fr']:
          url = "http://"+ split_msg[0] +".wikipedia.org/wiki/"
          split_msg = split_msg[1::]
        else:
          #TODO: wiki base url should depend on language
          url = "http://es.wikipedia.org/wiki/"
      except:
        url = "http://es.wikipedia.org/wiki/"

      term = re.sub( ' ', '_', ' '.join(split_msg))
      url += term

      logging.debug("Fetching wiki page: '{0}'.".format(url))

      f = requests.get(url)
      data = f.text
      try:
        soup = BeautifulSoup(data, "html.parser")
        basediv = soup.find('div', attrs={'class' : 'mw-parser-output' })
        peetexts = [pees.text for pees in basediv.findChildren('p')]
        basetext = " ".join(peetexts)
        p = basetext[:350]
      except Exception as e:
        logging.exception("Wiki: An error ocurred")
        ircMsg.msg = "Wiki: An error ocurred."
        return ircMsg

      m.msg = p
      m.channel = ircMsg.channel
      m.user = user
      m.directed = True
      return m
Ejemplo n.º 33
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        irc_msg = IRCMessage()
        irc_msg.channel = ircMsg.channel
        irc_msg.user = ircMsg.user
        irc_msg.directed = True

        try:

            search_query_list = ircMsg.msg.split(' ')
            search_query_list.pop(0)
            search_query = ' '.join(search_query_list)

            result = duckduckgo.query(search_query)

            irc_msg.msg = ' - '.join(
                [result.results[0].text, result.results[0].url])

        except:
            irc_msg.msg = 'Cagadales, el API del pato es una mierda'\
            ' https://duckduckgo.com/api'

        return irc_msg
Ejemplo n.º 34
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        definiciones = []
        split_msg = ircMsg.arguments
        try:
            #TODO: fix more languages for wiki plugin
            if split_msg[0] in ['es', 'en', 'de', 'fr']:
                url = "http://" + split_msg[0] + ".wikipedia.org/wiki/"
                split_msg = split_msg[1::]
            else:
                #TODO: wiki base url should depend on language
                url = "http://es.wikipedia.org/wiki/"
        except:
            url = "http://es.wikipedia.org/wiki/"

        term = re.sub(' ', '_', ' '.join(split_msg))
        url += term

        logging.debug("Fetching wiki page: '{0}'.".format(url))

        f = requests.get(url)
        data = f.text
        try:
            soup = BeautifulSoup(data, "html.parser")
            basediv = soup.find('div', attrs={'class': 'mw-parser-output'})
            peetexts = [pees.text for pees in basediv.findChildren('p')]
            basetext = " ".join(peetexts)
            p = basetext[:350]
        except Exception as e:
            logging.exception("Wiki: An error ocurred")
            ircMsg.msg = "Wiki: An error ocurred."
            return ircMsg

        m.msg = p
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 35
0
Archivo: sed.py Proyecto: killman/bot
  def execute(self, ircMsg, userRole, result):
    m = IRCMessage()
    m.channel = ircMsg.channel
    m.user = ircMsg.user

    groups, lines = result
    group = groups[0]

    logging.debug("RegexTriggerLogged: {0}".format(groups))

    try:
      try:
        index = int(group[0])
      except:
        index = 1
      m.msg = re.sub(group[1], group[2], lines[ircMsg.user][index])
      m.directed = True
    except (IndexError, KeyError):
      #TODO: proper error message
      return ircMsg

    return m
Ejemplo n.º 36
0
    def execute(self, ircMsg, userRole, result):
        m = IRCMessage()
        m.channel = ircMsg.channel
        m.user = ircMsg.user

        groups, lines = result
        group = groups[0]

        logging.debug("RegexTriggerLogged: {0}".format(groups))

        try:
            try:
                index = int(group[0])
            except:
                index = 1
            m.msg = re.sub(group[1], group[2], lines[ircMsg.user][index])
            m.directed = True
        except (IndexError, KeyError):
            #TODO: proper error message
            return ircMsg

        return m
Ejemplo n.º 37
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        user = ircMsg.user
        m = IRCMessage()
        term = ' '.join(ircMsg.arguments)

        try:
            temblo = self.get_quake(term)
        except Exception as e:
            ircMsg.msg = e.args[0]
            return ircMsg

        ## Converting UNIX timestamp to human readable time.
        date_t = datetime.fromtimestamp(temblo['properties']['time'] / 1000)
        date = date_t.isoformat()

        response_string = "Quake in: {0} | Magnitude: {1} | Time: {2} | URI: {3}".format(
            temblo['properties']['place'], temblo['properties']['mag'], date,
            temblo['properties']['url'])
        m.msg = response_string
        m.channel = ircMsg.channel
        m.user = user
        m.directed = True
        return m
Ejemplo n.º 38
0
  def execute(self, ircMsg, userRole, *args, **kwargs):
      user = ircMsg.user
      m = IRCMessage()
      definiciones = []
      split_msg = ircMsg.arguments
      try:
        #TODO: fix more languages for wiki plugin
        if split_msg[0] in ['es', 'en', 'de', 'fr']:
          url = "http://"+ split_msg[0] +".wikipedia.org/wiki/"
          split_msg = split_msg[1::]
        else:
          #TODO: wiki base url should depend on language
          url = "http://es.wikipedia.org/wiki/"
      except:
        url = "http://es.wikipedia.org/wiki/"

      term = re.sub( ' ', '_', ' '.join(split_msg))
      url += term

      logging.debug("Fetching wiki page: '{0}'.".format(url))

      f = requests.get(url)
      data = f.text
      try:
        soup = BeautifulSoup( data )
        tag = soup.find_all('div', attrs={'class' : 'mw-content-ltr' } )
        p = tag[0].p.text[:250]
      except:
        ircMsg.msg = "Wiki: An error ocurred."
        return ircMsg

      m.msg = p
      m.channel = ircMsg.channel
      m.user = user
      m.directed = True
      return m
Ejemplo n.º 39
0
    def execute(self, ircMsg, userRole, *args, **kwargs):
        irc_msg = IRCMessage()
        irc_msg.channel = ircMsg.channel
        irc_msg.user = ircMsg.user
        irc_msg.directed = True

        try:

            search_query_list = ircMsg.msg.split(' ')
            search_query_list.pop(0)
            search_query = ' '.join(search_query_list)

            result = duckduckgo.query(search_query)

            irc_msg.msg = ' - '.join([
                result.results[0].text,
                result.results[0].url
            ])

        except:
            irc_msg.msg = 'Cagadales, el API del pato es una mierda'\
            ' https://duckduckgo.com/api'

        return irc_msg