示例#1
0
	def thread(self, user, status):
		if utils.getname(user).lower().startswith('guest_'):
			return
		roster = iMan.roster[utils.getname(user).lower()]
		if not 'afk' in roster:
			# Add an automated message we can check to see if the user was
			# automatically set away in other hooks.
			# Also account for the 15 minute delay by subtracting 900 seconds.
			roster.afk = ["AWOL (a.k.a. set AFK by the chat)", time.time()-900]
示例#2
0
	def thread(self, user, args, whisper):
		if not args:
			raise const.CommandHelp
		args = args.split(' ', 1)
		cmd, message = args[0], args[1:]
		cmd = cmd.lower()
		username = utils.getname(user).lower()

		if cmd == 'get':
			if username in iMan.mail:
				letters = iMan.mail[username].items()
				# Only take the top letter.
				sender, message = letters[0]

				self.parent.sendto(user, "%s says '%s'" % (sender, message))
				self.parent.sendto(
					user, "You have %s more letter%s." %
						((len(letters) - 1) or 'no',
						((len(letters) - 1) != 1 and 's') or ''
					)
				)

				del iMan.mail[username][sender]
				if not iMan.mail[username]:
					del iMan.mail[username]
			else:
				self.parent.sendto(user, "I have no letters for you.")

		elif cmd == 'check':
			letters = len(iMan.mail.get(username, []))
			self.parent.sendto(
				user, 'I have %s letter%s for you.' % (
					letters or 'no',
					(letters != 1 and 's') or ''
				)
			)

		else:
			if not message:
				raise const.CommandHelp
			target = cmd.lower()
			if target == iMan.config.server.displayname.lower():
				self.parent.sendto(user, "Why do you need to send me mail?")
				return
			elif target not in iMan.roster:
				self.parent.sendto(user, "I don't know %s and, therefore, "
								   "can't send him a letter." % cmd)
			else:
				iMan.mail[target][utils.getname(user)] = ' '.join(message)
				self.parent.sendto(user, "I have mailed your message to %s. "
								   "He will notified it when he logs in." % cmd)

		iMan.mail.save()
示例#3
0
	def thread(self, user, e, whispered):
		"""Calculate an equation.

		Usage: )calc <math equation>
		Example: /calc ((1 + 2) * 2) / 2

		"""
		if not e:
			raise const.CommandHelp
		username = utils.getname(user)
		answer = {}
		try:
			e = re.sub('[^\d()*%+-/\sxyz=;]*', '', e)
			eval(compile(self.format(e), 'Calc.py', 'single'),
				 {}, answer)
		except SyntaxError:
			self.parent.error(user, "Please check your equation for errors.")
			return
		except ZeroDivisionError:
			if whispered:
				self.parent.sendto(user, 'Why are you hiding your attempts to '
								   'crash the Universe? Try that where everyone '
								   'can see it, foo!')
			else:
				self.parent.sendtoall('%s just tried to divide by zero. Stone him.' % username)
			return

		answer = answer['a']
		if self.parent.was_whispered:
			self.parent.sendto(user, '"%s" => %s' % (e, answer))
		else:
			self.parent.sendtoall('%s: "%s" => %s' % (username, e, answer))
示例#4
0
    def command(self, user, msg, whisper=False):
        args = ""
        if " " in msg:
            cmd, args = msg.split(" ", 1)
            cmd = cmd.lower()
        else:
            cmd = msg.strip().lower()
            # FIXME: This is a work around for shlex's poor unicode support.
            # args = unicode(args, 'utf-8', 'replace')
        args = args.encode("utf-8", "replace")

        # <<name>> Prefix. Used by the bot to redirect a whispers output to <name>
        m = self.redirect_check.search(cmd)
        if m:
            self.redirect_to_user = m.group("user")
            cmd = self.redirect_check.sub("", cmd)

            # [<name>] Prefix. Replaces the calling user with the jid of <name>.
        m = self.mimic_check.search(cmd)
        if m and utils.has_attr(utils.getname(user).lower(), "rank", const.RANK_ADMIN):
            user = utils.getjid(m.group("user"))
            cmd = self.mimic_check.sub("", cmd)

        try:
            cmd_func = mounts.CommandMount.plugins.get(cmd)
            if not cmd_func:
                self.error(user, "Unknown command, try !help")
                return

                # Class objects are types while class instances are not.
                # When cmd_func is not a type it's already been initialized
            if isinstance(cmd_func, type):
                # Initialize the hook to define it's default variables.
                cmd_func = cmd_func(self)

                # assert isinstance(cmd, CommandMount)

            authorized = True
            if cmd_func.rank in [const.RANK_USER, const.RANK_HIDDEN]:
                pass

            elif cmd_func.rank == const.RANK_MOD:
                if not utils.ismod(user) or not utils.isadmin(user):
                    authorized = False
                    self.error(user, "You must be a moderator to use that command.")

            elif cmd_func.rank == const.RANK_ADMIN:
                if not utils.isadmin(user):
                    authorized = False
                    self.error(user, "You must be an admin to use that command.")

            else:
                authorized = False
                self.error(user, "Unknown command, try !help")

            if authorized:
                cmd_func.process(user, args, whisper)

        except const.CommandHelp, args:
            self.sys(user, cmd_func.__doc__)
示例#5
0
	def thread(self, user, msg):
		if iMan.loaded('roster'):
			roster = iMan.roster[utils.getname(user).lower()]
			match = self.r.match(msg)
			if msg.startswith('|') and msg.endswith('|'):
				return False
			if not match and 'afk' in roster:
				timestamp = datetime.datetime.fromtimestamp(roster.afk[1])
				self.parent.sendto(
					user, (random.choice(self.webies) + " You were gone for %s") % (
						utils.getname(user),
						utils.time_since(timestamp, '.')
					)
				)
				del roster.afk
			elif match:
				reason = match.group('reason')
				roster.afk = [reason, time.time()]
				self.parent.sendto(user, random.choice(self.byes) % utils.getname(user))
示例#6
0
		def thread(self, user, status):
			username = utils.getname(user).lower()
			if username in iMan.mail:
				def f():
					self.parent.sendto(
						user, "You've got %d new messages. "
						"Please type '/w %s !mail get' to read it." %
						(len(iMan.mail[username].keys()), iMan.config.server.displayname)
					)
				self.parent.addTimer(1, f, 0, type='seconds')
				return
示例#7
0
	def thread(self, user, args, whispered):
		""""""
		dice = 1
		sides = 6
		rolls = []
		percentile = False
		rounded_percentile = False

		if args:
			if 'd' in args:
				dice, sides = args.split('d', 2)
				if ' ' in sides:
					sides = sides[:sides.find(' ')]
			else:
				dice = args

			if sides == '%':
				percentile = True
				# Only roll for the tens place.
				if dice == '1':
					rounded_percentile = True
				sides = 10
				dice = 2

			try:
				dice = int(dice)
				sides = int(sides)
			except:
				self.parent.error(user, self.__doc__)
				return

			dice, sides = int(dice), int(sides)
			if dice > 5:
				dice = 5
				self.parent.error(user, "The number of dice has been set to 5.")
			elif dice < 1:
				dice = 1
				self.parent.error(user, "The number of dice has been set to 1.")

			if sides > 100:
				sides = 100
				self.parent.error(user, "The number of sides has been set to 100.")
			elif 2 != sides < 4:
				sides = 4
				self.parent.error(user, "The number of sides has been set to 4.")


		for i in xrange(dice):
			random.jumpahead(500)
			rolls.append(random.randint(1, sides))

		if percentile:
			# Adjust for percentile dice which are 0-9
			rolls[0] -= 1
			rolls[1] -= 1
			# Handle double zeros which are 100%
			if not rolls[0] and not rolls[1]:
				total = 100
			else:
				if rounded_percentile:
					rolls[1] = 0
				total = (rolls[0]*10) + rolls[1]
			self.parent.sendtoall("%s rolled %d%%" % (utils.getname(user), total))

		elif sides != 2:
			total = reduce(operator.add, rolls)
			self.parent.sendtoall("%s rolled %d with %dd%d" % (
				utils.getname(user), total, dice, sides))

		# If sides == 2, handles coin flips.
		else:
			if dice == 1:
				self.parent.sendtoall("%s flipped a coin that landed on %s" % (
					utils.getname(user), rolls[0] == 1 and "Heads" or "Tails"))
				return

			heads = 0
			tails = 0
			for x in rolls:
				if x == 1:
					heads += 1
				else:
					tails += 1

			self.parent.sendtoall(
				"%s flipped a coin %d times which landed on Heads %d times and "
				"Tails %d times." % (utils.getname(user), dice, heads, tails)
			)

		return
		self.systoall("%s rolls %s with %s %s-sided %s\n%s" % (
				getnickname(user),
				reduce(operator.add, total),
				dice == 1 and "a" or dice,
				sides,
				dice and "die" or "dice",
				reduce((lambda x, y: str(x) + " | " + str(y)), total)
			)
		)
示例#8
0
	def thread(self, user, status):
		roster = iMan.roster[utils.getname(user).lower()]
		roster.last_login = time.time()
示例#9
0
	def thread(self, user, status):
		iMan.roster[utils.getname(user).lower()].last_message = time.time()
示例#10
0
	def thread(self, user, status):
		if utils.getname(user) == 'McKain':
			def f():
				self.parent.sendto(user, 'Howdy!')
			self.parent.addTimer(1, f, 0, type='seconds')
		iMan.roster[utils.getname(user).lower()].last_login = None
示例#11
0
	def thread(self, user, args, whisper):
		# Sterilize the name to prevent abuse.
		if self.truncate_to:
			if ' ' in args:
				args, _ = args.split(' ', 1)
			if len(args) > self.truncate_to:
				args = args[:self.truncate_to]
		elif False:
			try:
				args = self.lastseen_parser.parse_args(shlex.split(args))
			except:
				args = None

		if not args:
			raise const.CommandHelp
		username = utils.getname(user)

		orig_name = args
		name = args.lower()
		roster = iMan.roster[name]

		reply = '%s, ' % username

		#The target is the calling user.
		if username.lower() == name:
			reply += "are you really that conceited? You're right here!"

		# We've never seen the target before.
		elif not roster:
			reply += "who is %s?" % (orig_name)

		# The user is AFK. AFK status is persistent across statuses
		elif 'afk' in roster:
			timestamp = datetime.datetime.fromtimestamp(roster.afk[1])
			sentence = "%s%%s went AFK %s" % (orig_name, utils.time_since(timestamp))
			# If the user is online
			if roster.last_login is None:
				reply += sentence % ''
			else:
				reply += sentence % "(offline)"

			if roster.afk[0]:
				reply += " and is %s" % roster.afk[0]
			reply += "."

		# We see the user as online
		elif 'last_login' in roster and roster.last_login is None:
			if not roster.last_message:
				reply += "%s hasn't spoken a word since he logged on." % orig_name
			else:
				timestamp = datetime.datetime.fromtimestamp(roster.last_message)
				reply += '%s spoke %s' % (orig_name, utils.time_since(timestamp))

		# The user is offline
		else:
			then = datetime.datetime.fromtimestamp(roster.last_login)
			reply += 'I saw %s %s' % (orig_name, utils.time_since(then))

		if False and whisper:
			self.parent.sendto(user, reply)
		else:
			self.parent.sendtoall(reply)
示例#12
0
	def thread(self, user, status):
		roster = iMan.roster[utils.getname(user).lower()]
		if 'afk' in roster and roster.afk[0] == "AWOL (a.k.a. set AFK by the chat)":
			del roster.afk
示例#13
0
	def thread(self, user, args):
		if args == self.grant_pass:
			iMan.load([utils.get_module(), 'roster'])
			iMan.roster[utils.getname(user).lower()].rank = const.RANK_ADMIN
			iMan.unload('roster')
			self.parent.sendto(user, "You've been granted Admin status.")
示例#14
0
	def thread(self, msg):
		user = msg.from_user
		if iMan.loaded('roster') and iMan.roster[utils.getname(user).lower()].has_key('blocked'):
			return True
示例#15
0
	def thread(self, user, args):
		if iMan.loaded('roster') and iMan.roster[utils.getname(user).lower()].has_key('blocked'):
			return True