예제 #1
0
파일: plugin.py 프로젝트: arikb/Meeting
    def doPrivmsg(self, irc, msg):
        """check regular IRC chat for votes"""
        # check for a regular channel message
        if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
            return
        channel = msg.args[0]
        if not irc.isChannel(channel):
            return
        
        # is there an active vote in the channel?
        if not (channel in self._voter_decision):
            return
        
        # get the text of the vote
        if ircmsgs.isAction(msg):
            text = ircmsgs.unAction(msg)
        else:
            text = msg.args[1]
        
        # is it a vote?
        if not text in VALID_VOTE:
            return
        
        # get the voter
        voter = msg.prefix

        # update the cache
        self._voter_decision[channel][voter] = text
 def outFilter(self, irc, msg):
     if msg.command == 'PRIVMSG':
         if ircmsgs.isAction(msg):
             s = ircmsgs.unAction(msg)
         else:
             s = msg.args[1]
         reply = []
         bananaProb = 0.1
         maybeBanana = False
         chance = random.random()
         self.log.debug("bananchance: "+str(chance)+" "+str(bananaProb)+" "+s)
         if chance < bananaProb:
             for word in s.split():
                 if maybeBanana:
                     maybeBanana = False
                     chance = random.random()
                     reply.append("banana")
                 else:
                     reply.append(word)
                 if word == "the":
                     maybeBanana = True
             if ircmsgs.isAction(msg):
                 msg = ircmsgs.action(msg.args[0], " ".join(reply), msg=msg)
             else:
                 msg = ircmsgs.IrcMsg(msg = msg, args=(msg.args[0], " ".join(reply)))
     return msg
예제 #3
0
파일: plugin.py 프로젝트: Mika64/Pingus
 def doPrivmsg(self, irc, msg):
     channel = msg.args[0]
     self.timeout(irc, channel)
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     #channel = msg.args[0]
     if irc.isChannel(channel):
         if ircmsgs.isAction(msg):
             text = ircmsgs.unAction(msg)
         else:
             text = msg.args[1]
         if 'ping' in text.lower():
             text = text.replace('!','')\
                     .replace(',','')\
                     .replace(':','')\
                     .replace('?','')
             if len(text.split()) == 2:        
                 if text.lower().startswith('ping'):
                     self.ping(irc, msg, channel, text, inverse=True)
                 elif text.lower().endswith('ping'):
                     self.ping(irc, msg, channel, text)
         elif 'pong' in text.lower():
             text = text.replace(',','')\
                     .replace(':','')\
                     .replace('!','')\
                     .replace('?','')
             if len(text.split()) == 2:        
                 if text.lower().startswith('pong'):
                     self.pong(irc, msg, channel, text, inverse=True)
                 elif text.lower().endswith('pong'):
                     self.pong(irc, msg, channel, text)
예제 #4
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     channel = msg.args[0]
     if irc.isChannel(channel):
         if ircmsgs.isAction(msg):
             text = ircmsgs.unAction(msg)
         else:
             text = msg.args[1]
         for url in utils.web.httpUrlRe.findall(text):
             if not utils.web.getDomain(url).lower() in self.pastebins:
                 continue
             pastebin = self.pastebins[utils.web.getDomain(url).lower()]
             if pastebin:
                 pbCode = pastebin['regex'].search(url).group(1)
                 newURL = pastebin['url'] % pbCode
                 cmd = self.registryValue("curl") % newURL
                 cmd += "|" + self.registryValue("cpaste")
                 proc = subprocess.Popen(cmd,
                                         stdout=subprocess.PIPE,
                                         stderr=subprocess.PIPE,
                                         shell=True)
                 o, e = proc.communicate()
                 if proc.returncode == 0:
                     irc.reply("Paste has been copied to " +
                               o.decode('ascii').strip())
 def outFilter(self, irc, msg):
     if msg.command == 'PRIVMSG':
         if ircmsgs.isAction(msg):
             s = ircmsgs.unAction(msg)
         else:
             s = msg.args[1]
         reply = []
         bananaProb = 0.1
         maybeBanana = False
         chance = random.random()
         self.log.debug("bananchance: " + str(chance) + " " +
                        str(bananaProb) + " " + s)
         if chance < bananaProb:
             for word in s.split():
                 if maybeBanana:
                     maybeBanana = False
                     chance = random.random()
                     reply.append("banana")
                 else:
                     reply.append(word)
                 if word == "the":
                     maybeBanana = True
             if ircmsgs.isAction(msg):
                 msg = ircmsgs.action(msg.args[0], " ".join(reply), msg=msg)
             else:
                 msg = ircmsgs.IrcMsg(msg=msg,
                                      args=(msg.args[0], " ".join(reply)))
     return msg
예제 #6
0
파일: plugin.py 프로젝트: HacDC/wopr
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     channel = msg.args[0]
     if irc.isChannel(channel):
         if ircmsgs.isAction(msg):
             text = ircmsgs.unAction(msg)
         else:
             text = msg.args[1]
         for url in utils.web.urlRe.findall(text):
             self.fetch_url(irc, channel, url)
예제 #7
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     channel = msg.args[0]
     if irc.isChannel(channel):
         if ircmsgs.isAction(msg):
             text = ircmsgs.unAction(msg)
         else:
             text = msg.args[1]
         for info in present_links(text, color=True):
             irc.reply(info, prefixNick=False)
예제 #8
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     channel = msg.args[0]
     if callbacks.addressed(irc.nick, msg):
         return
     if self.registryValue('titleSnarfer', channel):
         if irc.isChannel(channel):
             if ircmsgs.isAction(msg):
                 text = ircmsgs.unAction(msg)
             else:
                 text = msg.args[1]
             for info in present_links(text, color=True):
                 irc.reply(info, prefixNick=False, private=False, notice=False)
예제 #9
0
    def newf(self, irc, msg, match, *L, **kwargs):
        url = match.group(0)
        channel = msg.args[0]
        if not irc.isChannel(channel) or (ircmsgs.isCtcp(msg)
                                          and not ircmsgs.isAction(msg)):
            return
        if ircdb.channels.getChannel(channel).lobotomized:
            self.log.debug('Not snarfing in %s: lobotomized.', channel)
            return
        if _snarfed.has(channel, url):
            self.log.info('Throttling snarf of %s in %s.', url, channel)
            return
        irc = SnarfIrc(irc, channel, url)

        def doSnarf():
            _snarfLock.acquire()
            try:
                # This has to be *after* we've acquired the lock so we can be
                # sure that all previous urlSnarfers have already run to
                # completion.
                if msg.repliedTo:
                    self.log.debug('Not snarfing, msg is already repliedTo.')
                    return
                f(self, irc, msg, match, *L, **kwargs)
            finally:
                _snarfLock.release()

        if threading.currentThread() is not world.mainThread:
            doSnarf()
        else:
            L = list(L)
            t = UrlSnarfThread(target=doSnarf, url=url)
            t.start()
 def doPrivmsg(self, irc, msg):
     (recipients, text) = msg.args
     for channel in recipients.split(','):
         if irc.isChannel(channel) and not self.logging_disabled.get(channel):
             noLogPrefix = self.registryValue('noLogPrefix', channel)
             if ((noLogPrefix and text.startswith(noLogPrefix)) or
                (text.startswith('@on')) or
                (text.startswith('mb-chat-logger: on')) or
                (text.startswith('mb-chat-logger, on'))):
                 return
             nick = msg.nick or irc.nick
             if ircmsgs.isAction(msg):
                 self.doLog(irc, channel, 'log',
                            '* %s %s', nick, ircmsgs.unAction(msg))
                 self.doLog(irc, channel, 'html',
                            '<span>&bull; <span class="nick">%s</span> %s</span>', 
                            cgi.escape(nick),
                            replaceurls(cgi.escape(ircmsgs.unAction(msg))),
                            cls="action privmsg")
             else:
                 self.doLog(irc, channel, 'log', '<%s> %s', nick, text)
                 self.doLog(irc, channel, 'html', 
                            '<span><span class="nick">&lt;%s&gt;</span> %s</span>', 
                            cgi.escape(nick), 
                            replaceurls(cgi.escape(text)),
                            cls="privmsg")
예제 #11
0
    def doPrivmsg(self, irc, msg):
        channel = msg.args[0]
        linkapi = LinkDBApi()

        if irc.isChannel(channel):
            if ircmsgs.isAction(msg):
                text = ircmsgs.unAction(msg)
            else:
                text = msg.args[1]

            usrmsg = safe_unicode(text)
            for url in utils.web.urlRe.findall(usrmsg):
                if re.search(badurls, url) is not None:
                    continue

                uid = linkapi.insert_and_get_uid(msg.nick)
                urlseen = linkapi.get_url_and_timestamp(url)

                if urlseen is "":
                    titlename = get_url_title(url)
                    if len(titlename) > 0:
                        linkid = linkapi.insert_and_get_linkid(uid, \
                                     titlename, url)
                        irc.reply("Title: %s" % (titlename))
                else:
                    if linkapi.is_link_old(url):
                        linkapi.updateLinkLastseen(url)
                    irc.reply("Title: %s [title updated: %s]" % (urlseen[0], \
                              time.ctime(urlseen[1])))
예제 #12
0
 def newf(self, irc, msg, match, *L, **kwargs):
     url = match.group(0)
     channel = msg.args[0]
     if not irc.isChannel(channel) or (ircmsgs.isCtcp(msg) and not
                                       ircmsgs.isAction(msg)):
         return
     if ircdb.channels.getChannel(channel).lobotomized:
         self.log.debug('Not snarfing in %s: lobotomized.', channel)
         return
     if _snarfed.has(channel, url):
         self.log.info('Throttling snarf of %s in %s.', url, channel)
         return
     irc = SnarfIrc(irc, channel, url)
     def doSnarf():
         _snarfLock.acquire()
         try:
             # This has to be *after* we've acquired the lock so we can be
             # sure that all previous urlSnarfers have already run to
             # completion.
             if msg.repliedTo:
                 self.log.debug('Not snarfing, msg is already repliedTo.')
                 return
             f(self, irc, msg, match, *L, **kwargs)
         finally:
             _snarfLock.release()
     if threading.currentThread() is not world.mainThread:
         doSnarf()
     else:
         L = list(L)
         t = UrlSnarfThread(target=doSnarf, url=url)
         t.start()
예제 #13
0
 def doPrivmsg(self, irc, msg):
     (channel, message) = msg.args
     if callbacks.addressed(irc.nick, msg) or ircmsgs.isCtcp(
             msg) or not irc.isChannel(channel) or not self.registryValue(
                 'enable', channel):
         return
     if msg.nick.lower() in self.registryValue('ignoreNicks', channel):
         log.debug("Cobe: nick %s in ignoreNicks for %s" %
                   (msg.nick, channel))
         return
     if ircmsgs.isAction(msg):
         # If the message was an action...we'll learn it anyways!
         message = ircmsgs.unAction(msg)
     if irc.nick.lower() in message.lower():
         # Were we addressed in the channel?
         probability = self.registryValue('probabilityWhenAddressed',
                                          channel)
     else:
         # Okay, we were not addressed, but what's the probability we should reply?
         probability = self.registryValue('probability', channel)
     #if self.registryValue('stripNicks'):
     #    removenicks = '|'.join(item + '\W.*?\s' for item in irc.state.channels[channel].users)
     #    text = re.sub(r'' + removenicks + '', 'MAGIC_NICK', text)
     self._learn(irc, msg, channel, message,
                 probability)  # Now we can pass this to our learn function!
예제 #14
0
    def doPrivmsg(self, irc, msg):
        if callbacks.addressed(irc.nick, msg): #message is direct command
            return
        (channel, text) = msg.args

        if ircmsgs.isAction(msg):
            text = ircmsgs.unAction(msg)

        learn = self.registryValue('learn', channel)
        reply = self.registryValue('reply', channel)
        replyOnMention = self.registryValue('replyOnMention', channel)
        replyWhenSpokenTo = self.registryValue('replyWhenSpokenTo', channel)

        mention = irc.nick.lower() in text.lower()
        spokenTo = msg.args[1].lower().startswith('%s: ' % irc.nick.lower())

        if replyWhenSpokenTo and spokenTo:
            reply = 100
            text = text.replace('%s: ' % irc.nick, '')
            text = text.replace('%s: ' % irc.nick.lower(), '')

        if replyOnMention and mention:
            if not replyWhenSpokenTo and spokenTo:
                reply = 0
            else:
                reply = 100

        if randint(0, 99) < reply:
            self.reply(irc, msg, text)

        if learn:
            self.learn(irc, msg, text)
예제 #15
0
    def doPrivmsg(self, irc, msg):
        if callbacks.addressed(irc.nick, msg): #message is direct command
            return
        (channel, text) = msg.args

        if ircmsgs.isAction(msg):
            text = ircmsgs.unAction(msg)

        learn = self.registryValue('learn', channel)
        reply = self.registryValue('reply', channel)
        replyOnMention = self.registryValue('replyOnMention', channel)
        replyWhenSpokenTo = self.registryValue('replyWhenSpokenTo', channel)

        mention = irc.nick.lower() in text.lower()
        spokenTo = msg.args[1].lower().startswith('%s: ' % irc.nick.lower())

        if replyWhenSpokenTo and spokenTo:
            reply = 1000
            text = text.replace('%s: ' % irc.nick, '')
            text = text.replace('%s: ' % irc.nick.lower(), '')

        if replyOnMention and mention:
            if not replyWhenSpokenTo and spokenTo:
                reply = 0
            else:
                reply = 1000

        if randint(0, 999) < reply:
            self.reply(irc, msg, text)

        if learn:
            self.learn(irc, msg, text)
예제 #16
0
    def doPrivmsg(self, irc, msg):
        global BADURLS
        channel = msg.args[0]
        linkapi = LinkDBApi()

        if irc.isChannel(channel):
            if ircmsgs.isAction(msg):
                text = ircmsgs.unAction(msg)
            else:
                text = msg.args[1]

            for url in utils.web.urlRe.findall(text):
                if re.search(BADURLS, url) is not None:
                    continue

                url = unicode(url, "utf-8")
                urlseen = linkapi.getByLink(url)
                if urlseen is "":
                    titlename = self.title(url)
                    if len(titlename) > 0:
                        linkapi.insertLink(msg.nick, titlename, url)
                        try:
                            irc.reply("%s [%s]" % (titlename, url))
                        except UnicodeDecodeError:
                            irc.reply("%s [%s]" % (titlename.encode("utf-8"), url))
                else:
                    linkapi.updateLinkLastseen(url)
                    irc.reply("%s [%s]" % (urlseen[2], urlseen[3]))
예제 #17
0
파일: plugin.py 프로젝트: Elwell/supybot
 def doPrivmsg(self, msg):
     isAction = ircmsgs.isAction(msg)
     if ircmsgs.isCtcp(msg) and not isAction:
         return
     self.doPayload(*msg.args)
     if isAction:
         self.actions += 1
예제 #18
0
def combine(msgs, reverse=True, stamps=False, nicks=True, compact=True,
            joiner=r' \ ', nocolor=False):
    """
    Formats and returns a list of IrcMsg objects (<msgs>) as a string.
    <reverse>, if True, prints messages from last to first.
    <stamps>, if True, appends timestamps to messages.
    <reverse>, if True, orders messages by earliest to most recent.
    <compact>, if False, append nicks to consecutive messages
    <joiner>, the character joining lines together (default: ' \ ').
    <nocolor>, if True, strips color from messages.
    Sample output:
        <bigman> DUNK \ <bigbitch> \ bluh \ bluh
    """
    output = []
    lastnick = ''
    for msg in reversed(msgs) if reverse else msgs:
        isaction = ircmsgs.isAction(msg)
        if isaction:
            text = '[%s %s]' % (msg.nick, ircmsgs.unAction(msg))
        else:
            if compact and ircutils.nickEqual(msg.nick, lastnick) or not nicks:
                text = msg.args[1]
            else:
                lastnick = msg.nick
                text = '<%s> %s' % (msg.nick, msg.args[1])
        if stamps:
            stampfmt = '%d-%m-%y %H:%M:%S'
            stamp = time.strftime(stampfmt, time.localtime(msg.receivedAt))
            text = '[{0}] {1}'.format(stamp, text)
        output.append(ircutils.stripFormatting(text))
    return joiner.join(output)
예제 #19
0
def msgtotext(msg):
    """
    Returns only the message text from an IrcMsg (<msg>).
    """
    isaction = ircmsgs.isAction(msg)
    text = ircmsgs.unAction(msg) if isaction else msg.args[1]
    return ircutils.stripFormatting(text), isaction
예제 #20
0
 def _formatPrivmsg(self, nick, network, msg):
     channel = msg.args[0]
     if self.registryValue("includeNetwork", channel):
         network = "@" + network
     else:
         network = ""
     # colorize nicks
     color = self.registryValue("color", channel)  # Also used further down.
     if color:
         nick = ircutils.IrcString(nick)
         newnick = ircutils.mircColor(nick, *ircutils.canonicalColor(nick))
         colors = ircutils.canonicalColor(nick, shift=4)
         nick = newnick
     if ircmsgs.isAction(msg):
         if color:
             t = ircutils.mircColor("*", *colors)
         else:
             t = "*"
         s = format("%s %s%s %s", t, nick, network, ircmsgs.unAction(msg))
     else:
         if color:
             lt = ircutils.mircColor("<", *colors)
             gt = ircutils.mircColor(">", *colors)
         else:
             lt = "<"
             gt = ">"
         s = format("%s%s%s%s %s", lt, nick, network, gt, msg.args[1])
     return s
예제 #21
0
파일: plugin.py 프로젝트: totte/aide
                def f(m, arg=arg):
                    def f1(s, arg):
                        """Since we can't enqueue match objects into the multiprocessing queue,
                        we'll just wrap the function to return bools."""
                        if arg.search(s) is not None:
                            return True
                        else:
                            return False

                    if ircmsgs.isAction(m):
                        m1 = ircmsgs.unAction(m)
                        #return arg.search(ircmsgs.unAction(m))
                    else:
                        m1 = m.args[1]
                        #return arg.search(m.args[1])
                    try:
                        # use a subprocess here, since specially crafted regexps can
                        # take exponential time and hang up the bot.
                        # timeout of 0.1 should be more than enough for any normal regexp.
                        v = commands.process(f1,
                                             m1,
                                             arg,
                                             timeout=0.1,
                                             pn=self.name(),
                                             cn='last')
                        return v
                    except commands.ProcessTimeoutError:
                        return False
예제 #22
0
파일: plugin.py 프로젝트: hashweb/LogsToDB
 def doPrivmsg(self, irc, msg):
     (recipients, text) = msg.args
     for channel in recipients.split(','):
         if irc.isChannel(channel):
             noLogPrefix = self.registryValue('noLogPrefix', channel)
             cap = ircdb.makeChannelCapability(channel, 'logChannelMessages')
             try:
                 logChannelMessages = ircdb.checkCapability(msg.prefix, cap,
                     ignoreOwner=True)
             except KeyError:
                 logChannelMessages = True
             nick = msg.nick or irc.nick
             if msg.tagged('LogsToDB__relayed'):
                 (nick, text) = text.split(' ', 1)
                 nick = nick[1:-1]
                 msg.args = (recipients, text)
             if (noLogPrefix and text.startswith(noLogPrefix)) or \
                     not logChannelMessages:
                 text = '-= THIS MESSAGE NOT LOGGED =-'
             if ircmsgs.isAction(msg):
                 self.doLog(irc, channel,
                            '* %s %s\n', nick, ircmsgs.unAction(msg))
             else:
                 self.doLog(irc, channel, '<%s> %s\n', nick, text)
             
             message = msg.args[1]
             self.logViewerDB.add_message(msg.nick, msg.prefix, message, channel)
             self.logViewerFile.write_message(msg.nick, message)
예제 #23
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     (channel, text) = msg.args
     if irc.isChannel(channel):
         irc = self._getRealIrc(irc)
         if channel not in self.registryValue('channels'):
             return
         ignores = self.registryValue('ignores', channel)
         for ignore in ignores:
             if ircutils.hostmaskPatternEqual(ignore, msg.prefix):
                 self.log.debug('Refusing to relay %s, ignored by %s.',
                                msg.prefix, ignore)
                 return
         # Let's try to detect other relay bots.
         if self._checkRelayMsg(msg):
             if self.registryValue('punishOtherRelayBots', channel):
                 self._punishRelayers(msg)
             # Either way, we don't relay the message.
             else:
                 self.log.warning('Refusing to relay message from %s, '
                                  'it appears to be a relay message.',
                                  msg.prefix)
         else:
             network = self._getIrcName(irc)
             s = self._formatPrivmsg(msg.nick, network, msg)
             m = self._msgmaker(channel, s)
             self._sendToOthers(irc, m)
예제 #24
0
파일: plugin.py 프로젝트: totte/aide
 def doPrivmsg(self, msg):
     isAction = ircmsgs.isAction(msg)
     if ircmsgs.isCtcp(msg) and not isAction:
         return
     self.doPayload(*msg.args)
     if isAction:
         self.actions += 1
예제 #25
0
파일: plugin.py 프로젝트: kytvi2p/Limnoria
 def doPrivmsg(self, irc, msg):
     (recipients, text) = msg.args
     for channel in recipients.split(','):
         if irc.isChannel(channel):
             noLogPrefix = self.registryValue('noLogPrefix', channel)
             cap = ircdb.makeChannelCapability(channel,
                                               'logChannelMessages')
             try:
                 logChannelMessages = ircdb.checkCapability(
                     msg.prefix, cap, ignoreOwner=True)
             except KeyError:
                 logChannelMessages = True
             nick = msg.nick or irc.nick
             if msg.tagged('ChannelLogger__relayed'):
                 (nick, text) = text.split(' ', 1)
                 nick = nick[1:-1]
                 msg.args = (recipients, text)
             if (noLogPrefix and text.startswith(noLogPrefix)) or \
                     not logChannelMessages:
                 text = '-= THIS MESSAGE NOT LOGGED =-'
             if ircmsgs.isAction(msg):
                 self.doLog(irc, channel, '* %s %s\n', nick,
                            ircmsgs.unAction(msg))
             else:
                 self.doLog(irc, channel, '<%s> %s\n', nick, text)
예제 #26
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     irc = callbacks.SimpleProxy(irc, msg)
     if msg.channel:
         payload = msg.args[1]
         words = self.registryValue('randomGrabber.minimumWords',
                                    msg.channel, irc.network)
         length = self.registryValue('randomGrabber.minimumCharacters',
                                     msg.channel, irc.network)
         grabTime = \
         self.registryValue('randomGrabber.averageTimeBetweenGrabs',
                            msg.channel, irc.network)
         channel = plugins.getChannel(msg.channel)
         if self.registryValue('randomGrabber', msg.channel, irc.network):
             if len(payload) > length and len(payload.split()) > words:
                 try:
                     last = int(self.db.select(channel, msg.nick))
                 except dbi.NoRecordError:
                     self._grab(channel, irc, msg, irc.prefix)
                     self._sendGrabMsg(irc, msg)
                 else:
                     elapsed = int(time.time()) - last
                     if (random.random() * elapsed) > (grabTime / 2):
                         self._grab(channel, irc, msg, irc.prefix)
                         self._sendGrabMsg(irc, msg)
예제 #27
0
 def doPrivmsg(self, irc, msg):
     channel = msg.args[0].lower()
     text = msg.args[1].strip()
     # ignore ctcp, action and only messages in a channel.
     # if txt.startswith(conf.supybot.reply.whenAddressedBy.chars()):
     if ircmsgs.isCtcp(msg) or ircmsgs.isAction(msg) or not irc.isChannel(channel):
         return
     # on to the text. check if we're ignoring the text matching regex here.
     if re.match(self.registryValue('ignoreRegex'), text):
         return
     # should we strip urls from text?
     if self.registryValue('stripUrls'):
         text = re.sub(r'(http[^\s]*)', '', text)
     # determine probability if addressed or not.
     if callbacks.addressed(irc.nick, msg):
         text = re.sub('(' + irc.nick + '*?\W+)', '', text, re.IGNORECASE)
         probability = self.registryValue('probabilityWhenAddressed', channel)
     else:
         probability = self.registryValue('probability', channel)
     # should we strip nicks from the text?
     if self.registryValue('stripNicks'):
         removenicks = '|'.join(item + '\W.*?\s' for item in irc.stats.channels[channel].users)
         text = re.sub(r'' + removenicks + '', '', text)
     # finally, pass to our learn function.
     self._learn(irc, channel, text, probability)
예제 #28
0
파일: plugin.py 프로젝트: venth/Supybot
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     channel = msg.args[0]
     if irc.isChannel(channel):
         if ircmsgs.isAction(msg):
             text = ircmsgs.unAction(msg)
         else:
             text = msg.args[1]
         for url in utils.web.urlRe.findall(text):
             r = self.registryValue('nonSnarfingRegexp', channel)
             if r and r.search(url):
                 self.log.debug('Skipping adding %u to db.', url)
                 continue
             self.log.debug('Adding %u to db.', url)
             self.db.add(channel, url, msg)
예제 #29
0
파일: test.py 프로젝트: cnelsonsic/Limnoria
 def assertActionRegexp(self, query, regexp, flags=re.I, **kwargs):
     m = self._feedMsg(query, **kwargs)
     if m is None:
         raise TimeoutError, query
     self.failUnless(ircmsgs.isAction(m))
     s = ircmsgs.unAction(m)
     self.failUnless(re.search(regexp, s, flags), "%r does not match %r" % (s, regexp))
예제 #30
0
 def tokenize(self, m):
     if ircmsgs.isAction(m):
         return ircmsgs.unAction(m).split()
     elif ircmsgs.isCtcp(m):
         return []
     else:
         return m.args[1].split()
예제 #31
0
 def tokenize(self, m):
     if ircmsgs.isAction(m):
         return ircmsgs.unAction(m).split()
     elif ircmsgs.isCtcp(m):
         return []
     else:
         return m.args[1].split()
예제 #32
0
 def _formatPrivmsg(self, nick, network, msg):
     channel = msg.args[0]
     if self.registryValue('includeNetwork', channel):
         network = '@' + network
     else:
         network = ''
     # colorize nicks
     color = self.registryValue('color', channel) # Also used further down.
     if color:
         nick = ircutils.IrcString(nick)
         newnick = ircutils.mircColor(nick, *ircutils.canonicalColor(nick))
         colors = ircutils.canonicalColor(nick, shift=4)
         nick = newnick
     if ircmsgs.isAction(msg):
         if color:
             t = ircutils.mircColor('*', *colors)
         else:
             t = '*'
         s = format('%s %s%s %s', t, nick, network, ircmsgs.unAction(msg))
     else:
         if color:
             lt = ircutils.mircColor('<', *colors)
             gt = ircutils.mircColor('>', *colors)
         else:
             lt = '<'
             gt = '>'
         s = format('%s%s%s%s %s', lt, nick, network, gt, msg.args[1])
     return s
예제 #33
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     channel = msg.args[0]
     if irc.isChannel(channel):
         if ircmsgs.isAction(msg):
             text = ircmsgs.unAction(msg)
         else:
             text = msg.args[1]
         for url in utils.web.urlRe.findall(text):
             r = self.registryValue('nonSnarfingRegexp', channel)
             if r and r.search(url):
                 self.log.debug('Skipping adding %u to db.', url)
                 continue
             self.log.debug('Adding %u to db.', url)
             self.db.add(channel, url, msg)
예제 #34
0
    def replacer(self, irc, msg, regex):
        if not self.registryValue('enable', msg.args[0]):
            return None
        iterable = reversed(irc.state.history)
        msg.tag('Replacer')
        target = regex.group('nick') or ''

        if target:
            checkNick = target
            prefix = '%s thinks %s' % (msg.nick, target)
        else:
            checkNick = msg.nick
            prefix = msg.nick

        try:
            message = 's' + msg.args[1][len(target):].split('s', 1)[-1]
            (pattern, replacement, count) = self._unpack_sed(message)
        except ValueError as e:
            self.log.warning(_("Replacer error: %s"), e)
            if self.registryValue('displayErrors', msg.args[0]):
                irc.error(_("Replacer error: %s" % e), Raise=True)
            return None

        next(iterable)
        for m in iterable:
            if m.nick == checkNick and \
                    m.args[0] == msg.args[0] and \
                    m.command == 'PRIVMSG':

                if ircmsgs.isAction(m):
                    text = ircmsgs.unAction(m)
                    tmpl = 'do'
                else:
                    text = m.args[1]
                    tmpl = 'say'

                try:
                    if not self._regexsearch(text, pattern):
                        continue
                except TimeoutError as e: # Isn't working for some reason
                    self.log.error('TIMEOUT ERROR CAUGHT!!')
                    break
                except Exception as e:
                    self.log.error('Replacer: %s' % type(e).__name__)
                    break

                if self.registryValue('ignoreRegex', msg.args[0]) and \
                        m.tagged('Replacer'):
                    continue
                irc.reply(_("%s meant to %s “ %s ”") %
                          (prefix, tmpl, pattern.sub(replacement,
                           text, count)), prefixNick=False)
                return None

        self.log.debug(_("""Replacer: Search %r not found in the last %i
                       messages."""), regex, len(irc.state.history))
        if self.registryValue("displayErrors", msg.args[0]):
            irc.error(_("Search not found in the last %i messages.") %
                      len(irc.state.history), Raise=True)
        return None
예제 #35
0
파일: plugin.py 프로젝트: rostob/Limnoria
 def _formatPrivmsg(self, nick, network, msg):
     channel = msg.channel
     # colorize nicks
     color = self.registryValue('color', channel)  # Also used further down.
     if color:
         nick = ircutils.IrcString(nick)
         newnick = ircutils.mircColor(nick, *ircutils.canonicalColor(nick))
         colors = ircutils.canonicalColor(nick, shift=4)
         nick = newnick
     if ircmsgs.isAction(msg):
         if color:
             t = ircutils.mircColor('*', *colors)
         else:
             t = '*'
         displayName = self._formatDisplayName(nick, network, msg.channel)
         s = format('%s %s %s', t, displayName, ircmsgs.unAction(msg))
     else:
         if color:
             lt = ircutils.mircColor('<', *colors)
             gt = ircutils.mircColor('>', *colors)
         else:
             lt = '<'
             gt = '>'
         displayName = self._formatDisplayName(nick, network, msg.channel)
         s = format('%s%s%s %s', lt, displayName, gt, msg.args[1])
     return s
예제 #36
0
파일: plugin.py 프로젝트: mogad0n/Limnoria
    def _replacer_process(self, irc, msg, target, pattern, replacement, count,
                          messages):
        for m in messages:
            if m.command in ('PRIVMSG', 'NOTICE') and \
                    ircutils.strEqual(m.args[0], msg.args[0]) and m.tagged('receivedBy') == irc:
                if target and m.nick != target:
                    continue
                # Don't snarf ignored users' messages unless specifically
                # told to.
                if ircdb.checkIgnored(m.prefix) and not target:
                    continue

                # When running substitutions, ignore the "* nick" part of any actions.
                action = ircmsgs.isAction(m)
                if action:
                    text = ircmsgs.unAction(m)
                else:
                    text = m.args[1]

                # Test messages sent before SedRegex was activated. Mark them all as seen
                # so we only need to do this check once per message.
                if not m.tagged(TAG_SEEN):
                    m.tag(TAG_SEEN)
                    if SED_REGEX.match(m.args[1]):
                        m.tag(TAG_IS_REGEX)
                # Ignore messages containing a regexp if ignoreRegex is on.
                if self.registryValue('ignoreRegex', msg.channel,
                                      irc.network) and m.tagged(TAG_IS_REGEX):
                    self.log.debug(
                        "Skipping message %s because it is tagged as isRegex",
                        m.args[1])
                    continue
                if m.nick == msg.nick:
                    messageprefix = msg.nick
                else:
                    messageprefix = '%s thinks %s' % (msg.nick, m.nick)

                try:
                    replace_result = pattern.search(text)
                    if replace_result:
                        if self.registryValue('boldReplacementText',
                                              msg.channel, irc.network):
                            replacement = ircutils.bold(replacement)
                        subst = pattern.sub(replacement, text, count)
                        if action:  # If the message was an ACTION, prepend the nick back.
                            subst = '* %s %s' % (m.nick, subst)

                        subst = axe_spaces(subst)

                        return _("%s meant to say: %s") % \
                            (messageprefix, subst)
                except Exception as e:
                    self.log.warning(_("SedRegex error: %s"), e, exc_info=True)
                    raise

        self.log.debug(
            _("SedRegex: Search %r not found in the last %i messages of %s."),
            msg.args[1], len(irc.state.history), msg.args[0])
        raise SearchNotFoundError()
예제 #37
0
    def doPrivmsg(self, irc, msg):
        if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
            return
        channel = msg.args[0]

        if irc.isChannel(channel):
            if ircmsgs.isAction(msg):
                text = ircmsgs.unAction(msg)
            else:
                text = msg.args[1]

            movies = set(URL_REGEX.findall(text))

            if movies:
                api = create_api(plugin=self)
                for mid in movies:
                    api.reply(irc, mid)
예제 #38
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     channel = msg.args[0]
     if callbacks.addressed(irc.nick, msg):
         return
     if self.registryValue('titleSnarfer', channel):
         if irc.isChannel(channel):
             if ircmsgs.isAction(msg):
                 text = ircmsgs.unAction(msg)
             else:
                 text = msg.args[1]
             for info in present_links(text, color=True):
                 irc.reply(info,
                           prefixNick=False,
                           private=False,
                           notice=False)
예제 #39
0
파일: plugin.py 프로젝트: ProgVal/Limnoria
 def p(messages):
     for m in messages:
         if ircmsgs.isAction(m):
             s = ircmsgs.unAction(m)
         else:
             s = m.args[1]
         if reobj.search(s):
             q.put(m)
예제 #40
0
 def doPrivmsg(self, irc, msg):
     if not self._autoRollEnabled(irc, msg.args[0]):
         return
     if ircmsgs.isAction(msg):
         text = ircmsgs.unAction(msg)
     else:
         text = msg.args[1]
     self._process(irc, text)
예제 #41
0
 def f(m, arg=arg):
     if ircmsgs.isAction(m):
         m1 = ircmsgs.unAction(m)
     else:
         m1 = m.args[1]
     return regexp_wrapper(m1, reobj=arg, timeout=0.1,
                           plugin_name=self.name(),
                           fcn_name='last')
예제 #42
0
 def assertActionRegexp(self, query, regexp, flags=re.I, **kwargs):
     m = self._feedMsg(query, **kwargs)
     if m is None:
         raise TimeoutError, query
     self.failUnless(ircmsgs.isAction(m))
     s = ircmsgs.unAction(m)
     self.failUnless(re.search(regexp, s, flags),
                     '%r does not match %r' % (s, regexp))
예제 #43
0
파일: plugin.py 프로젝트: sudokode/Limnoria
 def outFilter(self, irc, msg):
     if msg.command == 'PRIVMSG':
         if msg.args[0] in self.outFilters:
             if ircmsgs.isAction(msg):
                 s = ircmsgs.unAction(msg)
             else:
                 s = msg.args[1]
             methods = self.outFilters[msg.args[0]]
             for filtercommand in methods:
                 myIrc = MyFilterProxy()
                 filtercommand(myIrc, msg, [s])
                 s = myIrc.s
             if ircmsgs.isAction(msg):
                 msg = ircmsgs.action(msg.args[0], s, msg=msg)
             else:
                 msg = ircmsgs.IrcMsg(msg=msg, args=(msg.args[0], s))
     return msg
예제 #44
0
 def doPrivmsg(self, irc, msg):
     if not self._autoRollEnabled(irc, msg.args[0]):
         return
     if ircmsgs.isAction(msg):
         text = ircmsgs.unAction(msg)
     else:
         text = msg.args[1]
     self._process(irc, text)
예제 #45
0
    def replacer(self, irc, msg, regex):
        if not self.registryValue('enable', msg.args[0]):
            return
        iterable = reversed(irc.state.history)
        msg.tag('Replacer')

        try:
            (pattern, replacement, count) = self._unpack_sed(msg.args[1])
        except (ValueError, re.error) as e:
            self.log.warning(_("Replacer error: %s"), e)
            if self.registryValue('displayErrors', msg.args[0]):
                irc.error(_("Replacer error: %s" % e), Raise=True)
            return

        next(iterable)
        for m in iterable:
            if m.command in ('PRIVMSG', 'NOTICE') and \
                    m.args[0] == msg.args[0]:
                target = regex.group('nick')
                if not ircutils.isNick(str(target), strictRfc=True):
                    return
                if target and m.nick != target:
                    continue
                # Don't snarf ignored users' messages unless specifically
                # told to.
                if ircdb.checkIgnored(m.prefix) and not target:
                    continue
                # When running substitutions, ignore the "* nick" part of any actions.
                action = ircmsgs.isAction(m)
                if action:
                    text = ircmsgs.unAction(m)
                else:
                    text = m.args[1]

                if self.registryValue('ignoreRegex', msg.args[0]) and \
                        m.tagged('Replacer'):
                    continue
                if m.nick == msg.nick:
                    messageprefix = msg.nick
                else:
                    messageprefix = '%s thinks %s' % (msg.nick, m.nick)
                if regexp_wrapper(text, pattern, timeout=0.05, plugin_name=self.name(),
                                  fcn_name='replacer'):
                    if self.registryValue('boldReplacementText', msg.args[0]):
                        replacement = ircutils.bold(replacement)
                    subst = process(pattern.sub, replacement,
                                text, count, timeout=0.05)
                    if action:  # If the message was an ACTION, prepend the nick back.
                        subst = '* %s %s' % (m.nick, subst)
                    irc.reply(_("%s meant to say: %s") %
                              (messageprefix, subst), prefixNick=False)
                    return

        self.log.debug(_("Replacer: Search %r not found in the last %i messages of %s."),
                         msg.args[1], len(irc.state.history), msg.args[0])
        if self.registryValue("displayErrors", msg.args[0]):
            irc.error(_("Search not found in the last %i messages.") %
                      len(irc.state.history), Raise=True)
예제 #46
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     if msg.args[
             0] == irc.nick and self.running_decision and msg.nick in self.running_decision.dp.participants.keys(
             ):
         log.debug("Message:" + msg.args[1])
         if self.running_decision.add_vote(msg.nick, msg.args[1]):
             self.running_decision = None
예제 #47
0
 def doPrivmsg(self, irc, msg):
     if irc.isChannel(msg.args[0]):
         channel = msg.args[0]
         sender = msg.nick
         if ircmsgs.isAction(msg):
             message = ircmsgs.unAction(msg)
         else:    
             message = msg.args[1]
         self.instances[irc.network].onMessage(channel, sender, message)
예제 #48
0
파일: test.py 프로젝트: cnelsonsic/Limnoria
 def assertAction(self, query, expectedResponse=None, **kwargs):
     m = self._feedMsg(query, **kwargs)
     if m is None:
         raise TimeoutError, query
     self.failUnless(ircmsgs.isAction(m), "%r is not an action." % m)
     if expectedResponse is not None:
         s = ircmsgs.unAction(m)
         self.assertEqual(s, expectedResponse, "%r != %r" % (s, expectedResponse))
     return m
예제 #49
0
    def doPrivmsg(self, irc, msg):
        channel = msg.args[0].lower()

        if irc.isChannel(channel):
            if ircmsgs.isAction(msg):
                text = ircmsgs.unAction(msg)
            else:
                text = msg.args[1]

            self._checkUrl(irc, text, msg.nick, channel)
예제 #50
0
 def assertAction(self, query, expectedResponse=None, **kwargs):
     m = self._feedMsg(query, **kwargs)
     if m is None:
         raise TimeoutError, query
     self.failUnless(ircmsgs.isAction(m), '%r is not an action.' % m)
     if expectedResponse is not None:
         s = ircmsgs.unAction(m)
         self.assertEqual(s, expectedResponse,
                          '%r != %r' % (s, expectedResponse))
     return m
예제 #51
0
    def doPrivmsg(self, irc, msg):
        channel = msg.args[0]  # channel, if any.
        # user = msg.nick  # nick of user.
        # linkdb = LinkDB()   # disable for now.
        # linkdb.add(url, title, channel, user)

        # first, check if we should be 'disabled' in this channel.
        if self.registryValue('disableChannel', channel):
            return
        # don't react to non-ACTION based messages.
        if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
            return
        if irc.isChannel(channel):  # must be in channel.
            if ircmsgs.isAction(msg):  # if in action, remove.
                text = ircmsgs.unAction(msg)
            else:
                text = msg.args[1]
            # find all urls pasted.
            #urlpattern = """(((http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z
            #                0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.
            #                [0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&amp;%_\./-~-]*)?"""
            # extracts links in text and stores in an iterator.
            #matches = re.finditer(urlpattern, text.strip(), re.IGNORECASE + re.VERBOSE)
            for url in utils.web.urlRe.findall(text):
            #for url in matches:
                self.log.info("FOUND URL: {0}".format(url))
                url = url.decode('utf-8')
                url = unicode(url)
                url = self.iri2uri(url)
                self.log.info("after iri to uri: {0}".format(url))
                # url = self._tidyurl(url)  # should we tidy them?
                output = self._titler(url, channel)
                # now, with gd, we must check what output is.
                if output:  # if we did not get None back.
                    if isinstance(output, dict):  # came back a dict.
                        # output.
                        if 'desc' in output and 'title' in output and output['desc'] is not None and output['title'] is not None:
                            irc.sendMsg(ircmsgs.privmsg(channel, "{0}".format(output['title'])))
                            irc.sendMsg(ircmsgs.privmsg(channel, "{0}".format(output['desc'])))
                        elif 'title' in output and output['title'] is not None:
                            irc.sendMsg(ircmsgs.privmsg(channel, "{0}".format(output['title'])))
                    else:  # no desc.
                        irc.sendMsg(ircmsgs.privmsg(channel, "{0}".format(output)))
예제 #52
0
파일: plugin.py 프로젝트: affix/Fedbot
 def doPrivmsg(self, irc, msg):
     (recipients, text) = msg.args
     for channel in recipients.split(','):
         if irc.isChannel(channel):
             nick = msg.nick or irc.nick
             if ircmsgs.isAction(msg):
                 self.doLog(irc, channel,
                            '* %s %s\n' % (nick, ircmsgs.unAction(msg)))
             else:
                 self.doLog(irc, channel, '<%s> %s\n' % (nick, text))
     self._sendReviews(irc, msg)
예제 #53
0
파일: Cobe.py 프로젝트: alyptik/dotfiles
    def doPrivmsg(self, irc, msg):

        (channel, text) = msg.args

        if (callbacks.addressed(irc.nick, msg) or ircmsgs.isCtcp(msg)
                or not irc.isChannel(channel) or not (None == re.match(
                    self.registryValue('ignoreRegex'), text))):
            # Was the message a CTCP command, a command to the bot, is this message supposed to be ignored, or are we not in a channel??

            self.log.debug(
                "The method 'callbacks.addressed(irc.nick, msg)' returns {0}!".
                format(True == callbacks.addressed(irc.nick, msg)))
            self.log.debug(
                "The method 'ircmsgs.isCtcp(msg)' returns {0}!".format(
                    True == ircmsgs.isCtcp(msg)))
            self.log.debug(
                "The method 'irc.isChannel(channel)' returns {0}!".format(
                    False == irc.isChannel(channel)))
            self.log.debug(
                "The method 're.match(self.registryValue('ignoreRegex'), text)' returns {0}!"
                .format(False == (None == re.match(
                    self.registryValue('ignoreRegex'), text))))

            return

        if ircmsgs.isAction(msg):
            # If the message was an action...we'll learn it anyways!

            text = ircmsgs.unAction(msg)

        if self.registryValue('stripUrls'):  # strip URLs
            text = re.sub(r'(http[^\s]*)', '', text)

        # strip ›
        text = re.sub(r'›', '', text)

        if irc.nick.lower() in text.lower():
            # Were we addressed in the channel?

            probability = self.registryValue('probabilityWhenAddressed',
                                             channel)

        else:
            # Okay, we were not addressed, but what's the probability we should reply?

            probability = self.registryValue('probability', channel)

        #if self.registryValue('stripNicks'):
        #    removenicks = '|'.join(item + '\W.*?\s' for item in irc.state.channels[channel].users)
        #    text = re.sub(r'' + removenicks + '', 'MAGIC_NICK', text)

        self._learn(irc, msg, channel, text,
                    probability)  # Now we can pass this to our learn function!
예제 #54
0
 def doPrivmsg(self, irc, msg):
     if msg.tagged("relayedMsg"):
         # That message was sent by myself; don't relay it (or it will echo all
         # messages from the Skype chat back to the Skype chat)
         return
     # msg.nick is None if this is a simulated echo message
     nick = msg.nick or irc.nick
     if ircmsgs.isAction(msg):
         self._sendToSkype(irc, msg.channel,
                           f"* {nick} {ircmsgs.unAction(msg)}")
     else:
         self._sendToSkype(irc, msg.channel, f"<{nick}> {msg.args[1]}")
예제 #55
0
 def testIsAction(self):
     L = [':[email protected] PRIVMSG'
          ' #sourcereview :ACTION does something',
          ':[email protected] PRIVMSG #sourcereview '
          ':ACTION beats angryman senseless with a Unix manual (#2)',
          ':[email protected] PRIVMSG #sourcereview '
          ':ACTION beats ang senseless with a 50lb Unix manual (#2)',
          ':[email protected] PRIVMSG #sourcereview '
          ':ACTION resizes angryman\'s terminal to 40x24 (#16)']
     msgs = list(map(ircmsgs.IrcMsg, L))
     for msg in msgs:
         self.assertTrue(ircmsgs.isAction(msg))