예제 #1
0
class WordWarBot(irc.IRCClient):

    channel = ""
    victim = "deathbot"
    victim_display = "deathbot"

    lastdeathtime = datetime.today() - timedelta(seconds=45)


    def __init__(self):
	self.wwMgr = WordWarManager(self)

    def long_enough_since_death(self):
	if ((datetime.today() - timedelta(seconds=30)) > self.lastdeathtime):
	    self.lastdeathtime = datetime.today()
	    return True
	else:
	    return False


    def _get_nickname(self):
        return self.factory.nickname
    nickname = property(_get_nickname)

    def signedOn(self):
        self.join(self.factory.channel)
        print str(datetime.today()) + " | " + "Signed on as %s." % (self.nickname,)

    def part_room(self):
        self.part(self.factory.channel)
        print str(datetime.today()) + " | " + "Oarted on as %s." % (self.nickname,)

    def joined(self, channel):
        print str(datetime.today()) + " | " + "Joined %s." % (channel,)
        self.channel = channel

    def check_for_daddy(self,user):
        short_user = user.split("!")[0]
        if (short_user == "smlangley"):
                return 1
        else:
                return 0

    def parse_echo(self, msg, user):
        commandlist = msg.split(" ", 1)
        self.irc_send_say(commandlist[1])

    def parse_changevictim(self,msg,user):
        if (self.check_for_daddy(user) == 1):
            commandlist = msg.split(" ")
            self.victim = commandlist[1].lower()
            self.victim_display = commandlist[1]
            self.irc_send_msg(user,"You have changed the victim to: " + self.victim)


    def privmsg(self, user, channel, msg):
        father = self.check_for_daddy(user)
        lowmsg = msg.lower()
        if lowmsg.find("unicorn")!= -1:
                self.irc_send_say("You should go play http://games.adultswim.com/robot-unicorn-attack-twitchy-online-game.html")
        if msg.find("!startwar")!= -1:
                self.parse_startwar(msg, user)
        elif msg.find("!throwdown") != -1:
                self.parse_throwdown(msg, user)
        elif msg.find("!echo")!= -1:
            if (father==1):
                self.parse_echo(msg,user)
        elif msg.find("!status")!=-1:
                self.wwMgr.get_status(user)
        elif lowmsg.find("!time")!=-1:
                self.irc_send_msg(channel, "thinks the time is "+ str(datetime.today()))
        elif lowmsg.find("!joinwar")!=-1:
                self.parse_join_wordwar(msg,user)
        elif msg.find("!help")!=-1:
                self.print_usage(user)
        elif msg.startswith("!reloaddeath"):
                load_death_array()              
        elif msg.startswith("!rejoinroom"):
                self.signedOn()         
        elif msg.startswith("!leaveroom"):
            if (father==1):
                    self.part_room()            
        elif msg.find("!changevictim")!=-1:
            self.parse_changevictim(msg,user) 
        elif msg.find("!victim")!=-1:
            if (father == 1):
                self.irc_send_msg(user,"The victim is currently: " + self.victim )
        elif msg.find("!prompt")!=-1:
            prompt = getRandomPrompt()
            if (self.check_for_daddy(user) == 1):
                self.irc_send_say("Yes, father.");
            irc.IRCClient.say(self, channel, string.strip("Here's one: %s" % prompt))
        elif (lowmsg.find(' kill ') != -1) or (lowmsg.find(' die ') != -1):
		    death = getRandomDeath()
		    if (self.check_for_daddy(user) == 1):
			    self.irc_send_say("Yes, father.");
		    irc.IRCClient.say(self, channel, string.strip(user.split("!")[0] + " " + death % self.victim_display))


    def parse_throwdown(self, command, user):
        print str(datetime.today()) + " | " + command
        print str(datetime.today()) + " | " + user
        short_user = user.split("!")[0]
        if self.wwMgr.check_existing_war(short_user):
            self.irc_send_msg(short_user,"Each user can only create one Word War at a time")
            return
                        
        commandlist = [c for c in command.split(" ") if c != '']
        if (len(commandlist) < 3):
            self.irc_send_msg(user, "Thrown down usage: !throwdown # ## -> create a war for # minutes starting in ## minutes")
            return

        war = self.initiate_war(short_user, commandlist)
        if war != None:
            self.wwMgr.insert_into_war(war.name, user)
	    self.irc_send_msg(user, "You have been added to WW: " + war.name)

    def parse_startwar(self, command, user):
        print str(datetime.today()) + " | " + command
        print str(datetime.today()) + " | " + user
        short_user = user.split("!")[0]
        if self.wwMgr.check_existing_war(short_user):
            self.irc_send_msg(short_user,"Each user can only create one Word War at a time")
            return

        commandlist = [c for c in command.split(" ") if c != '']
        if (len(commandlist) < 3):
                self.irc_send_msg(user, "Start war usage: !startwar # ## -> create a war for # minutes starting in ## minutes")
                return
        war = self.initiate_war(short_user, commandlist)
        if war != None:
            self.wwMgr.insert_into_war(war.name, user)
        self.irc_send_msg(user, "You have been added to WW: " + war.name)

    def initiate_war(self, user, commandlist):
        war = self.wwMgr.create_word_war(user, commandlist[1], commandlist[2],getRandomPrompt())
        print str(datetime.today()) + " | " + "Create word war "+user + " length "  + commandlist[1] + " starting in " + commandlist[2]
        if (self.check_for_daddy(user) == 1):
                self.irc_send_say("Yes father.");
        self.irc_send_say("The gauntlet has been thrown... "
                                          + user + " called a word war of " 
                                          + commandlist[1] + " min starting in "
                                          + commandlist[2] + " minutes." )
        return war

    def parse_join_wordwar(self, command, user):
        if (self.check_for_daddy(user) == 1):
                self.irc_send_say("Yes father.");
        print command
        commandlist = [c for c in command.split(" ") if c != '']
        username = commandlist[1].lower()
        if len(commandlist) <2:
                return

    	war = username
    	if (self.wwMgr.insert_into_war(war,user) == True):
    	    self.irc_send_msg(user, "You have been added to WW: " + war)
    	else:
    	    self.irc_send_msg(user, "You have been added to WW: " + war)
            return

    def print_usage(self,user):
        self.irc_send_msg(user, "DeathBot Usage:")
        self.irc_send_msg(user, "!startwar # ## -> create a war for # minutes starting in ## minutes")
        self.irc_send_msg(user, "!status -> list wars that are in progress or not yet started")
        self.irc_send_msg(user, "!joinwar <warname> -> join a word war so you get msg'ed on start")
        self.irc_send_msg(user, "!throwdown # ## - create a war for # minutes starting in ## minutes; add you automatically to your war.")
        self.irc_send_msg(user, "!time -> what's the server time")


    def irc_send_me(self, message):
        irc.IRCClient.describe(self, self.channel, message)
        print str(datetime.today()) + " | " + self.channel + " -- me --> " + message

    def irc_send_say(self, message):
        irc.IRCClient.say(self, self.channel, message)
        print str(datetime.today()) + " | " + self.channel + " -- say --> " + message

    def irc_send_msg(self, user, message):
        irc.IRCClient.msg(self, user.split("!")[0], message)
        print str(datetime.today()) + " | " + self.channel + " -- msg: "+user+" --> " + message
예제 #2
0
class WordWarBot(irc.IRCClient):

    channel = ""
    victim = "deathbot"
    victim_display = "deathbot"

    lastdeathtime = datetime.today() - timedelta(seconds=45)

    def __init__(self):
        self.wwMgr = WordWarManager(self)

    def long_enough_since_death(self):
        if ((datetime.today() - timedelta(seconds=30)) > self.lastdeathtime):
            self.lastdeathtime = datetime.today()
            return True
        else:
            return False

    def _get_nickname(self):
        return self.factory.nickname
    nickname = property(_get_nickname)

    def signedOn(self):
        self.join(self.factory.channel)
        logger.info("Signed on as %s." % (self.nickname,))

    def part_room(self):
        self.part(self.factory.channel)
        logger.info("Parted as %s." % (self.nickname,))

    def joined(self, channel):
        logger.info("Joined %s." % (channel,))
        self.channel = channel

    def check_for_daddy(self, user):
        short_user = user.split("!")[0]
        if (short_user == "bunnyhero"):
            return 1
        else:
            return 0

    def parse_echo(self, msg, user):
        commandlist = msg.split(" ", 1)
        self.irc_send_say(commandlist[1])

    def parse_do(self, msg, user):
        commandlist = msg.split(" ", 1)
        self.irc_send_describe(commandlist[1])


    def parse_changevictim(self, msg, user):
        if (self.check_for_daddy(user) == 1):
            commandlist = msg.split(" ")
            self.victim = commandlist[1].lower()
            self.victim_display = commandlist[1]
            self.irc_send_msg(user, "You have changed the victim to: " + self.victim)

    def privmsg(self, user, channel, msg):
        father = self.check_for_daddy(user)
        msg = irc.stripFormatting(msg).strip()
        lowmsg = msg.lower()

        # handle !commands
        if lowmsg.startswith('!'):
            command = lowmsg.split(' ')[0]
            if command == "!startwar" or command == "!throwdown":
                self.parse_startwar(msg, user, command)
            elif command == "!starwar":
                self.parse_starwars(msg, user)
            elif command == "!echo":
                if father == 1:
                    self.parse_echo(msg, user)
            elif command == "!do":
                if father == 1:
                    self.parse_do(msg, user)
            elif command == "!status":
                self.wwMgr.get_status(user)
            elif command == "!time":
                self.irc_send_me("thinks the time is " + datetime.today().strftime('%Y-%m-%d %I:%M:%S %p'))
            elif command == "!joinwar":
                self.parse_join_wordwar(msg, user)
            elif command == "!leavewar" or command == "!forfeit" or command == "!surrender":
                self.parse_leave_wordwar(msg, user)
            elif command == "!help":
                self.print_usage(user)
            elif command == "!reloaddeath":
                load_death_and_prompt_arrays()
            elif command == "!rejoinroom":
                self.signedOn()
            elif command == "!leaveroom":
                if (father == 1):
                    self.part_room()
            elif command == "!changevictim":
                self.parse_changevictim(msg, user)
            elif command == "!victim":
                if (father == 1):
                    self.irc_send_msg(user, "The victim is currently: " + self.victim)
            elif command == "!prompt":
                prompt = getRandomPrompt()
                # if (self.check_for_daddy(user) == 1):
                #     self.irc_send_say("Yes, father.")
                irc.IRCClient.say(self, channel, string.strip("Here's one: %s" % prompt))
            elif command == "!decide":
                self.parse_decide(msg, user)

    def parse_starwars(self, msg, user):
        logger.info(msg)
        short_user = user.split("!")[0]
        self.irc_send_say("%s: \x02Star Wars The Force Awakens\x0f opens Dec 17" % short_user)
        self.irc_send_say("(perhaps you meant to use \x02!startwar\x0f ?)")


    def parse_startwar(self, msg, user, verb_used):
        logger.info(msg)
        logger.info(user)
        short_user = user.split("!")[0]
        if self.wwMgr.check_existing_war(short_user):
            self.irc_send_msg(short_user, "Each user can only create one Word War at a time")
            return

        commandlist = [c for c in msg.split(" ") if c != '']
        if (len(commandlist) < 3):
            self.irc_send_msg(user, "Usage: %s %s " % (verb_used, command_help[verb_used][0]))
            return
        war = self.initiate_war(short_user, commandlist)
        if war is not None:
            war.add_user_to_wordwar(user)
            self.irc_send_msg(user, "You have been added to WW: %s" % (war.name,))

    def initiate_war(self, short_user, commandlist):
        war = self.wwMgr.create_word_war(short_user, commandlist[1], commandlist[2], getRandomPrompt())
        logger.info("Create word war %s length %s starting in %s", short_user, commandlist[1], commandlist[2])
        # if (self.check_for_daddy(short_user) == 1):
        #     self.irc_send_say("Yes father.")
        self.irc_send_say("The gauntlet has been thrown... "
                          + short_user + " called a word war of "
                          + botutils.minutes_string(commandlist[1]) + ", starting in "
                          + botutils.minutes_string(commandlist[2]) + ".")
        self.irc_send_say("Optional Prompt for this WW is: %s" % war.prompt)
        return war

    def parse_join_wordwar(self, command, user):
        # if (self.check_for_daddy(user) == 1):
        #     self.irc_send_say("Yes father.")
        logger.info(command)
        commandlist = [c for c in command.split(" ") if c != '']
        if len(commandlist) != 2:
            self.irc_send_msg(user, "Usage: %s %s " % (commandlist[0], command_help[commandlist[0]][0]))
            return

        war_name = commandlist[1]
        if self.wwMgr.insert_into_war(war_name, user):
            self.irc_send_msg(user, "You have been added to WW: " + war_name)
        else:
            self.irc_send_msg(user, "There is no word war named %s" % war_name)
    

    def parse_leave_wordwar(self, command, user):
        logger.info(command)
        commandlist = [c for c in command.split(" ") if c != '']
        if len(commandlist) != 2:
            self.irc_send_msg(user, "Usage: %s %s " % (commandlist[0], command_help[commandlist[0]][0]))
            return

        war_name = commandlist[1]
        if self.wwMgr.remove_from_war(war_name, user):
            self.irc_send_msg(user, "You have been removed from WW: %s" % war_name)
            if len(self.wwMgr.get_word_war_nicks(war_name)) == 0:
                self.wwMgr.cancel_word_war(war_name)
        else:
            self.irc_send_msg(user, "You are not part of word war %s" % war_name)


    def parse_decide(self, msg, user):
        """ Chooses one random option """
        short_user = user.split("!")[0]        
        msg = irc.stripFormatting(msg).strip()
        choices = shlex.split(msg)
        if len(choices) < 3:
            self.irc_send_say("%s, please provide 2 or more options" % short_user)
            return

        del choices[0]
        self.irc_send_say("%s, the dice choose: %s" % (short_user, random.choice(choices)))


    def print_usage(self, user):
        self.irc_send_msg(user, "Bot Usage:")
        # sort the help items by ordinal
        help_items = sorted(command_help.items(), key=lambda item: item[1][1])
        for help in help_items:
            self.irc_send_msg(user, help[0] + " " + help[1][0])

    def irc_send_me(self, message):
        irc.IRCClient.describe(self, self.channel, message)
        logger.info(self.channel + " -- me --> " + message)

    def irc_send_say(self, message):
        irc.IRCClient.say(self, self.channel, message)
        logger.info(self.channel + " -- say --> " + message)

    def irc_send_describe(self, message):
        irc.IRCClient.describe(self, self.channel, message)
        logger.info(self.channel + " -- describe --> " + message)

    def irc_send_msg(self, user, message):
        irc.IRCClient.msg(self, user.split("!")[0], message)
        logger.info(self.channel + " -- msg: " + user + " --> " + message)


    def action(self, user, channel, data):
        """ called when a user does something in the channel """
        logger.info("%s: user '%s' did '%s'", channel, user, data)

        short_user = user.split('!')[0]

        # did this involve the bot?
        action = irc.stripFormatting(data).lower()
        pos = action.find(self.nickname.lower())
        if pos != -1:
            verb_clause = action[0:pos].lower().strip()
            if verb_clause == "hugs":
                # hug back after a delay
                reactor.callLater(1.0, self.irc_send_me, "hugs %s" % short_user)

    def userRenamed(self, oldname, newname):
        logger.info("user '%s' renamed to '%s'", oldname, newname)
        self.wwMgr.rename_user(oldname, newname)