示例#1
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!
示例#2
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)
示例#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):
     assert self is irc.callbacks[0], \
            'Owner isn\'t first callback: %r' % irc.callbacks
     if ircmsgs.isCtcp(msg):
         return
     s = callbacks.addressed(irc.nick, msg)
     if s:
         ignored = ircdb.checkIgnored(msg.prefix)
         if ignored:
             self.log.info('Ignoring command from %s.', msg.prefix)
             return
         maximum = conf.supybot.abuse.flood.command.maximum()
         self.commands.enqueue(msg)
         if conf.supybot.abuse.flood.command() \
            and self.commands.len(msg) > maximum \
            and not ircdb.checkCapability(msg.prefix, 'trusted'):
             punishment = conf.supybot.abuse.flood.command.punishment()
             banmask = ircutils.banmask(msg.prefix)
             self.log.info('Ignoring %s for %s seconds due to an apparent '
                           'command flood.', banmask, punishment)
             ircdb.ignores.add(banmask, time.time() + punishment)
             irc.reply('You\'ve given me %s commands within the last '
                       'minute; I\'m now ignoring you for %s.' %
                       (maximum,
                        utils.timeElapsed(punishment, seconds=False)))
             return
         try:
             tokens = callbacks.tokenize(s, channel=msg.args[0])
             self.Proxy(irc, msg, tokens)
         except SyntaxError, e:
             irc.queueMsg(callbacks.error(msg, str(e)))
示例#5
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()
示例#6
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()
示例#7
0
 def doPrivmsg(self, irc, msg):
     assert self is irc.callbacks[0], \
            'Owner isn\'t first callback: %r' % irc.callbacks
     if ircmsgs.isCtcp(msg):
         return
     s = callbacks.addressed(irc.nick, msg)
     if s:
         ignored = ircdb.checkIgnored(msg.prefix)
         if ignored:
             self.log.info('Ignoring command from %s.', msg.prefix)
             return
         maximum = conf.supybot.abuse.flood.command.maximum()
         self.commands.enqueue(msg)
         if conf.supybot.abuse.flood.command() \
            and self.commands.len(msg) > maximum \
            and not ircdb.checkCapability(msg.prefix, 'trusted'):
             punishment = conf.supybot.abuse.flood.command.punishment()
             banmask = conf.supybot.protocols.irc.banmask \
                     .makeBanmask(msg.prefix)
             self.log.info('Ignoring %s for %s seconds due to an apparent '
                           'command flood.', banmask, punishment)
             ircdb.ignores.add(banmask, time.time() + punishment)
             if conf.supybot.abuse.flood.command.notify():
                 irc.reply('You\'ve given me %s commands within the last '
                           '%i seconds; I\'m now ignoring you for %s.' %
                           (maximum,
                            conf.supybot.abuse.flood.interval(),
                            utils.timeElapsed(punishment, seconds=False)))
             return
         try:
             tokens = callbacks.tokenize(s, channel=msg.args[0])
             self.Proxy(irc, msg, tokens)
         except SyntaxError as e:
             irc.queueMsg(callbacks.error(msg, str(e)))
示例#8
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)
示例#9
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!
示例#10
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()
示例#11
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()
示例#12
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)
示例#13
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
示例#14
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())
示例#15
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
示例#16
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
示例#17
0
 def doNotice(self, irc, msg):
     if ircmsgs.isCtcp(msg):
         try:
             (version, payload) = msg.args[1][1:-1].split(None, 1)
         except ValueError:
             return
         if version == 'VERSION':
             self.versions.setdefault(payload, []).append(msg.nick)
示例#18
0
 def doNotice(self, irc, msg):
     if ircmsgs.isCtcp(msg):
         try:
             (version, payload) = msg.args[1][1:-1].split(None, 1)
         except ValueError:
             return
         if version == 'VERSION':
             self.versions.setdefault(payload, []).append(msg.nick)
示例#19
0
    def doPrivmsg(self, irc, msg):
        """
        Checks each channel message to see if it contains a trigger word
        """
        channel = msg.args[0]
        is_channel = irc.isChannel(channel)
        is_ctcp = ircmsgs.isCtcp(msg)
        message = msg.args[1]

        # Check origin nick to make sure the trigger
        # didn't come from the bot.
        origin_nick = msg.nick

        # Only react to messages/actions in a channel
        if is_channel and not is_ctcp:
            if type(message) is str and len(message):
                fact_chance = int(self.registryValue('factChance'))
                link_chance = int(self.registryValue('linkChance'))
                throttle_seconds = int(self.registryValue('throttleInSeconds'))
                triggered = self.message_contains_trigger_word(message)
                now = datetime.datetime.now()
                seconds = 0

                if self.last_message_timestamp:
                    seconds = (now -
                               self.last_message_timestamp).total_seconds()
                    throttled = seconds < throttle_seconds
                else:
                    throttled = False

                if triggered is not False:
                    self.log.debug(
                        "Cayenne triggered because message contained %s" %
                        (triggered))

                    fact_rand = random.randrange(0, 100) < fact_chance
                    link_rand = random.randrange(0, 100) < link_chance

                    if fact_rand or link_rand:
                        if throttled:
                            self.log.info(
                                "Cayenne throttled. Not meowing: it has been %s seconds"
                                % (seconds))
                        else:
                            self.last_message_timestamp = now

                            if fact_rand:
                                output = self.get_fact()

                            if link_rand:
                                output = self.get_link()

                            if output:
                                irc.sendMsg(ircmsgs.privmsg(channel, output))
                            else:
                                self.log.error(
                                    "Cayenne: error retrieving output")
示例#20
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
示例#21
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     if ircutils.isChannel(msg.args[0]) and self._is_voting_enabled(irc, msg):
         channel = msg.args[0]
         message = ircutils.stripFormatting(msg.args[1])
         match = self.regexp.match(message)
         if match and match.group(1) in irc.state.channels[channel].users:
             self._gegen(irc, msg, match.group(1))
 def doPrivmsg(self, irc, msg):
     """
     Checks each channel message to see if it contains a trigger word
     """
     channel = msg.args[0]
     is_channel = irc.isChannel(channel)
     is_ctcp = ircmsgs.isCtcp(msg)        
     message = msg.args[1]
     bot_nick = irc.nick
     
     # Check origin nick to make sure the trigger
     # didn"t come from the bot.
     origin_nick = msg.nick
     
     is_message_from_self = origin_nick.lower() == bot_nick.lower()
     
     # Only react to messages/actions in a channel and to messages that aren't from
     # the bot itself.
     if is_channel and not is_ctcp and not is_message_from_self:            
         if type(message) is str and len(message):
             fact_chance = int(self.registryValue("factChance"))
             link_chance = int(self.registryValue("linkChance"))            
             throttle_seconds = int(self.registryValue("throttleInSeconds"))
             triggered = self.message_contains_trigger_word(message)
             now = datetime.datetime.now()
             seconds = 0
             
             if self.last_message_timestamp:                
                 seconds = (now - self.last_message_timestamp).total_seconds()
                 throttled = seconds < throttle_seconds
             else:
                 throttled = False
             
             if triggered is not False:
                 self.log.debug("Cayenne triggered because message contained %s" % (triggered))
                 
                 fact_rand = random.randrange(0, 100) <= fact_chance
                 link_rand = random.randrange(0, 100) <= link_chance
                 
                 if fact_rand or link_rand:
                     if throttled:                    
                         self.log.info("Cayenne throttled. Not meowing: it has been %s seconds" % (round(seconds, 1)))
                     else:
                         self.last_message_timestamp = now
                         
                         if fact_rand:
                             output = self.get_fact()
                         
                         if link_rand:
                             output = self.get_link()
                         
                         if output:
                             irc.sendMsg(ircmsgs.privmsg(channel, output))
                         else:
                             self.log.error("Cayenne: error retrieving output")
示例#23
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)
示例#24
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)
示例#25
0
	def shouldLog(self, irc, msg, msgtype):
		if not self.registryValue("enable"):
			return False
		if msgtype == MessageType.privmsg or msgtype == MessageType.notice:
			if not irc.isChannel(msg.args[0]):
				return False
			if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
				return False
		if msgtype == MessageType.mode and msg.args[0] == irc.nick:
			return False
		return True
示例#26
0
 def doPrivmsg(self, irc, msg):
     # We don't handle this if we've been addressed because invalidCommand
     # will handle it for us.  This prevents us from accessing the db twice
     # and therefore crashing.
     if not (msg.addressed or msg.repliedTo):
         channel = msg.args[0]
         if irc.isChannel(channel) and \
            not ircmsgs.isCtcp(msg) and \
            self.registryValue('allowUnaddressedKarma', channel):
             irc = callbacks.SimpleProxy(irc, msg)
             thing = msg.args[1].rstrip()
             self._doKarma(irc, msg, channel, thing)
示例#27
0
    def _doPrivmsgs(self, irc, msg):
        """If the given message is a command, triggers Limnoria's
        command-dispatching for that command.

        Takes the same arguments as ``doPrivmsg`` would, but ``msg`` can
        potentially be an artificial message synthesized in doBatch
        from a multiline batch.

        Usually, a command is a single message, so ``payload=msg.params[0]``
        However, when ``msg`` is part of a multiline message, the payload
        is the concatenation of multiple messages.
        See <https://ircv3.net/specs/extensions/multiline>.
        """
        assert self is irc.callbacks[0], \
               'Owner isn\'t first callback: %r' % irc.callbacks
        if ircmsgs.isCtcp(msg):
            return

        s = callbacks.addressed(irc, msg)
        if s:
            ignored = ircdb.checkIgnored(msg.prefix)
            if ignored:
                self.log.info('Ignoring command from %s.', msg.prefix)
                return
            maximum = conf.supybot.abuse.flood.command.maximum()
            self.commands.enqueue(msg)
            if conf.supybot.abuse.flood.command() \
               and self.commands.len(msg) > maximum \
               and not ircdb.checkCapability(msg.prefix, 'trusted'):
                punishment = conf.supybot.abuse.flood.command.punishment()
                banmask = conf.supybot.protocols.irc.banmask \
                        .makeBanmask(msg.prefix)
                self.log.info(
                    'Ignoring %s for %s seconds due to an apparent '
                    'command flood.', banmask, punishment)
                ircdb.ignores.add(banmask, time.time() + punishment)
                if conf.supybot.abuse.flood.command.notify():
                    irc.reply('You\'ve given me %s commands within the last '
                              '%i seconds; I\'m now ignoring you for %s.' %
                              (maximum, conf.supybot.abuse.flood.interval(),
                               utils.timeElapsed(punishment, seconds=False)))
                return
            try:
                tokens = callbacks.tokenize(s,
                                            channel=msg.channel,
                                            network=irc.network)
                self.Proxy(irc, msg, tokens)
            except SyntaxError as e:
                if conf.supybot.reply.error.detailed():
                    irc.error(str(e))
                else:
                    irc.replyError(msg=msg)
                    self.log.info('Syntax error: %s', e)
示例#28
0
文件: plugin.py 项目: GLolol/Limnoria
 def doPrivmsg(self, irc, msg):
     # We don't handle this if we've been addressed because invalidCommand
     # will handle it for us.  This prevents us from accessing the db twice
     # and therefore crashing.
     if not (msg.addressed or msg.repliedTo):
         channel = msg.args[0]
         if irc.isChannel(channel) and \
            not ircmsgs.isCtcp(msg) and \
            self.registryValue('allowUnaddressedKarma', channel):
             irc = callbacks.SimpleProxy(irc, msg)
             thing = msg.args[1].rstrip()
             self._doKarma(irc, msg, channel, thing)
示例#29
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)
示例#30
0
 def doPrivmsg(self, irc, msg):
     try:
         if ircmsgs.isCtcp(msg):
             self.log.debug('Returning early from doPrivmsg: isCtcp(msg).')
             return
         s = callbacks.addressed(irc.nick, msg)
         payload = self.normalize(s or msg.args[1], irc.nick, msg.nick)
         if s:
             msg.tag('addressed', payload)
         msg = ircmsgs.IrcMsg(args=(msg.args[0], payload), msg=msg)
         self.__parent.doPrivmsg(irc, msg)
     finally:
         self.changed = False
         self.added = False
示例#31
0
 def doPrivmsg(self, irc, msg):
     try:
         if ircmsgs.isCtcp(msg):
             self.log.debug('Returning early from doPrivmsg: isCtcp(msg).')
             return
         s = callbacks.addressed(irc.nick, msg)
         payload = self.normalize(s or msg.args[1], irc.nick, msg.nick)
         if s:
             msg.tag('addressed', payload)
         msg = ircmsgs.IrcMsg(args=(msg.args[0], payload), msg=msg)
         self.__parent.doPrivmsg(irc, msg)
     finally:
         self.changed = False
         self.added = False
示例#32
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     if irc.isChannel(msg.args[0]):
         channel = msg.args[0]
         said = ircmsgs.prettyPrint(msg)
         self.db.update(channel, msg.nick, said)
         self.anydb.update(channel, msg.nick, said)
         try:
             id = ircdb.users.getUserId(msg.prefix)
             self.db.update(channel, id, said)
             self.anydb.update(channel, id, said)
         except KeyError:
             pass # Not in the database.
示例#33
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     if msg.channel:
         channel = msg.channel
         said = ircmsgs.prettyPrint(msg)
         self.db.update(channel, msg.nick, said)
         self.anydb.update(channel, msg.nick, said)
         try:
             id = ircdb.users.getUserId(msg.prefix)
             self.db.update(channel, id, said)
             self.anydb.update(channel, id, said)
         except KeyError:
             pass  # Not in the database.
示例#34
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)
示例#35
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)
示例#36
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)
示例#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 outFilter(self, irc, msg):
        if msg.command == 'PRIVMSG' and not ircmsgs.isCtcp(msg):
            text = msg.args[1]
            strippedText = ircutils.stripFormatting(text)

            def stripStringL(txt):
                return self.registryValue('badPrefix', msg.args[0]).sub('',txt)
            def stripStringR(txt):
                return self.registryValue('badSuffix', msg.args[0]).sub('',txt)
            if stripStringL(strippedText) != strippedText:
                text = ' ' + text
            if stripStringR(strippedText) != strippedText:
                text = text + '.'

            newArgs = list(msg.args)
            newArgs[1] = text
            return ircmsgs.IrcMsg(msg=msg, args=tuple(newArgs))
        return msg
示例#39
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]

            videos = set(m.groupdict()['yid'] for r in URL_REGEXES for m in r.finditer(text))

            if videos:
                api = YouTubeApi()

                for video in videos:
                    api.reply(irc, video)
示例#40
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):
                #http://us.battle.net/d3/en/calculator/monk#WVYjRk!YUa!cZZaYb
                m = re.search("battle.net/d3/en/calculator/([\\w-]+)#([\\w\\.]+)!([\\w\\.]+)!([\\w\\.]+)", url)
                if m:
                    sk = [self.skilldata[m.group(1)]["skills"][f] for f in self._hash_decode(m.group(2))]
                    out = self.classes[m.group(1)] + ": " #classname
                    out += ", ".join(["%s (%s)" % (sk[n]["name"], ("none" if f < 0 else sk[n]["runes"][f]["name"])) for (n, f) in enumerate(self._hash_decode(m.group(4)))]) #skills
                    out += " / "
                    out += ", ".join([self.skilldata[m.group(1)]["traits"][f]["name"] for f in self._hash_decode(m.group(3))]) #traits
                    irc.reply(out, prefixNick=False)
                    return  #no need no check the other url formats.
                #https://twitter.com/#!/Nyzaris/status/179599382814011392
                m = re.search("twitter.com/(?:#!/)?.+/status(?:es)?/(\d+)", url)
                if m:
                    resp, j = self._h.request("http://api.twitter.com/1/statuses/show/%s.json" % m.group(1), "GET")
                    tjson = json.loads(j)
                    irc.reply("%s (%s): %s" % (tjson["user"]["screen_name"], tjson["user"]["name"], tjson["text"]), prefixNick=False)
                    return
                m = re.search("redd.it/(.+)", url)
                if m:
                    url = "http://www.reddit.com/comments/%s/.json" % m.group(1)
                    # don't return because we want to go through the next block
                if url.find("reddit.com/") != -1:
                    resp, j = self._h.request(url + ".json?limit=1", "GET")
                    try:
                        f = json.loads(j)[0]["data"]["children"][0]["data"]
                    except KeyError:
                        return    #it probably was a link to a subreddit or something, so don't sweat it

                    if f["is_self"]:
                        irc.reply("Reddit: (+%d) %s (%s) by %s %s ago. %d comment%s." % (f["score"], f["title"], f["domain"], f["author"], DiabloCommon.timeago(time.time() - f["created_utc"]), f["num_comments"], "s" if f["num_comments"] != 1 else ""), prefixNick=False)
                    else:
                        irc.reply("Reddit: (+%d) %s (%s) by %s %s ago. %d comment%s." % (f["score"], f["title"], f["url"], f["author"], DiabloCommon.timeago(time.time() - f["created_utc"]), f["num_comments"], "s" if f["num_comments"] != 1 else ""), prefixNick=False)
                    return
示例#41
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)))
示例#42
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)))
示例#43
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     notes = self._notes.pop(msg.nick, [])
     # Let's try wildcards.
     removals = []
     for wildcard in self.wildcards:
         if ircutils.hostmaskPatternEqual(wildcard, msg.nick):
             removals.append(wildcard)
             notes.extend(self._notes.pop(wildcard))
         for removal in removals:
             self.wildcards.remove(removal)
     if notes:
         irc = callbacks.SimpleProxy(irc, msg)
         private = self.registryValue('private')
         for (when, whence, note) in notes:
             s = self._formatNote(when, whence, note)
             irc.reply(s, private=private)
         self._flushNotes()
示例#44
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     notes = self._notes.pop(msg.nick, [])
     # Let's try wildcards.
     removals = []
     for wildcard in self.wildcards:
         if ircutils.hostmaskPatternEqual(wildcard, msg.nick):
             removals.append(wildcard)
             notes.extend(self._notes.pop(wildcard))
         for removal in removals:
             self.wildcards.remove(removal)
     if notes:
         irc = callbacks.SimpleProxy(irc, msg)
         private = self.registryValue('private')
         for (when, whence, note) in notes:
             s = self._formatNote(when, whence, note)
             irc.reply(s, private=private, prefixNick=not private)
         self._flushNotes()
示例#45
0
文件: plugin.py 项目: jfoots/ircbot1
    def doPrivmsg(self, irc, msg):
        # We don't handle this if we've been addressed because invalidCommand
        # will handle it for us.  This prevents us from accessing the db twice
        # and therefore crashing.
        if not (msg.addressed or msg.repliedTo):
            channel = msg.args[0]
            if (
                irc.isChannel(channel)
                and not ircmsgs.isCtcp(msg)
                and self.registryValue("allowUnaddressedKarma", channel)
            ):
                irc = callbacks.SimpleProxy(irc, msg)
                thing = msg.args[1].rstrip()
                if "++" in thing or "--" in thing:
                    self._doKarma(irc, channel, thing)
                if "is also known as" in thing:
                    self._doAlias(irc, channel, thing)

                if "is no longer known as" in thing:
                    self._doUnalias(irc, channel, thing)
示例#46
0
文件: plugin.py 项目: Latinx/supybot
    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)
        
        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, channel, text, probability) # Now we can pass this to our learn function!
示例#47
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     if ircutils.isChannel(msg.args[0]) and self.registryValue(
             "resolve", msg.args[0]):
         if msg.args[1].find("twitter") != -1:
             status_id = self._get_status_id(msg.args[1], search=True)
             if status_id:
                 try:
                     api = self._get_twitter_api(msg)
                     tweet = api.get_status(status_id)
                     text = tweet.text.replace("\n", " ")
                     text = html.parser.HTMLParser().unescape(text)
                     message = "Tweet von @{}: {}".format(
                         tweet.user.screen_name, text)
                     message = ircutils.safeArgument(
                         message.encode('utf-8'))
                     irc.queueMsg(ircmsgs.notice(msg.args[0], message))
                 except tweepy.TweepError as e:
                     log.error("Twitter.doPrivmsg: {}".format(repr(e)))
                     return
示例#48
0
 def doNotice(self, irc, msg):
     mynick = irc.nick
     user = msg.nick
     hostname = irc.state.nickToHostmask(user)
     (recipients, text) = msg.args
     if ircmsgs.isCtcp(msg) or ircmsgs.isAction(msg) or irc.isChannel(msg.args[0]):  # ignore obvious non.
         return
     elif text.startswith('!ZNCAO'):  # we only process notices with !ZNCAO.
         textparts = text.split()  # split. should be 3.
         if len(textparts) != 3:  # make sure we have 3 parts to a valid ZNC message.
             self.log.error("ERROR: ZNC notice from {0} is malformed. I got: {1}".format(user, text))
             return
         if textparts[0] == "!ZNCAO" and textparts[1] == "CHALLENGE":  # if user is opped and we are not. we get challenge.
             self.log.info("We got a ZNC challenge from {0}".format(user))
             challenge = textparts[2]
             for (key, value) in self._users.items():  # iterate now through our users for key.
                 hostmask, key, channel = value[0]
                 if ircutils.hostmaskPatternEqual(hostmask, hostname):  # if we have a match.
                     if not irc.state.channels[channel].isOp(mynick) and irc.state.channels[channel].isOp(user):  # and they're opped, we're not.
                         response = "!ZNCAO RESPONSE {0}".format(self._zncresponse(key, challenge))  # this key and the challenge.
                         self.log.info("Sending {0} {1}".format(user, response))
                         irc.queueMsg(ircmsgs.notice(user, response))
         elif textparts[0] == "!ZNCAO" and textparts[1] == "RESPONSE":  # means we sent a challenge. we're opped, user is not.
             self.log.info("We got a ZNC response from {0}".format(user))
             if user in self._challenges:  # user is in challenges because their hostname matched.
                 for chan in self._challenges[user]:
                     if irc.state.channels[chan].isOp(mynick) and not irc.state.channels[chan].isOp(user):  # im op. they're not.
                         (chaltime, challenge, chaluser) = self._challenges[user][chan]
                         if chaltime - time.time() < 60:  # challenge less than 60s ago.
                             hostmask, key, channel = self._users[chaluser][0]  # find the user in the db.
                             mychallenge = self._zncresponse(key, challenge)  # create my own based on challenge/key to auth.
                             if mychallenge == textparts[2]:  # compare my md5 hash and theirs.
                                 self.log.info("Giving ZNC OP to {0} on {1} after valid key matching.".format(user, chan))
                                 irc.queueMsg(ircmsgs.op(chan, user))  # op if they're valid.
                             else:  # invalid key.
                                 self.log.info("ERROR: Invalid key from: {0} on {1}".format(user, chan))
                         else:  # key is too old.
                             self.log.info("ERROR: {0} in {1} challenge was more than 60s ago.".format(user, chan))
             else:
                 self.log.info("ERROR: {0} not found in ZNC challenges.".format(user))
示例#49
0
文件: plugin.py 项目: ki113d/Limnoria
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     irc = callbacks.SimpleProxy(irc, msg)
     if irc.isChannel(msg.args[0]):
         (chan, payload) = msg.args
         words = self.registryValue("randomGrabber.minimumWords", chan)
         length = self.registryValue("randomGrabber.minimumCharacters", chan)
         grabTime = self.registryValue("randomGrabber.averageTimeBetweenGrabs", chan)
         channel = plugins.getChannel(chan)
         if self.registryValue("randomGrabber", chan):
             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)
示例#50
0
 def testIsCtcp(self):
     self.failUnless(
         ircmsgs.isCtcp(ircmsgs.privmsg('foo', '\x01VERSION\x01')))
     self.failIf(ircmsgs.isCtcp(ircmsgs.privmsg('foo', '\x01')))
示例#51
0
    def doPrivmsg(self, irc, msg):
        """
        Observe each channel message and look for links
        """
        channel = msg.args[0].lower()
        is_channel = irc.isChannel(channel)
        is_ctcp = ircmsgs.isCtcp(msg)
        message = msg.args[1]
        now = datetime.datetime.now()

        if is_channel and not is_ctcp:
            channel_is_allowed = self.is_channel_allowed(channel)
            url = self.get_url_from_message(message)

            if url:
                # Check if channel is allowed based on white/black list restrictions
                if not channel_is_allowed:
                    self.log.info(
                        "SpiffyTitles: not responding to link in %s due to black/white list restrictions"
                        % (channel))
                    return

                info = urlparse(url)
                domain = info.netloc
                is_ignored = self.is_ignored_domain(domain)

                if is_ignored:
                    self.log.info(
                        "SpiffyTitles: ignoring url due to pattern match: %s" %
                        (url))
                    return
                """
                Check if we have this link cached according to the cache lifetime. If so, serve
                link from the cache instead of calling handlers.
                """
                cached_link = self.get_link_from_cache(url)

                if cached_link is not None:
                    title = cached_link["title"]
                else:
                    if domain in self.handlers:
                        handler = self.handlers[domain]
                        title = handler(url, info)
                    else:
                        title = self.handler_default(url)

                if title is not None and title:
                    self.log.info("SpiffyTitles: title found: %s" % (title))

                    formatted_title = self.get_formatted_title(title)

                    # Update link cache
                    if cached_link is None:
                        self.log.info("SpiffyTitles: caching %s" % (url))

                        self.link_cache.append({
                            "url": url,
                            "timestamp": now,
                            "title": title
                        })

                    irc.reply(formatted_title)
                else:
                    self.log.error(
                        "SpiffyTitles: could not get a title for %s" % (url))
示例#52
0
 def testIsCtcp(self):
     self.assertTrue(ircmsgs.isCtcp(ircmsgs.privmsg('foo',
                                                    '\x01VERSION\x01')))
     self.assertFalse(ircmsgs.isCtcp(ircmsgs.privmsg('foo', '\x01')))
示例#53
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     self._notify(irc, msg)
示例#54
0
 def doPrivmsg(self, irc, msg):
     if ircmsgs.isCtcp(msg) and not ircmsgs.isAction(msg):
         return
     self._notify(irc, msg)