Exemple #1
0
	def handler(self, **args):
		"""votes on a poll."""
		import database

		from irclib import Event
		from irclib import nm_to_h, nm_to_u
		target=args["channel"]
		if args["type"] == "privmsg":
			from irclib import nm_to_n
			target=nm_to_n(args["source"])
	
		poll_num = args["text"].split()[2]
		option_key = " ".join(args["text"].split()[3:])
		#first we check to make sure the requested poll exists.
		if database.doSQL("select count(poll_num) from poll where poll_num =" +poll_num)[0][0] == 0:
			return Event("privmsg", "", target, [ "No such poll." ])
	
		#now we check to make sure the user hasn't voted in that poll
		checkmask = "%!" + nm_to_u(args["source"]) + "@%" + nm_to_h(args["source"])[nm_to_h(args["source"]).find("."):]
		if database.doSQL("select count(option_key) from poll_votes where poll_num =" + poll_num + " and voter_nickmask like '" + checkmask + "'")[0][0] != 0:
			return Event("privmsg", "", target, [ "You already voted in that poll." ])
	
		#next we check to make sure the poll option exists.
		option_key = self.sqlEscape(option_key)
		if database.doSQL("select count(option_key) from poll_options where poll_num =" + poll_num + " and option_key = '" + option_key + "'")[0][0] == 0:
			return Event("privmsg", "", target, [ "No such poll option." ])
	
		# register the vote.
		database.doSQL("insert into poll_votes values('" + args["source"] + "', '" + option_key + "', " + poll_num + ")")
	
		return Event("privmsg", "", target, [ "Vote registered." ])
Exemple #2
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 #3
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 #4
0
	def on_privmsg(self, serv, ev) :
		source = irclib.nm_to_n(ev.source())
		message = ev.arguments()[0]
		user = irclib.nm_to_h(ev.source())
		if user in self._config['admins'] :
			for c in self.commands :
				c.command.run(self, serv, ev)
Exemple #5
0
    def on_virt_register(self, c, e, nick, args):
        if not self.userBase[nick]:
            c.privmsg(nick, 'You\'ve already got cookies.')
            return

        if len(args) < 4:
            c.privmsg(nick, "Can't process request, 3 arguments needed.")
            c.privmsg(nick, "usage: REGISTER <name> <password> <class> [<email>]")
            return -1

        charName, charPassword, charClass = args[1], args[2], args[3]
        if len(args) is 5:
            email = args[4]
        else:
            email = None
        gender = 0

        template = {'character_name': charName,
                    'character_class': charClass,
                    'nickname': nick,
                    'password': charPassword,
                    'email': email,
                    'gender': gender,
                    'hostname': nm_to_h(e.source())}

        answer = self.userBase[nick].createNew(self.users, **template)
        if answer is 1:
            c.privmsg(nick, "You've been successfully registred. You can now login.")
            c.privmsg(self._gameChannel, "Welcome to %s, the %s" % (charName,
                                                                    charClass))
        else:
            c.privmsg(nick, "A problem occured resulting of your character "\
                              "not being registred")
Exemple #6
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 #7
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 #8
0
 def on_privmsg(self, irc, e):
     try:
         nick = nm_to_n(e.source())
         host = nm_to_h(e.source())
         msg = unicode(e.arguments()[0], "utf-8")
     except Exception, e:
         print(str(e))
         return
Exemple #9
0
 def on_pubmsg(self, c, e):
     comment = e.arguments()[0]
     nick = nm_to_n(e.source())
     host = nm_to_h(e.source())
     if irc_lower(comment).startswith(irc_lower(self.connection.get_nickname()+": openid=")):
         try:
             utils.addOidUser(nick, comment[len(self.connection.get_nickname()+": openid="):])
             self.connection.privmsg(e.target(), "Ok")
         except ValueError, LookupError:
             self.connection.privmsg(e.target(), "Invalid OpenID")
Exemple #10
0
		def on_quit(self, c, e):
			source_name = nm_to_n(e.source()).lower()
			source_host = nm_to_h(e.source())
			
			if source_name in self.ignore:
				return
			
			for module in self.modules.values():
				try:
					module.handle_on_quit(source_name, source_host, None)
				except Exception, e:
					traceback.print_exc(file=sys.stdout)
Exemple #11
0
    def on_quit(self, c, e):
        source_name = nm_to_n(e.source()).lower()
        source_host = nm_to_h(e.source())

        if source_name in self.ignore:
            return

        for module in self.modules.values():
            try:
                module.handle_on_quit(source_name, source_host, None)
            except Exception, e:
                traceback.print_exc(file=sys.stdout)
Exemple #12
0
		def on_privmsg(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].decode("UTF8")
			self.last_message_sender = source_name
			
			for module in self.modules.values():
				try:
					module.handle_private_message(source_name, source_host, message)
				except Exception, e:
					traceback.print_exc(file=sys.stdout)
Exemple #13
0
    def on_action(self, c, e):
        source_name = nm_to_n(e.source()).lower()
        source_host = nm_to_h(e.source())
        message = e.arguments()[0].decode("UTF8")

        if source_name in self.ignore:
            return

        for module in self.modules.values():
            try:
                module.handle_action(source_name, source_host, message)
            except Exception, e:
                traceback.print_exc(file=sys.stdout)
Exemple #14
0
		def on_action(self, c, e):
			source_name = nm_to_n(e.source()).lower()
			source_host = nm_to_h(e.source())
			message = e.arguments()[0].decode("UTF8")
			
			if source_name in self.ignore:
				return

			for module in self.modules.values():
				try:
					module.handle_action(source_name, source_host, message)
				except Exception, e:
					traceback.print_exc(file=sys.stdout)
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_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 #17
0
    def traite_event(self, infos):
        self.check_time()

        # refresh actual friend
        self.refresh_friends()

        # Récupère l'auteur
        self.auteur = {
            'fn': infos.source(),  # fullname  ([email protected])
            'f': self.nm_to_fn(infos.source()),  # full      ([email protected])
            'm': nm_to_h(infos.source()),  # mask      (mclose.eu)
            'n': nm_to_n(infos.source())  # nickname  (rinsa)
        }

        self.current_channel = infos.target()
        self.users = [pseudo.lower() for pseudo in self.channels[self.current_channel].users()]
Exemple #18
0
    def on_privmsg(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].decode("UTF8")

        if source_name in self.ignore:
            return

        self.last_message_sender = source_name

        for module in self.modules.values():
            try:
                module.handle_private_message(source_name, source_host,
                                              message)
            except Exception, e:
                traceback.print_exc(file=sys.stdout)
Exemple #19
0
 def handler(self, **args):
     """A dummy handler we used for testing -- this is the first handler we wrote"""
     from irclib import nm_to_h, nm_to_n, Event
     print "someone beeped!"
     result = [
         Event("internal", "send_raw", "", [
             "send_raw",
             "mode %s +b *!*@%s" %
             (args["channel"], nm_to_h(args["source"]))
         ]),
         Event("internal", "send_raw", "", [
             "send_raw",
             "kick %s %s :don't beep." %
             (args["channel"], nm_to_n(args["source"]))
         ])
     ]
     return result
Exemple #20
0
 def on_join(self,c,e):
     """
     Handles the servers JOIN messages
     
     Here the bot eventually welcomes a new user (but not to himself)
     
     And the bot queries the database for getting the highest mode for
     the new user and applies it
     """
     nick = nm_to_n(e.source())
     host = nm_to_h(e.source())
     channel = e.target()
     if DEBUG: print nick + " joined"
     
     if nick != c.get_nickname():
         #c.privmsg(channel,"Hello %s" % nick)
         level = dbstuff.getLevel(channel,host)
         if DEBUG: print("level: %s on %s in %s has %s" % (nick, host, channel, level))
         if (level == "v") or (level == "o"):
             c.mode(channel,"+%s %s" % (level,nick))
Exemple #21
0
    def on_pubmsg(self, c, eventlist, ispubmsg=True):
        arg = eventlist.arguments()[0]

        nick = irclib.nm_to_n(eventlist.source())
        user = irclib.nm_to_u(eventlist.source())
        host = irclib.nm_to_h(eventlist.source())

        if arg[0] == self.cmdchar:
            cmd = arg[1:].split(' ')[0]

            info = {
                    "nick": nick,
                    "user": user,
                    "host": host,
                    "pubmsg": ispubmsg,
                    "target": eventlist.target(),
                    "source": eventlist.source(),
                    "args": arg[1:].split(' ')[1:]
                    }

            self.builtins.get(cmd, self.dispatch)(info)

        elif arg[0] == self.factchar:
            info = {
                    "nick": nick,
                    "user": user,
                    "host": host,
                    "pubmsg": ispubmsg,
                    "target": eventlist.target(),
                    "source": eventlist.source(),
                    "factoid": arg[1:].split(' ')[0],
                    "args": arg[1:].split(' ')[1:]
                    }

            self.do_factoid_lookup(info)

        #update the seen database
        seen = open("Seen.db", "r")

        lines = []
        updated = False

        for line in seen.read().split('\n'):
            parsed = line.split(',')

            if parsed[0] == eventlist.target():
                if parsed[1] == nick:
                    t = datetime.datetime.now()

                    nline = eventlist.target() + "," + nick + "," + \
                    str(time.mktime(t.timetuple()) + 1e-6*t.microsecond) + "," + "<" \
                    + nick + "> " + arg

                    updated = True
                    lines.append(nline)
                    break

            lines.append(line)

        if updated is False:
            #add a new line
            t = datetime.datetime.now()
            nline = eventlist.target() + "," + nick + "," + str(time.mktime(t.timetuple()) +
                    1e-6*t.microsecond) + "," + "<" + nick + "> " + arg

            lines.append(nline)

        seen.close()

        #Yes this is not the most efficient way to do this by far, but
        #everything is in memory so I defy someone to come up with a way that
        #is significantly faster in practice
        seen = open("Seen.db", "w")

        for line in lines:
            seen.write(line + "\n")
        seen.close()
Exemple #22
0
	def on_pubmsg(self, c, e):
		from_nick = nm_to_n(e.source())
		host = nm_to_h(e.source())

		msg = e.arguments()[0]

		if host.endswith('users.quakenet.org'):
			hosto = None
		else:
			hosto = self.get_host_o(gethostbyname_cached(clear_host(host)))
			hosto.add_message(msg)
		
		if msg.startswith('!testme'):
			self.kill_victim(e.source())
			return

		if msg.startswith('!writedb'):
			self.write_hosts_file()
			return

		if msg.startswith('!dumpdb'):
			print self.hosts
			return

		if msg.startswith('!notbot '):
			try:
				msg = msg[8:].strip()

				if not msg in self.hosts.keys():
					return

				hosto = self.get_host_o(msg)

				self.msg(self.channel, '--- [ ADDED %s TO EXCEPTIONS ]' % ip)

				hosto.exception = True
				self.write_hosts_file()
			except:
				pass
			return

		if msg.startswith('!isbot '):
			try:
				msg = msg[7:].strip()

				if not msg in self.hosts.keys():
					return

				hosto = self.get_host_o(msg)

				self.msg(self.channel, '--- [ REMOVED FROM EXCEPTIONS ]')

				hosto.exception = False
				self.write_hosts_file()
			except:
				pass
			return

		if msg.startswith('!ban '):
			if not self.user_is_admin(e.source()):
				return

			try:
				msg = msg[5:].strip()

				if not msg in self.hosts.keys():
					return

				hosto = self.get_host_o(msg)

				self.msg(self.channel, '--- [ IP %s ADDED TO BANLIST ]' % ip)

				hosto.banned = True
				self.write_hosts_file()
			except:
				pass
			return

		if msg.startswith('!unban '):
			if not self.user_is_admin(e.source()):
				return

			try:
				msg = msg[7:].strip()

				if not msg in self.hosts.keys():
					return

				hosto = self.get_host_o(msg)

				self.msg(self.channel, '--- [ REMOVED FROM BAN LIST ]')
				self.queue.add(self.connection.mode, (self.channel, '-b %s' % (msg)) )

				hosto.banned = False
				self.write_hosts_file()
			except:
				pass
			return

		if msg.startswith('!banfornickchange'):
			if not self.user_is_admin(e.source()):
				return

			try:
				self.ban_for_nick_change = True

				self.msg(self.channel, '--- [ DO NOT CHANGE YOUR NAME OR YOU WILL GET BANNED ]')
			except:
				pass
			return

		if msg.startswith('!dontbanfornickchange'):
			if not self.user_is_admin(e.source()):
				return

			try:
				self.ban_for_nick_change = False

				self.msg(self.channel, '--- [ NOW YOU CAN CHANGE YOUR NAME FREELY ]')
			except:
				pass
			return

		if msg.startswith('!bans'):

			# TODO: this could be written in one line ;)
			banlist = []
			for host, hostobj in self.hosts.items():
				if hostobj.banned:
					banlist.append(host)

			self.msg(self.channel, '--- [ CURRENT BAN LIST: %s ]' % (', '.join(banlist)))
			self.msg(self.channel, '--- [ USE !unban IP remove from ban list ]')
			return

		if msg.startswith('!nobotlist'):

			# TODO: this could be written in one line ;)
			exceptions = []
			for host, hostobj in self.hosts.items():
				if hostobj.exception:
					exceptions.append(host)

			self.msg(self.channel, '--- [ CURRENT EXCEPTION LIST: %s ]' % (', '.join(exceptions)))
			self.msg(self.channel, '--- [ USE !notbot IP or !isbot IP to add or remove from exception list ]')
Exemple #23
0
 def on_privmsg(self, c, e):
     nick = nm_to_n(e.source())
     host = nm_to_h(e.source())
     said = e.arguments()[0]
     print host
Exemple #24
0
	def handler(self, **args):
		"""A dummy handler we used for testing -- this is the first handler we wrote"""
		from irclib import nm_to_h, nm_to_n, Event
		print "someone beeped!"
		result = [ 
		Event("internal", "send_raw", "", ["send_raw", "mode %s +b *!*@%s" % (args["channel"], nm_to_h(args["source"]) ) ] )  , 
		Event("internal", "send_raw", "", ["send_raw", "kick %s %s :don't beep." % (args["channel"], nm_to_n(args["source"]))]) 
		]
		return result
Exemple #25
0
 def on_privmsg(self, c, e):
     nick = nm_to_n(e.source())
     host = nm_to_h(e.source())
     said = e.arguments()[0]
     print host