Пример #1
0
 def testSimplePing(self):
     channel = "#test-channel"
     user = "******"
     m = IRCMessage(channel, "---", user, True)
     response = self.p.execute(m, None)
     pong = IRCMessage(channel, "pong", user, True)
     self.assertEquals(response, pong)
Пример #2
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
Пример #3
0
  def get_user_track(self, ircMsg):
    """Gets the selected user track, returns an IRCMessage."""
    m = IRCMessage(user=ircMsg.user, channel=ircMsg.channel)
    user_fm = ircMsg.tokens[-1]
    user = self.last.get_user(user_fm)
    logging.info("Getting last.fm user {0}".format(user_fm))
    try:
      recent_tracks = user.get_recent_tracks()
    except:
      m.msg = "No user with that name."
      return m

    try:
      last_track = user.get_now_playing()
      if not last_track:
        last_track = recent_tracks[0].track
    except:
      m.msg = "No tracks avaliable for that username."
      return m

    tags_string =  u" , ".join([tag[0].name for tag in last_track.get_top_tags(4)])

    m.msg = u'User {0} is listening to: {1} - {2}: tags [ {3} ]'.format(user_fm, last_track.title,
      last_track.artist.name, tags_string)
    return m
Пример #4
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
Пример #5
0
  def get_user_track(self, ircMsg):
    """Gets the selected user track, returns an IRCMessage."""
    m = IRCMessage(user=ircMsg.user, channel=ircMsg.channel)
    user_s = ircMsg.msg.split(' ')[2]
    user = self.last.get_user(user_s)
    logging.info("Getting last.fm user {0}".format(user_s))
    try:
      recent_tracks = user.get_recent_tracks()
    except:
      m.msg = "No user with that name."
      return m

    try:
      last_track = user.get_now_playing()
      if not last_track:
        last_track = recent_tracks[0].track
    except:
      m.msg = "No tracks avaliable for that username."
      return m

    tags_string =  u" , ".join([tag[0].name for tag in last_track.get_top_tags(4)])

    m.msg = u'User {0} is listening to: {1} - {2}: tags [ {3} ]'.format(user_s, last_track.title,
      last_track.artist.name, tags_string)
    return m
Пример #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
Пример #7
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
Пример #8
0
    def run(self):
        while True:
            ircmsg = self.ircsock.recv(8192)
            ircmsg = ircmsg.decode(errors='ignore').strip('\n\r')
            if DEBUG:
                print(ircmsg)
            message = IRCMessage(ircmsg)
            if message.isValid():
                if message.msgType == 'PING':
                    self.ping()
                elif message.msgType == 'INVITE':
                    if message.target == self.botnick:
                        self.joinchan(message.channel)
                elif message.msgType == 'PRIVMSG':
                    if 'KeyJoin' == message.msg[:7]:
                        msg_split = message.msg.split()
                        if len(msg_split) == 3:
                            self.joinchan(msg_split[1], msg_split[2])

                    if '옵뿌려!' in message.msg:
                        members = self.listmember(message.channel).split(' ')
                        for mem in members:
                            if mem[0] != '@':
                                self.ircsock.send(
                                    ('MODE ' + message.channel + ' +o ' + mem +
                                     '\n').encode())

                else:
                    if LOG_ENABLE:
                        print(message)
                    if self.msgQueue is not None:
                        self.msgQueue.put({'type': 'irc', 'content': message})
Пример #9
0
  def pull(self, ircMsg):
    user = ircMsg.user
    message = ircMsg.msg
    args = message.split() #self.split_args(ircMsg)
    userid = args[2]
    if len(args) > 3:
      index = int(args[3])
    else:
      index = 0

    m = IRCMessage()

    #m.msg = _("msgIdentiPost").format(user, post)

    try:
      self.oauth()
      self.api = tweepy.API(self.auth, host = self.host, api_root = self.api_root)
      timeline = self.api.user_timeline(userid)
      #TODO: add support to pull an specific index
      m.msg = u"@{0}: {1}".format(userid, timeline[index].text)
    except:
      import traceback
      traceback.print_exc()
      m.msg("msgIdentiFail")

    return m
Пример #10
0
    def join(self, channel):
        ircmsg = IRCMessage("")

        ircmsg.msg_type = "JOIN"
        ircmsg.cmd = "join"
        ircmsg.args = channel

        self._join(ircmsg)
Пример #11
0
    def execute(self, ircMsg, userRole, regex_group):
        try:
            url = regex_group[0][0]
            msg = IRCMessage()
            msg.channel = ircMsg.channel
            msg.msg = WebTitle.get_title(url)
        except:
            logging.error(":(")

        return msg
Пример #12
0
    def execute(self, ircMsg, userRole, regex_groups):
        try:
            url = regex_groups[0][0]
            msg = IRCMessage()
            msg.channel = ircMsg.channel
            msg.msg = WebTitle.get_title(url)
        except:
            logging.error(":(")

        return msg
Пример #13
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
Пример #14
0
    def execute(self, ircMsg, userRole, regex_group):
        m = IRCMessage()
        m.channel = ircMsg.channel
        r_group = regex_group[0]

        status = self.api.show_status(id = r_group[-1])
        author = r_group[-2]

        m.msg = u"@{0}: {1}".format(author, status.get("text"))
        m.user = ircMsg.user

        return m
Пример #15
0
  def execute(self, ircMsg, userRole, regex_group):
    m = IRCMessage()
    m.channel = ircMsg.channel
    r_group = regex_group[0]

    status = self.api.get_status(r_group[-1])
    if r_group[-2]:
      author = r_group[-2]
    else:
      author = status.author.screen_name
    m.msg = u"@{0}: {1}".format(author, status.text)
    m.user = ircMsg.user
    return m
Пример #16
0
    def execute(self, ircMsg, userRole, regex_group):
        m = IRCMessage()
        m.channel = ircMsg.channel
        r_group = regex_group[0]

        status = self.api.get_status(r_group[-1])
        if r_group[-2]:
            author = r_group[-2]
        else:
            author = status.author.screen_name
        m.msg = u"@{0}: {1}".format(author, status.text)
        m.user = ircMsg.user
        return m
Пример #17
0
  def fetchAndFormatStatus(self, ircMsg, api, regex_group):
    m = IRCMessage()
    m.channel = ircMsg.channel

    status = api.get_status(regex_group[-1])
    if regex_group[-2]:
      author = regex_group[-2]
    else:
      author = status.author.screen_name

    m.msg = u"@{0}: {1}".format(author, status.text)
    m.user = ircMsg.user
    return m
Пример #18
0
 def get_artist_tracks(self, ircMsg):
   """Gets the selected user track, returns an IRCMessage"""
   m = IRCMessage(user=ircMsg.user, channel=ircMsg.channel)
   artist_s = " ".join(ircMsg.msg.split(' ')[2::])
   artist = self.last.get_artist(artist_s)
   logging.info("Getting last.fm artist {0}".format(artist_s))
   try:
     similar_artists = artist.get_similar(limit = 5)
   except:
     m.msg = "No artist with that name."
     return m
   similar_artists_s = u", ".join(map(lambda a: a[0].get_name(), similar_artists))
   m.msg = u"Artists similar to {0} are: {1}".format(artist.get_name().decode("utf-8"), similar_artists_s)
   return m
Пример #19
0
 def get_tag_artists(self, ircMsg):
   """Gets the artists that match the tag, returns an IRCMessage"""
   m = IRCMessage(user=ircMsg.user, channel=ircMsg.channel)
   tag_s = " ".join(ircMsg.msg.split(' ')[2::])
   tag = self.last.get_tag(tag_s)
   logging.info("Getting last.fm tag {0}".format(tag_s))
   try:
     tag_artists = tag.get_top_artists()[:4:]
   except:
     m.msg = "No tag with that name"
     return m
   tag_artists_s = u", ".join(map(lambda a: a[0].get_name(), tag_artists))
   m.msg = u"Artists that match the tag {0} are: {1}".format(tag.get_name().decode("utf-8"), tag_artists_s)
   return m
Пример #20
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
Пример #21
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
Пример #22
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
Пример #23
0
 def get_artist_tracks(self, ircMsg):
   """Gets the selected user track, returns an IRCMessage"""
   m = IRCMessage(user=ircMsg.user, channel=ircMsg.channel)
   artist_s = " ".join(ircMsg.msg.split(' ')[2::])
   artist = self.last.get_artist(artist_s)
   logging.info("Getting last.fm artist {0}".format(artist_s))
   try:
     similar_artists = artist.get_similar(limit = 5)
   except:
     m.msg = "No artist with that name."
     return m
   similar_artists_s = u", ".join(map(lambda a: a[0].get_name(), similar_artists))
   m.msg = u"Artists similar to {0} are: {1}".format(artist.get_name().decode("utf-8"), similar_artists_s)
   return m
Пример #24
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())
Пример #25
0
 def get_tag_albums(self, ircMsg):
   """Gets the artists that match the tag, returns an IRCMessage."""
   m = IRCMessage(user=ircMsg.user, channel=ircMsg.channel)
   tag_s = " ".join(ircMsg.msg.split(' ')[2::])
   tag = self.last.get_tag(tag_s)
   logging.info("Getting last.fm tag {0}".format(tag_s))
   try:
     tag_albums = tag.get_top_albums()[:4:]
   except:
     m.msg = "No tag with that name"
     return m
   tag_albums_s = u", ".join(map(lambda a: a[0].get_name(), tag_albums))
   m.msg = u"Albums that match the tag {0} are: {1}".format(tag.get_name().decode("utf-8"), tag_albums_s)
   return m
Пример #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
Пример #27
0
 def testRepeatedPing(self):
     channel = "#test-channel"
     user1 = "pedro"
     m1 = IRCMessage(channel, "---", user1, True)
     for i in range(self.p.threshold + 1):
         self.p.execute(m1, None)
     self.assertEquals(self.p.counter, self.p.threshold)
     user2 = "pepe"
     m2 = IRCMessage(channel, "---", user2, True)
     self.p.execute(m2, None)
     self.assertEquals(self.p.counter, 0)
     self.p.execute(m1, None)
     self.assertEquals(self.p.counter, 0)
     for i in range(self.p.threshold + 1):
         self.p.execute(m2, None)
     self.assertEquals(self.p.counter, self.p.threshold)
Пример #28
0
 def run(self):
     while True:
         ircmsg = self.ircsock.recv(8192)
         try:
             ircmsg = ircmsg.decode().strip("\n\r")
         except e:
             print(e)
         else:
             print(ircmsg)
             message = IRCMessage(ircmsg)
             if message.isValid():
                 print(message)
                 if message.msgType == "PING":
                     self.ping()
                 else:
                     self.msgQueue.put({"type": "irc", "content": message})
Пример #29
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
Пример #30
0
  def post(self, ircMsg):
    user = ircMsg.user
    message = ' '.join(ircMsg.msg.split())

    post = re.sub('^!identica post ', '', message)
    m = IRCMessage()

    m.msg = _("msgIdentiPost").format(user, post)

    try:
      self.oauth()
      self.api = tweepy.API(self.auth, host = self.host, api_root = self.api_root)
      #self.api.update_status(post[:140])
    except:
      m.msg("msgIdentiFail")
      return m
Пример #31
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
Пример #32
0
class IRCMessageTest(unittest.TestCase):
  def setUp(self):
    self.channel = "#test-channel"
    self.user = "******"
    self.m = IRCMessage(self.channel, "---", self.user, True)

  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())


  def testEquality(self):
    n = IRCMessage(self.channel, "---", self.user, True)
    self.assertEquals(self.m, n)
    n.msg = "!-"
    self.assertNotEquals(self.m, n)
    n.msg = self.m.msg
    n.channel = "#"
    self.assertNotEquals(self.m, n)

    ## A fake directed should not be equal.
    n = IRCMessage(self.channel, "---", self.user, False)
    self.m.directed = True
    self.assertNotEquals(self.m, n)

    n.msg = "{0}: {1}".format(n.user, n.msg)
    self.assertNotEquals(self.m, n)

  def testRender(self):
    expected = "{0}: {1}".format(self.m.user, self.m.msg)
    self.assertEquals(self.m.render(), expected)
    expected = self.m.msg
    self.m.directed = False
    self.assertEquals(self.m.render(), expected)
Пример #33
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
Пример #34
0
  def execute(self, ircMsg, userRole):
    m = IRCMessage()
    try:
      msg = ircMsg.msg
      option = msg.rsplit('identica')[1].strip().split(' ')[0]

      if option == 'post':
        m = self.post(ircMsg)
      elif option == 'pull':
        m = self.pull(ircMsg)
    except:
      ## TODO: raise a different exception.
      m.msg =  _("msgIdentiFail")

    m.channel = ircMsg.channel
    m.user = ircMsg.user

    return m
Пример #35
0
 def run(self):
     while True:
         ircmsg = self.ircsock.recv(8192)
         try:
             ircmsg = ircmsg.decode().strip('\n\r')
         except:
             ircmsg = ''
             print("error?!")
             pass
         finally:
             #print(ircmsg)
             message = IRCMessage(ircmsg)
             if message.isValid():
                 #print(message)
                 if message.msgType == 'PING':
                     self.ping()
                 else:
                     self.msgQueue.put({'type': 'irc', 'content': message})
Пример #36
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
Пример #37
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
Пример #38
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
Пример #39
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
Пример #40
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
Пример #41
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
Пример #42
0
Файл: sed.py Проект: 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
Пример #43
0
  def testEquality(self):
    n = IRCMessage(self.channel, "---", self.user, True)
    self.assertEquals(self.m, n)
    n.msg = "!-"
    self.assertNotEquals(self.m, n)
    n.msg = self.m.msg
    n.channel = "#"
    self.assertNotEquals(self.m, n)

    ## A fake directed should not be equal.
    n = IRCMessage(self.channel, "---", self.user, False)
    self.m.directed = True
    self.assertNotEquals(self.m, n)

    n.msg = "{0}: {1}".format(n.user, n.msg)
    self.assertNotEquals(self.m, n)
Пример #44
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
Пример #45
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
Пример #46
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
Пример #47
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
Пример #48
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
Пример #49
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
Пример #50
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
Пример #51
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
Пример #52
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
Пример #53
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
Пример #54
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
Пример #55
0
  def privmsg(self, user, channel, msg):
    """Gets called when the bot receives a message in a channel or via PM.

    Here is contained the main logic of tio_chema. Should dispatch messages
    to the plugins registered, depending if they register for a global or
    a specific trigger keyword.
    It blocks, so it should not include heavy or slow logic.

    Args:
      user: A string containing the origin user.
      channel: A string with the originating channel or PM channel.
      msg: A string containing the message recieved.

    """

    directed = False
    if channel == self.factory.nick:
        directed = True
    message = IRCMessage(channel, msg, user, directed=directed)

    # logging.info(message)
    #TODO: add channel trigger plugins (user defined actions)

    self._parseAndExecute(message)
Пример #56
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
Пример #57
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
Пример #58
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
Пример #59
0
 def setUp(self):
   self.p = TwitterTextPlugin()
   self.n = IRCMessage("#test-channel", "http://identi.ca/notice/98533495", "josema", True)