예제 #1
0
    def do_command(self, c, e):
        message = e.arguments()[0].strip()

        if message:

            cmd = message.strip().split()[0]
            nick = nm_to_n(e.source())

            if cmd.startswith('!'):
                if self.anti_flood(nick, cmd) >= 11:
                    pass
                else:
                    command = Commands(self, cmd, e)
                    command.run()
            else:
                if cmd.strip(':') == self.nickname:
                    edbot = Edbot()
                    result = edbot.answer(message)
                    if result:
                        self.conn.privmsg(e.target(), '%s %s' % (nick, result))

            if is_channel(e.target()):
                self.log('%s: %s - %s' % (self.channel, nick, message))
            else:
                self.log('pvt: %s - %s' % (nick, message))
예제 #2
0
파일: bot.py 프로젝트: LuizOz/botcha
    def do_command(self, c, e):
        message = e.arguments()[0].strip()
        
        if message:

            cmd = message.strip().split()[0]
            nick = nm_to_n(e.source())

            if cmd.startswith('!'):
                if self.anti_flood(nick, cmd) >= 4:
                    pass
                else:
                    command = Commands(self, cmd, e)
                    command.run()
            else:
                if cmd.strip(':') == self.nickname:
                    edbot = Edbot()
                    result = edbot.answer(message)
                    if result:
                        self.conn.privmsg(e.target(), '%s %s' % (nick, result))

            if is_channel(e.target()):
                self.log('%s: %s - %s' % (self.channel, nick, message))
            else:
                self.log('pvt: %s - %s' % (nick, message))
예제 #3
0
파일: bot.py 프로젝트: Algy/sirc
	def on_mode(self, c, e):
		nick = irclib.nm_to_n(e.source())
		target = e.target()
		if irclib.is_channel(target):
			self._log(target, config.NOTIFY_NAME, '[%s] by <%s>.' % (' '.join(e.arguments()), nick))
		else:
			pass
예제 #4
0
파일: marjubot.py 프로젝트: kaarelj/marju2
    def ai(self, c, e):
        channel = e.target()
        if (not is_channel(channel) or is_channel(channel) and not self.channels[channel].ai):
            return

        #save random message to AI vocabulary
        msg = e.arguments()[0].strip()
        if (random.random() < 0.1):
           self.saveVoc(msg, channel)

        #answer if bot's nick is mentioned
        if (c.get_nickname().lower() in msg.lower()):
            if (random.random() < 0.6):
                out = self.getVoc(channel)
                c.privmsg(channel, out)
                msg = "<" + c.get_nickname() + "> " + msg
예제 #5
0
파일: mcxPyBot.py 프로젝트: havvg/mcxPyBot
    def __resolveCommandType(self, command, e):
        """
            resolves the command type by an event and a command

            @type command: string
            @param command: name of the command to execute

            @type e: Event
            @param e: event object that was fired

            @rtype: string
            @return: actual name of the command type
        """
        # check for existing DCC Connection
        try:
            if self.__IpToUser[e.source()]['auth'] == NOT_AUTHED:
                return 'not_authed_dcc'
            else:
                return 'authed_dcc'
        # DCC Connection does not exist
        except KeyError:

            if not is_channel(e.target()):
                return 'query'
            else:
                # defaults to channel
                return 'channel'
예제 #6
0
 def on_welcome(self, con, evt):
     """ Used for joining, can't be simplified or talk function will break. """
     if irclib.is_channel("#" + self.tag):
         con.join("#" + self.tag)
         self.tag = "#" + self.tag
     else:
         self.send_it()
예제 #7
0
 def on_welcome(self, connection, event):
     if irclib.is_channel(self.channel):
         connection.join(self.channel)
     else:
         print >> sys.stderr, '"%s" is not a valid IRC channel' %\
               self.channel
         sys.exit(1)
예제 #8
0
 def on_welcome(self, connection, event):
     if irclib.is_channel(self.target):
         print "*** Joining channel %s" %self.target
         connection.join(self.target, self.targetpass)
         self.connection.privmsg(self.target, "[%s] v%s" % (self.cfg.ircNick, VERSION)) 
         for server in self.rcon:
             server.send("say \"[%s] v%s\"" % (self.cfg.ircNick, VERSION))
예제 #9
0
파일: irc.py 프로젝트: anotherjesse/intern
    def reply(self, msg):
        """Send a privmsg"""
        if not hasattr(msg, "encode"):
            try:
                msg = str(msg)
            except Exception:
                self.log.error("msg cannot be converted to string")
                return

        msg = msg.encode("utf-8").split("\n")
        # 10 is completely arbitrary for now
        if len(msg) > 10:
            msg = msg[0:8]
            msg.append("...")

        for line in msg:
            if self.addressed:
                source = self.source.split("!")[0]
                self.connection.privmsg(self.target, "%s: %s" % (source, line))
                self.log.info("-%s- <%s> %s: %s" % (self.target, self.nick,
                        source, line))
            else:
                self.connection.privmsg(self.target, line)
                if irclib.is_channel(self.target):
                    self.log.info("-%s- <%s> %s" % (self.target, self.nick,
                            line))
                else:
                    self.log.info("<%s> %s" % (self.nick, line))
예제 #10
0
파일: mcxPyBot.py 프로젝트: havvg/mcxPyBot
    def __privMsg(self, c, e, message):
        """
            privmsg message on connection c

            @type c: Connection
            @param c: either DCCConnection or ServerConnection

            @type e: Event
            @param e: event object that was fired

            @type message: string
            @param e: message that will be sent on the connection

            @raise InvalidArgumentException: If the given object (c) is neither an instance of DCCConnection nor ServerConnection class (INVALID_CONNECTION).
        """
        if isinstance(c, DCCConnection):
            c.privmsg(message)

        if isinstance(c, ServerConnection):
            # if message was sent to a channel, answer in channel
            if is_channel(e.target()):
                c.privmsg(e.target(), message)
            # otherwise it was sent via privmsg to nick (bot)
            else:
                c.privmsg(nm_to_n(e.source()), message)

        if not isinstance(c, DCCConnection) and not isinstance(c, ServerConnection):
            raise InvalidArgumentException(INVALID_CONNECTION)
예제 #11
0
	def addUrl(self, url, hash, source, target, str):
		id, title = self.getUrl(url, hash)
		if id:
			if not title:
				title = self.fetchTitle(url)
				if title:
					database.doSQL("UPDATE url SET title='%s' WHERE url='%s' AND hash='%s'" % (self.sqlEscape(title), self.sqlEscape(url), self.sqlEscape(hash)))

			return title

		urlInfo = urlparse.urlparse(url)
		scheme = urlInfo.scheme
		port = urlInfo.port
		if not port:
			if scheme == 'http':
				port = 80
			elif scheme == 'https':
				port = 443

		host = urlInfo.hostname
		if not host:
			return

		hostId = self.addHost(scheme, host, port)
		chanId = 0
		if is_channel(target):
			chanId = self.addChan(target[1:])

		# Strip mIRC color codes
		str = re.sub('\003\d{1,2},\d{1,2}', '', str)
		str = re.sub('\003\d{0,2}', '', str)
		# Strip mIRC bold, plain, reverse and underline codes
		str = re.sub('[\002\017\026\037]', '', str)

		values = {}

		values["nickid"]   = "%d"   % int(self.addNick(nm_to_n(source)))
		values["string"]   = "'%s'" % self.sqlEscape(str)
		values["url"]      = "'%s'" % self.sqlEscape(url)
		values["hash"]     = "'%s'" % self.sqlEscape(hash)
		values["hostid"]   = "%d"   % int(hostId)
		values["chanid"]   = "%d"   % int(chanId)
		values["time"]     = "CURRENT_TIMESTAMP()"
		values["type"]     = "'%s'" % self.sqlEscape(self.rImageUrl.search(url) and "image" or "html")

		if database.type == "mysql":
			pass
		elif database.type == "pgsql":
			values['time'] = 'CURRENT_TIMESTAMP'
		elif database.type == "sqlite3":
			values['time'] = 'time()'

		title = self.fetchTitle(url) or ""

		values['title'] = "'%s'" % self.sqlEscape(title)

		sql = "insert into url(%s) values(%s)" % (','.join(values.keys()), ','.join(values.values()))
		database.doSQL(sql)
		return title
예제 #12
0
파일: irc.py 프로젝트: DonAtPoundCS/pyhole
 def notice(self, msg):
     """Send a notice."""
     msg = self._mangle_msg(msg)
     for line in msg:
         self.connection.notice(self.target, line)
         if irclib.is_channel(self.target):
             self.log.info("-%s- <%s> %s" % (self.target, self.nick, line))
         else:
             self.log.info("<%s> %s" % (self.nick, line))
예제 #13
0
파일: marjubot.py 프로젝트: kaarelj/marju2
 def do_youtube(self, c, e):
     channel = e.target()
     if (not is_channel(channel) or is_channel(channel) and not self.channels[channel].ai):
         return
     msg = e.arguments()[0].strip()
     matches = re.findall(youtubeUrlRe, msg)
     if (not matches):
         return
     for match in matches:
         id = match[1]
         url = 'http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=jsonc'
         result = urlopen(url).read()
         response = json.loads(result)
         if ('error' in response):
             continue
         title = response['data']['title'].encode("utf-8")
         c.privmsg(channel, title)
         self.log(channel, "<" + c.get_nickname() + "> " + title)
예제 #14
0
파일: ui.py 프로젝트: hunner/irc-256
  def on_connect(self, connection, event):
    if irclib.is_channel(self.room):
      connection.join(self.room)
      who = event.source()[0:event.source().find("!")]
      self.status = Line('status', "[%s] [%s]" % (who, self.room))
      self._draw_status()
      self._goto_input()

    self.add_line(Line('chat', "Connected", timestamp=True))
예제 #15
0
파일: marjubot.py 프로젝트: joosep/marju2
 def doInterceptors(self, e):
     channel = e.target()
     if (not is_channel(channel)):
         return
     msg = e.arguments()[0].strip()
     author = nm_to_n(e.source())
     for interceptor in INTERCEPTOR_PLUGINS:
         if (self.isInterceptorAllowedForChannel(interceptor, channel)):
             threading.Thread(target=self.interceptorWorker, args=(interceptor, msg, channel, author)).start()
예제 #16
0
파일: irc.py 프로젝트: rainya/pyhole
 def notice(self, msg):
     """Send a notice."""
     msg = self._mangle_msg(msg)
     for line in msg:
         self.connection.notice(self.target, line)
         if irclib.is_channel(self.target):
             self.log.info("-%s- <%s> %s" % (self.target, self.nick, line))
         else:
             self.log.info("<%s> %s" % (self.nick, line))
예제 #17
0
파일: irc.py 프로젝트: rainya/pyhole
 def join_channel(self, params):
     """Join a channel."""
     channel = params.split(" ", 1)
     self.reply("Joining %s" % channel[0])
     if irclib.is_channel(channel[0]):
         self.channels.append(channel[0])
         if len(channel) > 1:
             self.connection.join(channel[0], channel[1])
         else:
             self.connection.join(channel[0])
예제 #18
0
파일: irc.py 프로젝트: DonAtPoundCS/pyhole
 def join_channel(self, params):
     """Join a channel."""
     channel = params.split(" ", 1)
     self.reply("Joining %s" % channel[0])
     if irclib.is_channel(channel[0]):
         self.channels.append(channel[0])
         if len(channel) > 1:
             self.connection.join(channel[0], channel[1])
         else:
             self.connection.join(channel[0])
예제 #19
0
파일: pythonbot.py 프로젝트: CyBaH/scripts
    def on_welcome(self, connection, event):
        if irclib.is_channel(self.target):
            connection.join(self.target)
            self.channel = '#tempestuoso'
            connection.join(self.channel)
            self.channel = '#temptalks'
            connection.join(self.channel)

        else:
            self.send_it()
예제 #20
0
파일: pierc.py 프로젝트: dlech/pierc
 def on_join(self, connection, event):
     # only change topic if it is the bot joining
     try:
         source = event.source().split("!")[0]
         if source != self.nick:
             return
     except IndexError:
         return
     if self.topic and irclib.is_channel(self.target):
         connection.topic(self.target, self.topic)
예제 #21
0
 def doInterceptors(self, e):
     channel = e.target()
     if (not is_channel(channel)):
         return
     msg = e.arguments()[0].strip()
     author = nm_to_n(e.source())
     for interceptor in INTERCEPTOR_PLUGINS:
         if (self.isInterceptorAllowedForChannel(interceptor, channel)):
             threading.Thread(target=self.interceptorWorker,
                              args=(interceptor, msg, channel,
                                    author)).start()
예제 #22
0
파일: inkblot.py 프로젝트: puzzlet/inkblot
 def reply(self, event, message):
     eventtype = event.eventtype().lower()
     target = event.target()
     source = event.source()
     if source:
         source = irclib.nm_to_n(source)
     if eventtype in ('privmsg', 'pubmsg'):
         reply_to = target if irclib.is_channel(target) else source
         reply_to, _ = self.codec.decode(reply_to)
         assert isinstance(reply_to, str)
         assert isinstance(message, str)
         self.push_message(Message('privmsg', (reply_to, message)))
예제 #23
0
파일: uniko.py 프로젝트: puzzlet/uniko
 def is_listening_bot(self, bot, channel):
     """Tell whether the bot is on of the "listening bots" for the channel.
     """
     if not irclib.is_channel(channel):
         return False # not even a channel
     if bot not in self.bots:
         return False
     bots = self.get_bots_by_channel(channel)
     if bot not in bots:
         return False
     bots.sort()
     return bots[0] == bot
예제 #24
0
    def parse_event(self, e):
        """ Get the username and channel from an irclib event. """

        # Extract the username from the IRC sender string
        username = irclib.nm_to_n(e.source())
        # See if this is a channel or private message
        if irclib.is_channel(e.target()):
            channel = e.target()
        else:
            channel = None

        return username, channel
예제 #25
0
파일: irc.py 프로젝트: DonAtPoundCS/pyhole
    def on_welcome(self, connection, _event):
        """Join channels upon successful connection."""
        if self.identify_password:
            self.privmsg("NickServ", "IDENTIFY %s" % self.identify_password)

        for channel in self.channels:
            channel = channel.split(" ", 1)
            if irclib.is_channel(channel[0]):
                if len(channel) > 1:
                    connection.join(channel[0], channel[1])
                else:
                    connection.join(channel[0])
예제 #26
0
파일: irc.py 프로젝트: rainya/pyhole
    def on_welcome(self, connection, _event):
        """Join channels upon successful connection."""
        if self.identify_password:
            self.privmsg("NickServ", "IDENTIFY %s" % self.identify_password)

        for channel in self.channels:
            channel = channel.split(" ", 1)
            if irclib.is_channel(channel[0]):
                if len(channel) > 1:
                    connection.join(channel[0], channel[1])
                else:
                    connection.join(channel[0])
예제 #27
0
파일: main.py 프로젝트: zhangsen/ircbot
def msg_handler(connection, event):
    dest = decide_reply_dest(event)
    if not dest:
        return

    input_msg = strip_nickname_from_msg(event.arguments()[0])

    try:
        if input_msg.startswith("join"):
            chann = input_msg[4:].strip()
            if not irclib.is_channel(chann):
                msg = "%s is not a channel name." % chann
                connection.privmsg(dest, msg)
            else:
                connection.join(chann)
            return
        elif input_msg.startswith("part"):
            chann = input_msg[4:].strip()
            if not irclib.is_channel(chann):
                msg = "%s is not a channel name." % chann
                connection.privmsg(dest, msg)
            else:
                connection.part(chann)
            return
    except:
        pass

    issue_numbers = parse_issue_numbers(input_msg)
    for num in issue_numbers:
        try:
            msg = jira.query_issue(num)
        except suds.WebFault as excp:
            if excp.args[0] == ("Server raised fault: "
                    "'com.atlassian.jira.rpc.exception.RemotePermissionException: "
                    "This issue does not exist or you don't have permission to "
                    "view it.'"):
                msg = "%s: No such record?" % num
            else:
                raise
        connection.privmsg(dest, msg)
예제 #28
0
 def _on_mode(self, c, e):
     """[Internal]"""
     modes = parse_channel_modes(" ".join(e.arguments()))
     t = e.target()
     if is_channel(t):
         ch = self.channels[t]
         for mode in modes:
             if mode[0] == "+":
                 f = ch.set_mode
             else:
                 f = ch.clear_mode
             f(mode[1], mode[2])
     else:
         # Mode on self... XXX
         pass
예제 #29
0
파일: ircbot.py 프로젝트: aisquad/nemesian
 def _on_mode(self, conn, evt):
     """[Internal]"""
     modes = parse_channel_modes(" ".join(evt._params[1:]))
     t = evt._params[0]
     if is_channel(t):
         ch = self.channels[t]
         for mode in modes:
             if mode[0] == "+":
                 f = ch.set_mode
             else:
                 f = ch.clear_mode
             f(mode[1], mode[2])
     else:
         # Mode on self... XXX
         pass
예제 #30
0
 def _on_mode(self, c, e):
     """[Internal]"""
     modes = parse_channel_modes(" ".join(e.arguments()))
     t = e.target()
     if is_channel(t):
         ch = self.channels[t]
         for mode in modes:
             if mode[0] == "+":
                 f = ch.set_mode
             else:
                 f = ch.clear_mode
             f(mode[1], mode[2])
     else:
         # Mode on self... XXX
         pass
예제 #31
0
파일: feed.py 프로젝트: quadr/feedex
 def pop_buffer(self, message_buffer):
     message = message_buffer.peek()
     if message.timestamp > time.time():
         # 미래에 보여줄 것은 미래까지 기다림
         # TODO: ignore_time이면 이 조건 무시
         return False
     if self.silent:
         return self.process_message(message_buffer.pop())
     if message.command in ['privmsg']:
         target = message.arguments[0]
         chan = irclib.irc_lower(self.codec.encode(target)[0])
         if irclib.is_channel(chan):
             if chan not in [irclib.irc_lower(_) for _ in self.channels]:
                 self.connection.join(chan)
     return BufferingBot.pop_buffer(self, message_buffer)
예제 #32
0
def _handle_command(bot, e, cmd, args):

    c = bot.connection
    nick = nm_to_n(e.source())
    if is_channel(e.target()):
        target = e.target()
    else:
        target = nick

    if cmd in ['die', 'quit', 'foad']:
        bot.die(msg='Quit requested by %s' % nick)

    elif cmd == 'ping':
        c.privmsg(target, 'Pong!')

    elif cmd == 'sched':
        for t, f, a in c.irclibobj.delayed_commands:
            def argstr(a):
                if repr(a) == repr(bot):
                    return 'bot'
                return repr(a)

            c.privmsg(target, '%s %s(%s)' % (
                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(t)),
                f.__name__,
                ', '.join(map(argstr, a))
            ))

    elif cmd == 'clearsched' and nick == TRUSTED_NICK:
        c.irclibobj.delayed_commands = []
        c.privmsg(target, 'Schedule cleared')

    elif cmd == 'subs' and nick == TRUSTED_NICK:
        at = time.strptime(args, '%H:%M')
        _schedule_update_subs(bot, at.tm_hour, at.tm_min)

    elif cmd == 'op' and nick == TRUSTED_NICK:
        for i in args.split(' '):
            c.privmsg(CHANSERV, 'access %s add %s member' % (OPS_CHAN, args))
            c.privmsg(CHANSERV, 'op %s %s' % (OPS_CHAN, args))

    elif cmd == 'deop' and nick == TRUSTED_NICK:
        for i in args.split(' '):
            c.privmsg(CHANSERV, 'access %s del %s' % (OPS_CHAN, args))
            c.privmsg(CHANSERV, 'deop %s %s' % (OPS_CHAN, args))

    else:
        c.notice(target, "I didn't understand \"%s\"" % cmd)
예제 #33
0
파일: irc.py 프로젝트: rainya/pyhole
 def reply(self, msg):
     """Send a privmsg."""
     msg = self._mangle_msg(msg)
     for line in msg:
         if self.addressed:
             source = self.source.split("!")[0]
             self.connection.privmsg(self.target, "%s: %s" % (source, line))
             self.log.info("-%s- <%s> %s: %s" % (self.target, self.nick,
                     source, line))
         else:
             self.connection.privmsg(self.target, line)
             if irclib.is_channel(self.target):
                 self.log.info("-%s- <%s> %s" % (self.target, self.nick,
                         line))
             else:
                 self.log.info("<%s> %s" % (self.nick, line))
예제 #34
0
파일: irc.py 프로젝트: DonAtPoundCS/pyhole
 def reply(self, msg):
     """Send a privmsg."""
     msg = self._mangle_msg(msg)
     for line in msg:
         if self.addressed:
             source = self.source.split("!")[0]
             self.connection.privmsg(self.target, "%s: %s" % (source, line))
             self.log.info("-%s- <%s> %s: %s" %
                           (self.target, self.nick, source, line))
         else:
             self.connection.privmsg(self.target, line)
             if irclib.is_channel(self.target):
                 self.log.info("-%s- <%s> %s" %
                               (self.target, self.nick, line))
             else:
                 self.log.info("<%s> %s" % (self.nick, line))
예제 #35
0
    def cmd_tell(self, c, msg, target, source):
        """ !tell <recipient> <message>

            The bot will save the given message for the given recipient
        """
        reply = self.create_reply(c, target, source)

        msgparts = msg.split(" ")
        if len(msgparts) < 2:
            reply("Usage: !tell <recipient> <message>")
        else:
            recipient = msgparts[0]
            message = " ".join(msgparts[1:])
            location = target if is_channel(target) else "private"

            add_tell_message(source, location, recipient, message)
            reply("I'll save that message for %s" % recipient)
예제 #36
0
파일: uniko.py 프로젝트: puzzlet/uniko
 def handle(self, bot, event):
     network = bot.network
     if network not in self.networks:
         return
     target = event.target()
     handled = False
     try:
         if irclib.is_channel(target):
             handled = self.handle_channel_event(bot, event)
         else:
             handled = self.handle_private_event(bot, event)
     except Exception:
         logging.exception('')
     return handled
     if not handled and self.debug:
         print('Unhandled message:', event.source(), event.target(),
             event.eventtype(), event.arguments())
예제 #37
0
파일: BBBot.py 프로젝트: Nikola-K/BBBot
 def on_pubmsg(self, c, e):
     nick = nm_to_n(e.source())
     t = e.target()
     command = e.arguments()[0]
     if command == '!streams':
         command = '!stream'
     try:
         if (command.split()[0] in self.disabledcmds) or\
            (('bot' in self.disabledcmds) and not\
            command.startswith('.turn')):
             return
     except:
         return
     if not is_channel(t):
         t = nick
     if (nick.lower() in self.authorized) and\
        (command.split()[0].strip() in self.restrictedcmds) and\
        (nick.lower() not in self.loggedinusers):
         c.whois(nick)
         self.cmdqueue.append(nm_to_n(e.source()))
         #chan/nick
         self.cmdqueue.append(e.target())
         #destination
         self.cmdqueue.append(e.arguments()[0])
         #command
         return
     if not nick.lower() in self.authorized:
         if command in ['!stream', '!i', '!download']:
             if time() - self.cmdlimits[command] < self.cmdlimits['timelimit']:
                 if time() - self.cmdlimits['notify'] > self.cmdlimits['notifytime']:
                     try:
                     #info and notification split to 2 lines to make it easier to read
                         info = str(self.cmdlimits['timelimit']),
                         str(self.cmdlimits['timelimit'] - 
                         (time() - self.cmdlimits[command])).split('.')[0]
                         notification = ': Only one command of that kind is'\
                         'alllowed every %s seconds, try again in %s seconds' % info
                     except:
                         notification = 'Error:'
                     c.privmsg(t, nick + notification)
                     self.cmdlimits['notify'] = time()
                 return
             self.cmdlimits[command] = time()
     self.do_command(nm_to_n(e.source()), e.target(), e.arguments()[0])
     return
예제 #38
0
파일: Bot.py 프로젝트: JoeyJo0/williewortel
    def on_privmsg( self, c, e ):
        logging.debug( "on_privmsg" )

        source = nm_to_n( e.source() )
        target = e.target() if is_channel( e.target() ) else source
        message = e.arguments()[0]

        self.__module_handle( 'privmsg', source, target, message )
        try:
            self.__process_command( c, e )
        except BotExitException as e:
            raise e
        except BotReloadException as e:
            self.connection.disconnect( "Reloading bot..." )
            self.modules.unload()
            raise e
        except Exception as e:
            logging.exception( 'Error in __process_command: %s', e )
예제 #39
0
파일: irc.py 프로젝트: ker2x/cobe
    def on_pubmsg(self, conn, event):
        user = irclib.nm_to_n(event.source())

        if event.target() == self.log_channel:
            # ignore input in the log channel
            return

        # ignore specified nicks
        if self.ignored_nicks and user in self.ignored_nicks:
            return

        # only respond on channels
        if not irclib.is_channel(event.target()):
            return

        msg = event.arguments()[0]

        # strip pasted nicks from messages
        msg = re.sub("<\S+>\s+", "", msg)

        # strip kibot style quotes from messages
        match = re.match('"(.*)" --\S+, \d+-\S+\d+.', msg)
        if match:
            msg = match.group(1)

        # look for messages directed to a user
        match = re.match("\s*(\S+)[,:]\s+(.*?)\s*$", msg)

        if match:
            to = match.group(1)
            text = match.group(2)
        else:
            to = None
            text = msg

        # convert message to unicode
        text = text.decode("utf-8").strip()

        if not self.only_nicks or user in self.only_nicks:
            self.brain.learn(text)

        if to == self.nick:
            reply = self.brain.reply(text).encode("utf-8")
            conn.privmsg(event.target(), "%s: %s" % (user, reply))
예제 #40
0
파일: testbot.py 프로젝트: moschlar/ircbot
 def say_by_proxy(self,c,e,msg):
     """
     Makes the bot say something as it were his own words
     
     Keeps max_ghosts entries as history of ghostwriters.
     """
     if len(self.ghostwriters) >= self.max_ghosts:
         self.ghostwriters = self.ghostwriters[1:]
     self.ghostwriters.append((nm_to_n(e.source()),msg))
     
     msgsplit = msg.split(None,1)
     if is_channel(msgsplit[0]) and len(msgsplit) > 1:
         chan = msgsplit[0]
         msg = msgsplit[1]
     else:
         chan = self.main_channel
     
     c.privmsg(chan,msg)
     return
예제 #41
0
def kysysana(self, e, c):
    """command !sana handler"""
    nick = nm_to_n(e.source())

    line = e.arguments()[0]
    new_word = string.join(line.split()[1:], " ")

    if (not is_channel(e.target()) and self.is_admin(e.source())):
        # for admins in /query
        if (len(new_word) > 0):
            sana.current_word = unicode(new_word, 'utf-8')
        else:
            sana.current_word = random.choice(wordgame_wordlist)
        sana.just_asked = False

    if (len(sana.current_word) > 0):
        self.cron.delete_event(sana.cron_id)
        sana(self)
    else:
        c.privmsg(e.target(), "%s: Sanapeli ei ole nyt käynnissä. Malta hetki."%(nick))
예제 #42
0
 def reply(self, msg):
     """Send a privmsg. If the generating event was in channel #test, respond
     in ##test."""
     # Todo: We need a better way to generate a hash
     # if hash == None:
     # hash = self.generate_hash(self.source, self.source)
     hash = self.hash
     if len(hash) > 0:
         hash = hash + ";"
     msg = self._mangle_msg(msg)
     for line in msg:
         if self.addressed:
             source = self.source.split("!")[0]
             self.connection.privmsg(self.target, "%s: %s" % (source, line))
             self.log.info("-%s- <%s> %s: %s" %
                           (self.target, self.nick, source, line))
         else:
             self.connection.privmsg('#' + self.target, hash + line)
             if irclib.is_channel(self.target):
                 self.log.info("-%s- <%s> %s" %
                               (self.target, self.nick, line))
             else:
                 self.log.info("<%s> %s" % (self.nick, line))
예제 #43
0
 def on_welcome(self, connection, event):
     if irclib.is_channel(self.target):
         connection.join(self.target)
예제 #44
0
 def on_kick(self, connection, event):
     if event.arguments()[0] == self.cfg.ircNick and irclib.is_channel(self.target):
         print "*** Got kicked, re-joining channel %s" %self.target
         self.connection.join(self.target, self.targetpass)
예제 #45
0
 def create_reply(self, c, target, source):
     reply_target = target if is_channel(target) else source
     reply = lambda msg: chat_and_log(c, reply_target, msg)
     return reply
예제 #46
0
 def on_welcome(self, connection, event):
     '''Evenement: On vient de se connecter'''
     # On parcours la liste des canaux pour les rejoindre.
     for i in range(len(self.canaux)):
         if irclib.is_channel(self.canaux[i]):
             connection.join(self.canaux[i])
예제 #47
0
    def handler(self, **args):
        from irclib import Event
        import priv

        argv = self.spaces.split((args["text"]).strip())
        # case: ~ab
        if len(argv) < 3:
            cmd = None
            argv = []
            argc = 0
        # case ~ab ...
        else:
            cmd = argv[2].lower()
            argv = argv[3:]
            argc = len(argv)

        reply = None

        channel = self.return_to_sender(args)
        from irclib import nm_to_n
        yournick = nm_to_n(args['source'])
        try:
            from irclib import is_channel
            from ValueModifier import IntValueModifier
            if not is_channel(channel):
                reply = "this is a channel only command"
            elif cmd == "grant":
                if argc != 3:
                    raise StopReply()

                import priv
                nick, ability, score = argv
                try:
                    score = IntValueModifier(score)
                except ValueError:
                    reply = "%s: score must be number" % yournick
                    raise StopReply()

                curscore = self.getUserAbilityScore(nick, channel,
                                                    ability) or 0
                score = score.apply(curscore)
                # normal users?
                if priv.checkPriv(args["source"], "ab_admin_priv") == 0 \
                 and priv.checkPriv(args["source"], "all_priv") == 0:
                    if nick == yournick:
                        reply = "You're so proud, %s" % yournick
                        raise StopReply()
                    yourscore = self.getUserAbilityScore(
                        yournick, channel, ability)
                    # apply rules
                    if not yourscore or yourscore < score:
                        yourscore = self.getUserAbilityScore(
                            yournick, channel, '*')
                        if not yourscore or yourscore < score:
                            reply = "You don't have enough ability score, %s" % yournick
                            raise StopReply()

                    if curscore >= score:
                        reply = "%s's %s ability is %d already" % (
                            nick, ability, curscore)
                        raise StopReply()

                abilityid = self.getAbilityId(ability, True)
                self.setUserAbilityScore(nick, channel, abilityid, score,
                                         yournick)
                reply = "%s's %s ability is set to %d" % (nick, ability, score)
            elif cmd == "despise":
                if argc != 2:
                    raise StopReply()
                ability, score = argv
                try:
                    score = IntValueModifier(score)
                except ValueError:
                    reply = "%s: score must be number" % yournick
                    raise StopReply()

                curscore = self.getUserAbilityScore(yournick, channel, ability)
                if not curscore:
                    reply = "%s: You have no %s ability despise for" % (
                        ability, yournick)
                    raise StopReply()

                score = score.apply(curscore)
                if curscore == score:
                    reply = "%s: You're yourself" % yournick
                elif curscore <= score:
                    reply = "%s: Are you conceited?" % yournick
                else:
                    abilityid = self.getAbilityId(ability, True)
                    self.setUserAbilityScore(yournick, channel, abilityid,
                                             score, yournick)
                    reply = "%s has despise him/herself to %d on %s ability" % (
                        yournick, score, ability)
            elif cmd == "top" or cmd == "help":
                if cmd == "help":
                    if argc != 1:
                        # module help
                        raise StopReply()
                    reply = "This function is in TODO"
                    raise StopReply()

                from irclib import IrcStringIO
                if argc == 1:
                    ability = argv[0]
                    user_scores = self.getTopAbilityUsers(channel, ability)
                    if not user_scores:
                        reply = "no one is capable of %s" % ability
                        raise StopReply()
                    buffer = IrcStringIO("top user(s) that capable of %s:" %
                                         ability)
                    for user_score in user_scores:
                        buffer.write(" %s*%s" % user_score)
                elif argc == 0:
                    abilityScoreUsers = self.getTopAbilities(channel)
                    if not abilityScoreUsers:
                        reply = "no one is superman"
                        raise StopReply()
                    from irclib import IrcStringIO
                    buffer = IrcStringIO("top abilities:")
                    for abilityScoreUser in abilityScoreUsers:
                        buffer.write(" %s*%s/%s" % abilityScoreUser)
                reply = buffer.getvalue()
            else:
                nick = None
                ability = None
                name = None  # name to guess
                if argc == 0:
                    # quick query
                    if cmd:
                        name = cmd
                    else:
                        nick = yournick
                elif cmd != "query":
                    raise StopReply()
                elif argc == 1:
                    # "query $nick"
                    name = argv[0]
                elif argc == 2:
                    # "query $nick $ability"
                    [nick, ability] = argv
                else:
                    raise StopReply()

                # guess if it's nick or ability
                if name:
                    abilityid = self.getAbilityId(name)
                    if abilityid:
                        ability = name
                        nick = yournick
                    else:
                        nick = name
                        ability = None
                if nick:
                    if ability:
                        score = self.getUserAbilityScore(
                            nick, channel, ability) or 0
                        if yournick == nick:
                            reply = "Your %s ability is %d" % (ability, score)
                            if score < 0:
                                reply = reply + ". rats!"
                        else:
                            reply = "%s's %s ability is %d" % (nick, ability,
                                                               score)
                    else:
                        ability_scores = self.getUserAbilities(nick, channel)
                        if not ability_scores:
                            reply = nick + " doesn't have any ability, is he/she disabled?"
                        else:
                            from irclib import IrcStringIO
                            buffer = IrcStringIO(nick + " is capable of")
                            for ability_score in ability_scores:
                                buffer.write(" %s*%s" % ability_score)
                            reply = buffer.getvalue()
                else:
                    reply = nick + " not found"
        except StopReply:
            pass

        if not reply:
            if cmd == "help" and argc == 0 or not self.helps.has_key(cmd):
                reply = "AbilityProfile: " + " ;; ".join(self.helps.values())
            else:
                reply = "AbilityProfile: " + self.helps[cmd]

        result = Event("privmsg", "", channel, [reply])
        return result
예제 #48
0
 def on_welcome(self, connection, event):
     self.listner.on_welcome()
     if is_channel(self.channel):
         connection.join(self.channel)
     else:
         sys.exit(1)
예제 #49
0
def on_connect(connection, event):
    print 'on_connect'
    if irclib.is_channel(target):
        connection.join(target)
    else:
        print 'target should be a channel!'
예제 #50
0
파일: network.py 프로젝트: jk0/svcshare
 def on_welcome(self, connection, event):
     self._curNick = event.target()
     self._network.statusIs(STATUS['connected'])
     self._logger.debug('Connected to IRC. Nick is %s.' % self._curNick)
     if irclib.is_channel(self._channel):
         connection.join(self._channel)
예제 #51
0
    def _irc_event_handler(self, connection, event):
        """[Internal] Manage IRC events"""

        # Answer ping
        if event.eventtype() == 'ping':
            connection.pong(connection.get_server_name())
            return

        # Events we always want to ignore
        if 'all' in event.eventtype() or 'motd' in event.eventtype(
        ) or event.eventtype() in [
                'nicknameinuse', 'nickcollision', 'erroneusnickname'
        ]:
            return
        if event.eventtype() in [
                'pong', 'privnotice', 'ctcp', 'nochanmodes', 'notexttosend',
                'currenttopic', 'topicinfo', '328', 'pubnotice', '042',
                'umode', 'welcome', 'yourhost', 'created', 'myinfo',
                'featurelist', 'luserclient', 'luserop', 'luserchannels',
                'luserme', 'n_local', 'n_global', 'endofnames', 'luserunknown',
                'luserconns', 'inviteonlychan', 'bannedfromchan',
                'channelisfull', 'badchannelkey', 'topic', 'noorigin'
        ]:
            self.error(1, 'ignoring IRC ' + event.eventtype(), debug=True)
            return

        source_nickname = None
        if event.source() and '!' in event.source():
            source_nickname = event.source().split('!')[0]

        # A string representation of the event
        event_str = '\nconnection=' + connection.__str__(
        ) + '\neventtype=' + event.eventtype() + '\nsource=' + repr(
            event.source()) + '\ntarget=' + repr(
                event.target()) + '\narguments=' + repr(event.arguments())
        debug_str = 'Received IRC event.' + event_str

        handled = False

        # Private message
        if event.eventtype() in ['privmsg', 'action']:

            if event.target() == self.nickname:
                # message is for the bot
                connection.privmsg(source_nickname,
                                   self.respond(event.arguments()[0]))
                return

            elif not irclib.is_channel(event.target()[0]):
                # search if the IRC user who sent the message is in one of the bridges
                for bridge in self.iter_bridges(irc_server=connection.server):
                    try:
                        from_ = bridge.get_participant(source_nickname)
                        # he is, forward the message on XMPP
                        if event.eventtype() == 'action':
                            action = True
                        else:
                            action = False
                        from_.say_on_xmpp_to(connection.nickname,
                                             event.arguments()[0],
                                             action=action)
                        return
                    except Bridge.NoSuchParticipantException:
                        continue

                # he isn't, send an error
                connection.privmsg(
                    source_nickname,
                    'XIB error: you cannot send a private message to an XMPP user if you are not in one of the chans he is in'
                )

        # Connection errors
        if event.eventtype() in ['disconnect', 'kill', 'error']:
            if len(event.arguments()) > 0 and event.arguments(
            )[0] == 'Connection reset by peer':
                self.error(2, debug_str, debug=True)
            else:
                self.error(say_levels.debug, debug_str, send_to_admins=True)
            return

        # Chan errors
        if event.eventtype() in ['cannotsendtochan', 'notonchannel']:
            self.error(2, debug_str, debug=True)

            bridge = self.get_bridge(irc_room=event.arguments()[0],
                                     irc_server=connection.server)

            if event.eventtype() == 'cannotsendtochan':
                if connection.nickname == self.nickname:
                    bridge._join_irc_failed(event.eventtype())
                else:
                    p = bridge.get_participant(connection.nickname)
                    p._close_irc_connection(event.eventtype())
                    p.irc_connection = event.eventtype()

            elif event.eventtype() == 'notonchannel':
                if connection.nickname == self.nickname:
                    bridge.restart(
                        message=
                        'Restarting bridge because we received the IRC event '
                        + event.eventtype())
                else:
                    p = bridge.get_participant(connection.nickname)
                    p.irc_connection.join(bridge.irc_room)

            return

        # Ignore events not received on bot connection
        if connection.nickname != self.nickname:
            self.error(1,
                       'ignoring IRC ' + event.eventtype() +
                       ' not received on bridge connection',
                       debug=True)
            return

        # Server events
        if event.eventtype() in ['quit', 'nick']:
            for bridge in self.iter_bridges(irc_server=connection.server):

                try:
                    from_ = bridge.get_participant(source_nickname)
                except Bridge.NoSuchParticipantException:
                    continue

                handled = True

                # Quit event
                if event.eventtype() == 'quit':
                    if len(event.arguments()) > 0:
                        leave_message = event.arguments()[0]
                    else:
                        leave_message = 'Left server.'
                    bridge.remove_participant('irc', from_.nickname,
                                              leave_message)
                    continue

                # Nickname change
                if event.eventtype() == 'nick':
                    from_.change_nickname(event.target(), 'xmpp')
                    continue

            if handled:
                return

        # Chan events
        if event.eventtype() in [
                'pubmsg', 'action', 'part', 'kick', 'mode', 'join'
        ]:

            if event.eventtype() in [
                    'pubmsg', 'action', 'part', 'kick', 'join'
            ] and not source_nickname:
                self.error(
                    say_levels.debug, 'a source is needed for a ' +
                    event.eventtype() + ' event' + event_str)
                return

            if event.eventtype() in ['kick', 'mode'] and len(
                    event.arguments()) == 0:
                self.error(
                    say_levels.debug, 'at least 1 argument is needed for a ' +
                    event.eventtype() + ' event' + event_str)
                return

            chan = event.target().lower()

            bridge = self.get_bridge(irc_room=chan,
                                     irc_server=connection.server)

            from_ = None
            if source_nickname:
                try:
                    from_ = bridge.get_participant(source_nickname)
                except Bridge.NoSuchParticipantException:
                    pass

            # Join event
            if event.eventtype() == 'join':
                bridge.add_participant('irc', source_nickname)
                return

            # kick handling
            if event.eventtype() == 'kick':
                try:
                    kicked = bridge.get_participant(event.arguments()[0])
                except Bridge.NoSuchParticipantException:
                    self.error(
                        say_levels.debug,
                        'a participant that was not here has been kicked ? WTF ?'
                        + event_str)
                    return

                leave_message = 'kicked by ' + source_nickname
                if len(event.arguments()) > 1:
                    leave_message += ' with reason: ' + event.arguments()[1]
                else:
                    leave_message += ' (no reason was given)'
                log_message = '"' + kicked.nickname + '" has been ' + leave_message

                self.error(say_levels.warning, log_message)

                if isinstance(kicked.irc_connection, irclib.ServerConnection):
                    # an IRC duplicate of an XMPP user has been kicked, auto-rejoin
                    kicked.irc_connection.join(bridge.irc_room)
                elif isinstance(kicked.xmpp_c, xmpp.client.Client):
                    # an IRC user has been kicked, make its duplicate leave
                    kicked.leave(leave_message)
                else:
                    # an IRC user with no duplicate on XMPP has been kicked, say it on XMPP
                    bridge.say(say_levels.warning, log_message, on_irc=False)
                return

            # Part event
            if event.eventtype() == 'part':
                if not from_:
                    self.error(
                        say_levels.debug,
                        'a participant that wasn\'t here left:' + event_str)
                    return
                if len(event.arguments()) > 0:
                    leave_message = event.arguments()[0]
                else:
                    leave_message = 'Left channel.'
                bridge.remove_participant('irc', from_.nickname, leave_message)
                return

            # Chan message
            if event.eventtype() in ['pubmsg', 'action']:
                message = event.arguments()[0]
                if event.eventtype() == 'action':
                    action = True
                else:
                    action = False
                if isinstance(from_, Participant):
                    from_.say_on_xmpp(message, action=action)
                else:
                    bridge.say_on_behalf(source_nickname,
                                         message,
                                         'xmpp',
                                         action=action)
                return

            # Mode event
            if event.eventtype() == 'mode':
                if len(event.arguments()) == 1:
                    # chan mode
                    self.error(1,
                               'ignoring IRC mode "' + event.arguments()[0] +
                               '" for chan "' + event.target() + '"',
                               debug=True)
                elif len(event.arguments()) == 2:
                    # participant mode
                    if event.arguments(
                    )[1] != self.nickname or not 'o' in event.arguments()[0]:
                        self.error(1,
                                   'ignoring IRC mode "' +
                                   event.arguments()[0] + '" for "' +
                                   event.arguments()[1] + '" in chan "' +
                                   event.target() + '"',
                                   debug=True)
                        return
                    if re.search('\+[^\-]*o', event.arguments()[0]):
                        # bot is channel operator
                        bridge.irc_op = True
                        self.error(
                            say_levels.notice,
                            'bot has IRC operator privileges in ' + chan)
                    elif re.search('\-[^\+]*o', event.arguments()[0]):
                        # bot lost channel operator privileges
                        if bridge.irc_op:
                            self.error(say_levels.notice,
                                       'bot lost IRC operator privileges in ' +
                                       chan,
                                       send_to_admins=True)
                        bridge.irc_op = False
                else:
                    # unknown mode
                    self.error(
                        say_levels.debug,
                        'unknown IRC "mode" event (has 3 arguments):' +
                        event_str)
                return

        # Namreply event
        if event.eventtype() == 'namreply':
            bridge = self.get_bridge(irc_room=event.arguments()[1].lower(),
                                     irc_server=connection.server)
            for nickname in re.split('(?:^[&@\+%]?|(?: [&@\+%]?)*)',
                                     event.arguments()[2].strip()):
                if nickname == '' or nickname == self.nickname:
                    continue
                bridge.add_participant('irc', nickname)
            return

        # Unhandled events
        self.error(1, 'event not handled', debug=True)
        self._send_message_to_admins(
            say_levels.debug,
            'The following IRC event was not handled:' + event_str)