Example #1
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
Example #2
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
Example #3
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
Example #4
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
Example #5
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
Example #6
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)
Example #7
0
 def setUp(self):
   self.p = TwitterTextPlugin()
   self.n = IRCMessage("#test-channel", "http://identi.ca/notice/98533495", "josema", True)
Example #8
0
 def setUp(self):
   self.channel = "#test-channel"
   self.user = "******"
   self.m = IRCMessage(self.channel, "---", self.user, True)
Example #9
0
def run_bot():
    while 1:
        ircmsg = ircsock.recv(8192)
        ircmsg = ircmsg.strip('\n\r')
        # ping
        if ircmsg.find('PING :') != -1:
            ping()
            continue

        print
        print ircmsg

        if ircmsg[0] != ':':
            continue

        message = IRCMessage(ircmsg)
        print message

        if message.msgType == 'INVITE':
            joinchan(message.channel)
            sendmsg(message.channel, '안녕하세요, 업무 봇입니다')
            sendmsg(message.channel, '업무 추가/제거는 주인만 가능하고 열람은 자유입니다')

        elif message.msgType == 'MODE':
            if message.msg == u'+o 업무봇':
                sendmsg(message.channel, '감사합니다 :)')
            if message.msg == u'-o 업무봇':
                sendmsg(message.channel, '......')

        elif message.msgType == 'PRIVMSG':
            parse = re.match(ur'업무봇\s+조회\s*(?P<limit>전체|[0-9]+)?', message.msg)
            if parse:
                worklist = dao.query(Work).filter(Work.done == False).order_by(
                    Work.due)
                if worklist.count() == 0:
                    sendmsg(message.channel, '남은 할 일이 없습니다')
                else:
                    sendmsg(message.channel, '할 일 목록 :')
                    limit = 5
                    if parse.group('limit') == u'전체':
                        limit = None
                    elif parse.group('limit') != None:
                        limit = int(parse.group('limit').decode('utf-8'))
                    for work in worklist[:limit]:
                        sendmsg(message.channel, '%s' % work)
            if re.match(ur'업무봇\s+(추가|제거|삭제|완료|종료)\s*(.*)', message.msg):
                if message.sender != '[email protected]':
                    sendmsg(message.channel, '봇 주인만 업무 관리를 할 수 있습니다')
                else:
                    work_pattern = re.compile(
                        ur'''
                        (?P<due_day>
                                ((다+음|이번)주\s+[월화수목금토일]요일)
                            |   (오늘|내일|모레|\d+일\s*후)
                            |   ((\d+월\s*)?\d+일)
                        )?\s*
                        (?P<due_time>
                                (\d+시\s*((\d+분)|반)?)
                        )?\s*
                        (?P<title>.*)
                        ''', re.VERBOSE)

                    parse = re.match(ur'업무봇\s+추가\s+(?P<content>.*)',
                                     message.msg)
                    if parse:
                        work_parse = work_pattern.match(parse.group('content'))
                        if work_parse:
                            newWork = Work(work_parse.group('title'),
                                           work_parse.group('due_day'),
                                           work_parse.group('due_time'))
                            dao.add(newWork)
                            try:
                                dao.commit()
                            except exc.SQLAlchemyError:
                                sendmsg(message.channel, '이미 존재하는 업무입니다')
                                dao.rollback()
                            else:
                                sendmsg(message.channel,
                                        '%s 추가되었습니다' % newWork)

                    parse = re.match(ur'업무봇\s+(제거|삭제)\s+(?P<content>.*)',
                                     message.msg)
                    if parse:
                        print parse.group('content')
                        work = dao.query(Work).filter(
                            Work.name == parse.group('content')).first()
                        dao.delete(work)
                        dao.commit()
                        sendmsg(message.channel, '%s 제거되었습니다' % work)

                    parse = re.match(ur'업무봇\s+(완료|종료)\s+(?P<content>.*)',
                                     message.msg)
                    if parse:
                        work = dao.query(Work).filter(
                            Work.name == parse.group('content')).first()
                        work.done = True
                        work.finished = datetime.now()
                        dao.add(work)
                        dao.commit()