Exemple #1
0
 def on_ctcp(self, c, e):
     if e.arguments()[0] == 'VERSION':
         c.ctcp_reply(nm_to_n(e.source()),
                      'Bot for watching stuff in %s.' % self.channel)
     elif e.arguments()[0] == 'PING':
         if len(e.arguments()) > 1:
             c.ctcp_reply(nm_to_n(e.source()), 'PING ' + e.arguments()[1])
Exemple #2
0
	def Try(self,bot,query):
		if query.Directed():
			_match = self._rx.match(query.Message())
			if _match:
				if _match.group('id')[0] == "#": #delete by id number, otherwise by key
					id=_match.group('id')[1:]
					entry = bot.sql(r'select name,protected from %(table)s where id=%%s'%{'table':self._table},(id),['key','protected'])[0] #id is the primary key, so there will only be one tupple returned
					if (entry['protected']==1 and isAdmin(query.From())) or entry['protected'] == 0:
						self._clearCache(bot,entry['key'])
						bot.sql(r'delete from %(table)s where id=%%s'%{'table':self._table},(id))
						self.OK(bot,query)
						resp = self.Handled('deleted %(type)s #%(num)s for %(who)s'%{'type':self._type,'num':id,'who':nm_to_n(query.From())})
					else:
						bot.say(query,"Sorry %(who)s, that %(type)s is protected"%{'who':nm_to_n(query.From()),'type':self._type})
						resp = self.Handled('%(who)s attempted to delete protected %(type)s #%(num)s'%{'who':query.From(),'num':id,'type':self._type})
				elif isAdmin(query.From()): #batch delete, requires admin
					key=_match.group('id')
					bot.sql('delete from %(table)s where name=%%s'%{'table':self._table},(key))
					self._clearCache(bot, key)
					self.OK(bot,query)
					resp=self.Handled("deleted %(type)s '%(key)s' for %(who)s"%{'type':self._type,'who':query.From(),'key':key})
				else:
					bot.say(query,"Sorry %(who)s, you need to be an admin to do that"%{'who':nm_to_n(query.From())})
					resp = self.Handled("%(who)s attempted to batch delete factoid '%(key)s'"%{'who':query.From(),'key':key})
				return resp
		return self.Unhandled()
Exemple #3
0
    def queuemsg(self, event, target, phrase):
        """
        A local wrapper to connection.privmsg

        This wrapper adds a typing delay, improves grammar, performs replies,
        then sends the message out.
        """

        if phrase is None or len(phrase) is 0:
            return

        phrase = phrase.replace("$who", nm_to_n(event.source()))
        phrase = phrase.replace(self.nick+' ', 'I ').replace('I is', 'I am')
        phrase = phrase.lstrip('10')
        
        # If any statement contains <reply> we only say what comes
        # after it.
        index = phrase.lower().find('<reply>')
        if index > -1:
            self.queuemsg(
                event,
                target,
                "%s" % (
                    phrase[index+7:].strip()
                )
            )

            return
        
        if (target == self.nick):
            target = nm_to_n(event.source())

        self.output.put((target,phrase))
  def kill(self, e, who):
    "Allow a werewolf to express intent to 'kill' somebody."
    if self.time != "night":
      self.reply(e, "Are you a werewolf?  In any case, it's not nighttime.")
      return
    if nm_to_n(e.source()) not in self.wolves:
      self.reply(e, "Huh?")
      return
    if who not in self.live_players:
      self.reply(e, "That player either doesn't exist, or is dead.")
      return
    if len(self.wolves) > 1:
      # Multiple wolves are alive:
      self.wolf_votes[nm_to_n(e.source())] = who
      self.reply(e, "Your vote is acknowledged.")

      # If all wolves have voted, look for agreement:
      if len(self.wolf_votes) == len(self.wolves):
        for killee in self.wolf_votes.values():
          if who != killee:
            break
        else:
          self.wolf_target = who
          self.reply(e, "It is done. The werewolves agree.")
          if self.check_night_done():
            self.day()
          return
        self.reply(e, "Hm, I sense disagreement or ambivalence.")
        self.reply(e, "You wolves should decide on one target.")
    else:
      # only one wolf alive, no need to agree with anyone.
      self.wolf_target = who
      self.reply(e, "Your decision is acknowledged.")
      if self.check_night_done():
        self.day()
Exemple #5
0
 def on_privmsg(self, c, e):
     nick = nm_to_n(e.source())
     targ = nm_to_n(e.target())
     msg = e.arguments()[0]
     print "[on_privmsg] received '%s' from '%s' for %s" % (msg, nick, targ)
     message = '$To: %s From: %s $<%s> %s|' % (targ, nick, nick, msg)
     self.hub.local_user.sendmessage(message)
 def on_msg(c, e):
     try:
         callback(irclib.nm_to_n(e.source()), e.arguments()[0])
     except None:   
         # remove None in production use to not crash on exceptions
         log("Unhandled exception caused by %s: %s" %  \
             (irclib.nm_to_n(e.source()), sys.exc_info()))
Exemple #7
0
	def handler(self, **args):
		"""when somebody says something handled by this module, their
		count for that thing is incremented by this function"""
		from irclib import Event
		import database

		import re
		from irclib import nm_to_n
		
		content = args["text"]
		lower_content = content.lower()
		
		count = 0	# Init count to 0.
		for scope in stats_scope:
			if content.find(scope) >= 0 and len(content) != len("~" + scope + "stats") \
			and (lower_content.startswith(bot_nick.lower()) == 0 or content.endswith(scope + "stats") == 0 \
			or len(content) - len(bot_nick) - content.count(" ") - len(scope + "stats") - 2 > 0 ):
				count = content.count(scope)
				keyword = scope
				
				keyword = keyword.lower()
				
				results=database.doSQL("select counter from stats where nick = '" + nm_to_n(args["source"]) + "' and type = '" + keyword + "'")
				if len(results) == 0:
					database.doSQL("insert into stats values( '" + nm_to_n(args["source"]) + "', '" + keyword + "', 0)")
					results=database.doSQL("select counter from stats where nick = '" + nm_to_n(args["source"]) + "' and type = '" + keyword + "'")
				database.doSQL("update stats set counter = counter + %d where nick = '" % count + nm_to_n(args["source"]) + "' and type= '" + keyword+"'")
		target=args["channel"]
		if args["type"] == "privmsg":
			from irclib import nm_to_n
			target=nm_to_n(args["source"])
		return Event("continue", "", target, [ "" ])
 def on_ctcp(self, c, e):
     if e.arguments()[0] == 'VERSION':
         c.ctcp_reply(nm_to_n(e.source()),
                      "Bot for filtering account unifications in %s" % self.rcfeed)
     elif e.arguments()[0] == 'PING':
         if len(e.arguments()) > 1:
             c.ctcp_reply(nm_to_n(e.source()),
                          "PING " + e.arguments()[1])
Exemple #9
0
	def _on_nick(self, c, e):
		"""[Internal]"""
		before = nm_to_n(e.source())
		after = e.target()
		for ch in self.channels.values():
			if ch.has_user(before):
				ch.change_nick(before, after)
		if nm_to_n(before) == self._nickname:
			self._nickname = after
Exemple #10
0
 def on_ctcp(self, serverconnection, event):
     if event.arguments()[0] == 'ACTION':
         event.arguments().pop(0)
         self.on_action(serverconnection, event)
     elif event.arguments()[0] == 'VERSION':
         serverconnection.ctcp_reply(nm_to_n(event.source()), self.config.version)
     elif event.arguments()[0] == 'PING':
         if len(event.arguments()) > 1:
             serverconnection.ctcp_reply(nm_to_n(event.source()), 'PING ' + event.arguments()[1])
Exemple #11
0
 def on_privnotice(self, c, e):
     source = e.source()
     if (source and str(nm_to_n(e.source())).lower() in self.admin) or\
     (source and str(nm_to_n(e.source())).lower() == 'nickserv'):
         if e.arguments()[0].find('IDENTIFY') >= 0:
             # Received request to identify
             if self.ircpass and self.nickname == c.get_nickname():
                 c.privmsg('nickserv', 'identify %s' % self.ircpass)
         if e.arguments()[0].find('NICKNAME') >= 0:
             c.nick(self.nickname)
Exemple #12
0
	def on_ctcp(self, c, e):
		"""Default handler for ctcp events.

		Replies to VERSION and PING requests.
		"""
		if e.arguments()[0] == "VERSION":
			c.ctcp_reply(nm_to_n(e.source()), self.get_version())
		elif e.arguments()[0] == "PING":
			if len(e.arguments()) > 1:
				c.ctcp_reply(nm_to_n(e.source()),
							 "PING " + e.arguments()[1])
Exemple #13
0
def on_kick(connection, event):
    # nm_to_n(event.source())== Person who did it (eg OP), event.arguments()[1] == reason   event.arguments()[0]=person kick,  event.target() == channel
    Dprnt("DEBUG: IRC: [Event] On Kicked")
    # For now easy to shut down app then try to rejoin/maintain connection for another days work
    # Better having some kicking handling then none. (possible Bugs here may be if no reason was said)
    if event.arguments()[0] == YOURNICK:
        chanwin.addLine("You have Kicked from the channel by " +nm_to_n(event.source())+  "(" + event.arguments()[1] + ")")
        msgok("You have been Kicked \n Might be easiy to Reboot XBMC now")
    else:
        #Donno has kicked DonnoII from #xbmc (bye)
        chanwin.addLine(nm_to_n(event.source()) + " has kicked " + event.arguments()[0] + " from " + event.target() +  " ("  + event.arguments()[1] + ")" )
Exemple #14
0
	def on_privmsg(self, c, e):
		print "Got privmsg from "+irclib.nm_to_n(e.source())+" to "+e.target()
		a = e.arguments()[0]
		if a[0] == '!':
			command = a[1:]
		else:
			a = e.arguments()[0].split(":", 1)
			if len(a) > 1 and a[0].lower() == self.connection.get_nickname().lower():
				command = a[1].strip()
			else:
				command = e.arguments()[0]
		self.do_command(c, irclib.nm_to_n(e.source()), e.target(), command)
Exemple #15
0
		def on_nick(self, c, e):
			source_before = nm_to_n(e.source()).lower()
			source_after = nm_to_n(e.target()).lower()
			source_host = nm_to_h(e.source())
			
			if source_before in self.ignore:
				return

			for module in self.modules.values():
				try:
					module.handle_on_change_nick(source_before, source_host, source_after)
				except Exception, e:
					traceback.print_exc(file=sys.stdout)
Exemple #16
0
def on_join(c, e):
	# temporary for now, until I figure out config options
	if irclib.nm_to_n(e.source()) == bot._nickname:
		lognames[e.target()] = e.target()+".log"
	log = lognames.get(e.target(), None)
	if log == None:
		return
	logfile = open(logdirectory+log, 'a')
	if irclib.nm_to_n(e.source()) == bot._nickname:
		print >>logfile, "-- Log opened %s" % (time.strftime("%a %b %d %Y %H:%M:%S %Z"))
		currentday[e.target()] = datetime.date.today()
	print >>logfile, "%s -!- %s [%s] has joined %s" % (timestamp(), irclib.nm_to_n(e.source()), irclib.nm_to_uh(e.source()), e.target())
	logfile.close()
Exemple #17
0
def on_join(c, e):
	nick = irclib.nm_to_n(e.source())
	if bot._quietmode:
		t = irclib.nm_to_n(e.source())
	else:
		t = e.target()
	print bot._quietmode, t
	if nick in memos:
		c.privmsg(t, "Memos for "+nick+":")
		for msg in memos[nick]:
			c.privmsg(t, msg)
			time.sleep(3)
		del memos[nick]
Exemple #18
0
    def on_ctcp(self, c, e):
        """Default handler for ctcp events.

        Replies to VERSION and PING requests and relays DCC requests
        to the on_dccchat method.
        """
        if e.arguments()[0] == "VERSION":
            c.ctcp_reply(nm_to_n(e.source()), "VERSION " + self.get_version())
        elif e.arguments()[0] == "PING":
            if len(e.arguments()) > 1:
                c.ctcp_reply(nm_to_n(e.source()), "PING " + e.arguments()[1])
        elif e.arguments()[0] == "DCC" and e.arguments()[1].split(" ", 1)[0] == "CHAT":
            self.on_dccchat(c, e)
Exemple #19
0
    def on_ctcp(self, c, e):
        print "ctcp"
        print e.arguments()

        if not e.arguments()[0]=='ACTION':
            SingleServerIRCBot.on_ctcp(self, c,e)
        else:
            if nm_to_n( e.source() ) not in self.komconn.bot.keys():
                #send_message( self.komconn, self.komconn.confs[ e.target() ],
                # str(e.source()) + " " + str( e.arguments()[0] ))
                send_comment( self.komconn, self.komconn.confs[ e.target().lower() ],
                              str(e.source())+" gör något",
                              nm_to_n(e.source()) + " " + str( e.arguments()[1] ),
                              nm_to_n(e.source()), nm_to_uh(e.source()), 1)
Exemple #20
0
 def on_ctcp(self, c, e):
     args = e.arguments()
     if args[0] == 'VERSION':
         #print 'on ctcp VERSION'
         log.debug('on ctcp VERSION')
         self.connection.ctcp_reply(irclib.nm_to_n(e.source()),
                                    'OIL %s' % VERSION)
     elif args[0] == 'ACTION':
         channel = e.target().lstrip(''.join(CHANNEL_PREFIXES))
         source = irclib.nm_to_n(e.source())
         message = args[1]
         print channel, 'ctcp', source, args[1], args[0]
         #self.send_event(channel, 'ctcp', source, args[1], subtype=args[0])
         self.write_event(channel, 'ctcp', source, args[1], subtype=args[0])
Exemple #21
0
	def on_join(self, c, e):
		host = nm_to_h(e.source())

		if nm_to_n(e.source()) == self.nick:
			return

		if not host.endswith('users.quakenet.org'):
			guy = e.source()
			ip = gethostbyname_cached(clear_host(nm_to_h(guy)))

			hosto = get_host_o(ip)
			hosto.join_date = datetime.datetime.now()

			self.lookup_and_kill(nm_to_n(guy), ip)
Exemple #22
0
 def on_privmsg(self, c, e):
     nickname = nm_to_n(e.source())
     if nickname in self.authorized:
         if nickname in self.loggedinusers:
             self.do_command(nm_to_n(e.source()),
                             e.target(),
                             e.arguments()[0])
         else:
             c.whois(nickname)
             #sleep(1)
             self.cmdqueue.append(nm_to_n(e.source()))
             #chan/nick
             self.cmdqueue.append(e.target())
             #destination
             self.cmdqueue.append(e.arguments()[0])
Exemple #23
0
 def get_auth(self, c, e, nick):
     """
     Determines highest current user level of nick
     
     Result: n: normal users, v: voiced users, o: op users
     """
     auth = "n"
     for chname, chobj in self.channels.items():
         if nm_to_n(nick) in chobj.opers():
             auth = "o"
             break
         if nm_to_n(nick) in chobj.voiced():
             auth = "v"
     print("%s has +%s" % (nm_to_n(nick), auth))
     return auth
Exemple #24
0
def on_part(c, e):
	log = lognames.get(e.target(), None)
	if log == None:
		return
	logfile = open(logdirectory+log, 'a')
	partreason = ""
	try:
		partreason = e.arguments()[0]
	except IndexError:
		partreason = "Client quit"
	print >>logfile, "%s -!- %s [%s] has left %s [%s]" % (timestamp(), irclib.nm_to_n(e.source()), irclib.nm_to_uh(e.source()), e.target(), partreason)
	if irclib.nm_to_n(e.source()) == bot._nickname:
		print >>logfile, "-- Log closed %s" % (time.strftime("%a %b %d %Y %H:%M:%S %Z"))
		del currentday[e.target()]
	logfile.close()
Exemple #25
0
    def on_pubmsg(self, c, e):
        # Handle a message recieved from the channel
        source_name = nm_to_n(e.source()).lower()
        source_host = nm_to_h(e.source())
        message = e.arguments()[0]

        if source_name in self.ignore:
            return

        self.last_message_sender = self.channel

        # If a message was addressed specifically to the bot, note this and strip
        # this from the message
        addressed_to_BeardBot = False
        if irc_lower(message).startswith("%s: " % self.nick.lower()):
            message = message.split(": ", 1)[-1]
            addressed_to_BeardBot = True
        elif irc_lower(message).startswith("%s, " % self.nick.lower()):
            message = message.split(", ", 1)[-1]
            addressed_to_BeardBot = True

        # Alert each module that a message has arrived
        for module in self.modules.values():
            try:
                if addressed_to_BeardBot:
                    module.handle_addressed_message(source_name, source_host,
                                                    message.decode("UTF8"))
                else:
                    module.handle_channel_message(source_name, source_host,
                                                  message.decode("UTF8"))
            except Exception, e:
                traceback.print_exc(file=sys.stdout)
Exemple #26
0
	def handler(self, **args):
		from irclib import Event, nm_to_n
		params = args['text'].strip().split(' ')[2:]
		if not params or params[0].lower() == 'help':
			msg = 'Usage: agecompare [ |help|$nick[ $nick2]]'
		else:
			nick1 = params[0]
			if len(params) == 2:
				nick2 = params[1]
			else:
				nick2 = nm_to_n(args['source'])
			self.Debug(params)
			b1 = Birthday(nick1).get()
			b2 = Birthday(nick2).get()
			if not b1:
				msg = "Birthday of %s is not set" % (nick1)
			elif not b2:
				msg = "Birthday of %s is not set" % (nick2)
			else:
				self.Debug(b1, b2, nick1, nick2)
				if b1 == b2:
					op = "=="
				elif b1 > b2:
					op = "<"
				else:
					op = ">"
				msg = "age(%s) %s age(%s)" % (nick1, op, nick2)

		return Event("privmsg", "", self.return_to_sender(args), [ msg ])
Exemple #27
0
 def _on_join(self, c, e):
     """[Internal]"""
     ch = e.target()
     nick = nm_to_n(e.source())
     if nick == c.get_nickname():
         self.channels[ch] = Channel()
     self.channels[ch].add_user(nick)
Exemple #28
0
    def wrapper(*args, **kwargs):
        """wrapper"""
        method = to_wrap or kwargs['method']

        self, _connection, event = args

        allowed = not require_trust or event.user.trusted

        # These next two blocks are hideous, refactor
        params = (
            nm_to_n(event.source()),  # User nick
            method.__name__,  # method name
            event.arguments()[0]  # user message
        )

        if allowed:
            try:
                resp = method(*args)
            except Exception, e:
                print '== Exception------'
                traceback.print_exc(e)
                print '== ---------------'

                resp = "Error: %s" % e
            finally:
Exemple #29
0
def on_privmsg(c, e):
    if logprivmsg:
        nick = irclib.nm_to_n(e.source())
        log = nick + ".priv.log"
        logfile = open(logdirectory + log, 'a')
        print >> logfile, "%s<%s> %s" % (timestamp(), nick, e.arguments()[0])
        logfile.close()
Exemple #30
0
 def on_join(self,serv,ev):
     self.auteur = irclib.nm_to_n(ev.source())
     self.canal = ev.target()
     self.serv = serv
     for user in settings.OP:
         if user == self.auteur:
             self.serv.mode("#recalbox", "+o "+self.auteur)
Exemple #31
0
 def _on_quit(self, c, e):
     """[Internal]"""
     nick = nm_to_n(e.source())
     self.log.info(nick + ' has quit')
     for ch in self.channels.values():
         if ch.has_user(nick):
             ch.remove_user(nick)
Exemple #32
0
 def __init__(self, parent, event):
     self.args = event.arguments()[0].split()[1:]
     self.parent = parent
     self.nick = nm_to_n(event.source())
     self.name = nm_to_u(event.source()).strip('~')
     self.channel = event.target()
     self.__setup__()
Exemple #33
0
    def do_command(self, e, cmd):
        nick = nm_to_n(e.source())
        c = self.connection

        if cmd == "disconnect":
            self.disconnect()
        elif cmd == "die":
            self.die()
        elif cmd == "stats":
            for chname, chobj in list(self.channels.items()):
                c.notice(nick, "--- Channel statistics ---")
                c.notice(nick, "Channel: " + chname)
                users = chobj.users()
                users.sort()
                c.notice(nick, "Users: " + ", ".join(users))
                opers = chobj.opers()
                opers.sort()
                c.notice(nick, "Opers: " + ", ".join(opers))
                voiced = chobj.voiced()
                voiced.sort()
                c.notice(nick, "Voiced: " + ", ".join(voiced))
        elif cmd == "dcc":
            dcc = self.dcc_listen()
            c.ctcp("DCC", nick, "CHAT chat %s %d" % (
                ip_quad_to_numstr(dcc.localaddress),
                dcc.localport))
        else:
            c.notice(nick, "Not understood: " + cmd)
 def on_privnotice(self, c, e):
     source = e.source()
     if source and irc_lower(nm_to_n(source)) == 'nickserv':
         if e.arguments()[0].find('IDENTIFY') >= 0:
             # Received request to identify
             if self.nickpass and self.desired_nickname == c.get_nickname():
                 self.queue.send('identify %s' % self.nickpass, 'nickserv')
Exemple #35
0
    def on_pubmsg(self, c, e):
        print "pubmsg"

        print e
        print dir(e)
        print e.target()
        
        print "From %s " % nm_to_n( e.source() )
        print self.komconn.bot.keys()

        if nm_to_n( e.source() ) not in self.komconn.bot.keys():
            #send_message( self.komconn, self.komconn.confs[ e.target() ], str(e.source()) + " " + str( e.arguments()[0] ))
            send_comment( self.komconn,  self.komconn.confs[ e.target().lower() ], str(e.source()) + " säger ", str( e.arguments()[0] ),
                          nm_to_n(e.source()), nm_to_uh(e.source()), 1)

        return
Exemple #36
0
    def write_event(self, name, event, params={}):
        now = time.time()
        chans = event.target()

        msg = {
            'host': event.source(),
            'source': nm_to_n(event.source()),
            'time': now,
            'action': name
        }

        if event.arguments():
            msg['message'] = event.arguments()[0]

        if params:
            msg['params'] = params

        message_id = redis.incr('message_ids')

        # Quit goes across all channels
        if not chans or not chans.startswith('#'):
            chans = self.chans
        else:
            chans = [chans]

        for chan in chans:
            redis.sadd('channels', chan)
            redis.sadd('channel:%s:dates' % chan,
                       time.strftime('%F', time.gmtime(now)))
            redis.hset('channel:%s:messages' % chan, message_id,
                       json.dumps(msg))
Exemple #37
0
def on_join(c, e):
    # temporary for now, until I figure out config options
    if irclib.nm_to_n(e.source()) == bot._nickname:
        lognames[e.target()] = e.target() + ".log"
    log = lognames.get(e.target(), None)
    if log == None:
        return
    logfile = open(logdirectory + log, 'a')
    if irclib.nm_to_n(e.source()) == bot._nickname:
        print >> logfile, "-- Log opened %s" % (
            time.strftime("%a %b %d %Y %H:%M:%S %Z"))
        currentday[e.target()] = datetime.date.today()
    print >> logfile, "%s -!- %s [%s] has joined %s" % (
        timestamp(), irclib.nm_to_n(e.source()), irclib.nm_to_uh(
            e.source()), e.target())
    logfile.close()
Exemple #38
0
    def on_ctcp(self, c, e):
        """Default handler for ctcp events.

        Replies to VERSION and PING requests and relays DCC requests
        to the on_dccchat method.
        """
        if e.arguments()[0] == "VERSION":
            c.ctcp_reply(nm_to_n(e.source()),
                         "VERSION " + self.get_version())
        elif e.arguments()[0] == "PING":
            if len(e.arguments()) > 1:
                c.ctcp_reply(nm_to_n(e.source()),
                             "PING " + e.arguments()[1])
        elif e.arguments()[0] == "DCC" and string.split(e.arguments()[1],
                                                        " ", 1)[0] == "CHAT":
            self.on_dccchat(c, e)
Exemple #39
0
    def on_pubmsg(self, serv, ev):
        auteur = irclib.nm_to_n(ev.source())
        canal = ev.target()
        message = ev.arguments()[0].lower()
        if self.search in message:
            try:
                self.nb = 0
                query = message.replace('?search ', '')
                nb_result = self.api.count(query)

                serv.privmsg(
                    canal,
                    'Number of result(s) : %s' % (nb_result.get('total')))

                result = self.api.search(query)

                for service in result['matches']:
                    if (self.nb < self.request_nb):
                        serv.privmsg(canal, service['ip_str'])
                        time.sleep(0.1)
                        self.nb = self.nb + 1
                    else:
                        self.nb = 0
                        break

            except Exception, e:
                serv.privmsg(canal, "This request don't work.")
Exemple #40
0
    def on_pubmsg(self, c, e):
        # process messages from the joined channels
        nick = nm_to_n(e.source())
        channel = e.target()
        message = e.arguments()[0]

        self.process_message(c, nick, channel, message, True)
Exemple #41
0
 def _on_nick(self, c, e):
     """[Internal]"""
     before = nm_to_n(e.source())
     after = e.target()
     for ch in self.channels.values():
         if ch.has_user(before):
             ch.change_nick(before, after)
Exemple #42
0
    def on_privmsg(self, serv, ev):
        author = irclib.nm_to_n(ev.source())
        message = ev.arguments()[0].strip()
        arguments = message.split(' ')
        nombreArg = len(arguments)

        # OWNER OPTIONS
        if (author == bot_owner):
            if ('!say' == arguments[0]):
                serv.privmsg(arguments[1], message.replace('!say', '')\
                    .replace(arguments[1], '')[2:])
            elif ('!act' == arguments[0]):
                serv.action(arguments[1], message.replace('!act', '')\
                    .replace(arguments[1], '')[2:])
            elif ('!j' == arguments[0]):
                serv.join(message[3:])
            elif ('!p' == arguments[0]):
                serv.part(message[3:])
            else:
                serv.privmsg(
                    author, "n00b " + author + " ! "
                    "Tu causes à ton bot là !")
        else:
            serv.privmsg(author, "Hey "+author+", t'as craqué ou quoi ? "\
                "Tu causes à un bot là, spice de n00b !")
Exemple #43
0
    def do_command(self, e, cmd):
        nick = nm_to_n(e.source())
        c = self.connection

        if cmd.startswith("display "):
            message = cmd[8:]
            if len(message) > 1:
                c.notice(nick, "I'm displaying " + message)
                print message
                self.message_display_buffer = message
                self.sign.OneLine(message)
        elif cmd == "clear":
            c.notice(nick, "I'm clearing the sign")
            self.message_display_buffer = ""
            self.sign.OneLine("")
            print
        elif cmd == "disconnect":
            self.disconnect()
        elif cmd == "die":
            self.die()
        elif cmd == "help":
            c.notice(nick, "Hi " + nick + ", my name is " + self.get_version())
            c.notice(nick, "--- Here's what I can do:")
            c.notice(nick, "help")
            c.notice(nick, "disconnect")
            c.notice(nick, "die")
            c.notice(nick, "display - display something on the sign")
            c.notice(nick, "clear - clear the sign")
        else:
            c.notice(nick, "I don't know how to " + cmd)
Exemple #44
0
def oraakkeli(self, e, c):

    line = e.arguments()[0]
    nick = nm_to_n(e.source())

    query = string.join(line.split()[1:], " ")

    if not len(query):
        c.privmsg(e.target(), "%s, mitä vittua nää yrität?" % (nick))
        return

    # lintukoto expects latin-1
    #query = ircutil.recode(query,'latin-1')

    opr = opener()

    uri = "%s%s" % (oraakkeli_url, query)

    try:
        fd = opr.open(uri)
    except:
        print "url.py: FAIL opening %s" % uri
        c.privmsg(e.target(), "Sori, oraakkeli on nyt lomalla?")
        return

    reply = fd.read()
    fd.close

    if reply.startswith('<'):
        reply = "nyt en kuule jouda vastaamaan."

    c = self.connection
    c.privmsg(e.target(), "%s, %s" % (nick, reply))
Exemple #45
0
 def on_privmsg(self, serv, ev):
     author = irclib.nm_to_n(ev.source())
     message = ev.arguments()[0]
     self.__prompt('privmsg', self.__safe_prompt(message), author = author)
     self.default(author, author, serv, message)
     if self._stat[author].status == -1:
         self.default_admin(author, author, serv, message)
Exemple #46
0
    def on_pubmsg(self, serv, ev):
        """
        Méthode appelée à la réception d'un message, qui exclut son expéditeur s'il
        écrit une insulte.
        """

        # Il n'est pas indispensable de passer par des variables
        # Ici elles permettent de clarifier le tout.
        auteur = irclib.nm_to_n(ev.source())
        masque_auteur = ev.source()
        canal = ev.target()
        message = ev.arguments()[0].lower()  # Les insultes sont écrites en minuscules.

        if message == "!quit" and irclib.mask_matches(masque_auteur, "*!*@GG-B3C3AEFC.w80-15.abo.wanadoo.fr"):
            # serv.privmsg(canal, "You murder me !")
            serv.part(canal, "You murder me !")
            self.die()

        if message == "chell":
            serv.privmsg(canal, "Do not mention her !")

        for insulte in self.insultes:
            if insulte in message:
                serv.privmsg(canal, "3...")
                serv.execute_delayed(1, serv.privmsg, (canal, "2..."))
                serv.execute_delayed(2, serv.privmsg, (canal, "1..."))
                serv.execute_delayed(3, serv.privmsg, (canal, "Continue testing !"))
                # serv.execute_delayed(3, serv.kick, (auteur, "Continue testing !"))
                break
Exemple #47
0
 def do_command(self, e, cmd):
     nick = nm_to_n(e.source())
     c = self.connection
     #run through all known commands, add more here if needed
     if cmd == "disconnect":
         self.disconnect()
     elif cmd == "die":
         c.privmsg(self.channel,"I shall!!!")
         self.die()
     elif cmd == "forget":
         self.reset()
         c.privmsg(self.channel,"I forgot!")
     elif cmd == "stats":
         for chname, chobj in self.channels.items():
             c.notice(nick, "--- Channel statistics ---")
             c.notice(nick, "Channel: " + chname)
             users = chobj.users()
             users.sort()
             c.notice(nick, "Users: " + ", ".join(users))
             opers = chobj.opers()
             opers.sort()
             c.notice(nick, "Opers: " + ", ".join(opers))
             voiced = chobj.voiced()
             voiced.sort()
             c.notice(nick, "Voiced: " + ", ".join(voiced))
     else:
         print cmd
         self.mTimer.cancel()
         response = self.respond(nick, cmd)
Exemple #48
0
 def do_command(self, e, cmd):
     nick = nm_to_n(e.source())
     c = self.connection
     #run through all known commands, add more here if needed
     if cmd == "disconnect":
         self.disconnect()
     elif cmd == "die":
         c.privmsg(self.channel,"I shall!!!")
         self.die()
     elif cmd == "stats":
         for chname, chobj in self.channels.items():
             c.notice(nick, "--- Channel statistics ---")
             c.notice(nick, "Channel: " + chname)
             users = chobj.users()
             users.sort()
             c.notice(nick, "Users: " + ", ".join(users))
             opers = chobj.opers()
             opers.sort()
             c.notice(nick, "Opers: " + ", ".join(opers))
             voiced = chobj.voiced()
             voiced.sort()
             c.notice(nick, "Voiced: " + ", ".join(voiced))
     else:
         #none of the commands match, pass the text to the response function defined above
         #but first sleep a little
         time.sleep(1)
         c.privmsg(self.channel,nick + ": " + responseFun(cmd))    
Exemple #49
0
 def _on_join(self, c, e):
     """[Internal]"""
     ch = e.target()
     nick = nm_to_n(e.source())
     if nick == c.get_nickname():
         self.channels[ch] = Channel()
     self.channels[ch].add_user(nick)
Exemple #50
0
	def on_nick(self, c, e):
		if self.ban_for_nick_change and not self.user_is_admin(e.source()):
			host = lookup_cache( clear_host(nm_to_h(e.source()) ))

			self.bans.append(host)
			self.write_bans_file()
			self.kill_victim(host, nm_to_n(e.source()))
Exemple #51
0
    def on_pubmsg(self, serv, ev):
        author = irclib.nm_to_n(ev.source())
        message = ev.arguments()[0].strip()
        arguments = message.split(' ')
        event_time = time.strftime('[%H:%M:%S]', time.localtime())
        record = '{0} {1}: {2}'.format(event_time, author, message)
        FILE = open(self.irc_entries, "a")
        FILE.write("{}\n".format(record))
        FILE.close()
        print(record)
        chan = ev.target()
        if author in wookie['bot_owner']:
            try:
                if ev.arguments()[0].lower() == '.restart':
                    self.restart_bot(serv, ev)
                if ev.arguments()[0].lower() == '.quit':
                    serv.disconnect()
                    if not wookie['mode']:
                        os.system(wookie['kill_bot'])
                    sys.exit(1)
            except OSError as error:
                serv.disconnect()
                print(error)
                sys.exit(1)

        if '.help' == arguments[0].lower():
            serv.privmsg(
                chan, '{0}{2}{3}Available commands:{1}{0} .help || '
                '.version || .uptime || .restart || .quit || '
                '.get <release>{1}'.format(self.BOLD, self.END, self.UNDERLINE,
                                           self.BLUE))

        if '.version' == arguments[0].lower():
            serv.privmsg(
                chan, '{0}{1}{2}{3}'.format(self.BOLD, self.PINK,
                                            network['bot_name'], self.END))

        if '.uptime' == arguments[0].lower():
            uptime_raw = round(time.time() - self.start_time)
            uptime = timedelta(seconds=uptime_raw)
            serv.privmsg(
                chan,
                '{0}{3}[UPTIME]{4} {2}{1}'.format(self.BOLD, self.END, uptime,
                                                  self.TEAL, self.BLACK))

        if '.get' == arguments[0].lower() and len(arguments) > 1:
            try:
                self.search_release(serv, ev, message, chan)
            except (HTTPError, URLError, KeyError, ValueError, TypeError,
                    AttributeError):
                serv.privmsg(
                    chan, '{0}Nothing found, sorry about this.{1}'.format(
                        self.BOLD, self.END))
                pass
            except socket.timeout:
                serv.privmsg(
                    chan, "{0}{1}[ERROR]{2} API timeout...".format(
                        self.BOLD, self.RED, self.END))
                pass
Exemple #52
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
Exemple #53
0
 def on_privnotice(self, _connection, event):
     """Handle private notices."""
     if event.source() is not None:
         source = irclib.nm_to_n(event.source())
     else:
         source = None
     msg = event.arguments()[0]
     self.log.info(unicode("-%s- %s" % (source, msg), "utf-8"))
Exemple #54
0
 def do_command(self, e, cmd):
     if cmd == "disconnect":
         self.disconnect()
     elif cmd == "die":
         self.die()
     else:
         self.connection.notice(nm_to_n(e.source()),
                                "I don't how to " + cmd)
Exemple #55
0
 def on_privmsg(self, c, e):
     nick = nm_to_n(e.source())
     if not nick == self.getBossName():
         c.privmsg(
             nick, "One does not simply PM me, " + nick + ". Only " +
             self.getBossName() + " may. I refuse to listen.")
     else:
         self.do_command(e, e.arguments()[0])
Exemple #56
0
 def on_quit(self, c, e):
     nick = nm_to_n(e.source())
     # Only write the event on channels that actually had the user in the channel
     for chan in self.channels:
         if nick in [
                 x.lstrip('~%&@+') for x in self.channels[chan].users()
         ]:
             self.write_event("quit", e, {"%chan%": chan})
Exemple #57
0
	def on_quit(self, serv, ev):
		user = irclib.nm_to_n(ev.source())
		print "Quit "+user
		if self.vf_global_mode == True:
			if user in self.players: self.players.remove(user)
			self.players_ez.remove(user)
			serv.privmsg(self.chan, u"Quelle tarlouze ce "+user)
		self.users.remove(user)
Exemple #58
0
 def on_pubmsg(self, c, e):
     a = e.arguments()[0].split(",", 1)
     print datetime.now().strftime("%d/%m/%y %H:%M:%S") + " <" + nm_to_n(
         e.source()) + "> " + e.arguments()[0]
     if len(a) > 1 and irc_lower(a[0]) == irc_lower(
             self.connection.get_nickname()):
         self.do_command(e, a[1].strip())
     return
Exemple #59
0
 def on_part(self, c, e):
     nick = nm_to_n(e.source())
     if (nick == c.get_nickname()):
         self.logger.logSelfPart(e)
         return
     self.logger.logPart(e)
     channel = e.target()
     self.doSeen(nick, channel, False)
Exemple #60
0
 def on_nick(self, c, e):
     before = nm_to_n(e.source())
     after = e.target()
     for channelName, channel in self.channels.items():
         if channel.has_user(before):
             self.logger.logNick(channelName, before, after)
             self.doSeen(before, channelName, False)
             self.doSeen(after, channelName, True)