Ejemplo n.º 1
0
    def privmsg(self, user, channel, msg):
        """This will get called when the bot receives a message."""
        user = user.split('!', 1)[0]
        
        #self.mode("#wrentest2", True, "c");
        if msg == "modes?":
            def modesCallback(prefix, command, params):
                if prefix == "RPL_CHANNELMODEIS":
                    self.msg(channel, params[2])
                    return True
                elif prefix == "RPL_UMODEIS":
                    self.msg(channel, params[1])
                    return True
                return False
                #self.msg(channel, "The mode for %s is %s" % (rplChannel,rplModes))
                #return True
            self.addCallback(modesCallback)
            self.sendLine("MODE %s" % channel)

        # Check to see if they're sending me a private message
        # TODO: This should be cleaned up to be less confusing in terms of channel vs user
        if channel == self.nickname:
			channel = user
        
        CommandHandler.handleCommand(self, user, channel, msg)
        #print "Handlers:", self.handlers
        for handler in self.handlers:
            #print handler, dir(handler)
            if "privmsg" in dir(self.handlers[handler]):
                self.handlers[handler].privmsg(self, user, channel, msg)
Ejemplo n.º 2
0
def on_touch_up(touch):
    CommandHandler.execute(Command("Mouse release","Release the mouse button","leftrelease " + str(touch.x) + " " + str(touch.y)));
    # touch is over, display informations, and check if it matches some
    # known gesture.
    g = simplegesture(
            '',
            zip(touch.ud['line'].points[::2], touch.ud['line'].points[1::2])
            )
    # print the gesture representation, you can use that to add
    # gestures to my_gestures.py
    #print "gesture representation:", gdb.gesture_to_str(g)

    gesture = OwnGesture.Gesture("name", False, gdb.gesture_to_str(g))

    if len(EventLoop.touches) < 2:
        global V2SWIPE_REF
        global H2SWIPE_REF
        global ROTATE_REF
        global PINCH_REF
        #Clear multi-touch reference points
        V2SWIPE_REF = []
        H2SWIPE_REF = []
        ROTATE_REF = []
        PINCH_REF = []
    
    return gesture    #TODO Return actual gesture object
Ejemplo n.º 3
0
    def privmsg(self, user, channel, msg):
        """This will get called when the bot receives a message."""
        user = user.split('!', 1)[0]

        #self.mode("#wrentest2", True, "c");
        if msg == "modes?":

            def modesCallback(prefix, command, params):
                if prefix == "RPL_CHANNELMODEIS":
                    self.msg(channel, params[2])
                    return True
                elif prefix == "RPL_UMODEIS":
                    self.msg(channel, params[1])
                    return True
                return False
                #self.msg(channel, "The mode for %s is %s" % (rplChannel,rplModes))
                #return True

            self.addCallback(modesCallback)
            self.sendLine("MODE %s" % channel)

        # Check to see if they're sending me a private message
        # TODO: This should be cleaned up to be less confusing in terms of channel vs user
        if channel == self.nickname:
            channel = user

        CommandHandler.handleCommand(self, user, channel, msg)
        #print "Handlers:", self.handlers
        for handler in self.handlers:
            #print handler, dir(handler)
            if "privmsg" in dir(self.handlers[handler]):
                self.handlers[handler].privmsg(self, user, channel, msg)
Ejemplo n.º 4
0
def on_touch_move(touch):
    # store points of the touch movement
    CommandHandler.execute(Command("Mouse drag","Move the mouse cursor","positionmouse " + str(touch.x) + " " + str(touch.y)));

    try:
        touch.ud['line'].points += [touch.x, touch.y]
    except (KeyError), e:
        pass
Ejemplo n.º 5
0
def handle_incoming_messages():
    data = request.json
    try:
    	sender = data['entry'][0]['messaging'][0]['sender']['id']
    	message = data['entry'][0]['messaging'][0]['message']['text']
    except:
    	pass
    if 'message' in locals():
        CommandHandler.process(sender, message)
    return "ok"
Ejemplo n.º 6
0
def main():
    global slack_client

    READ_WEBSOCKET_DELAY = 1  # 1 second delay between reading from firehose
    Competitors.load_competitors()
    if slack_client.rtm_connect():
        print("Smashbot connected and running!")
        CommandHandler.init()

        if sys.argv[-1] == "tfile":
            tfile = open("entry.txt", 'r+')
            stuff = tfile.read().split("\n")
            channel = stuff[4]
            user = "******"  # jackson lol
            print(stuff)
            CommandHandler.player1 = stuff[0]
            CommandHandler.player2 = stuff[1]
            CommandHandler.score1 = int(stuff[2])
            CommandHandler.score2 = int(stuff[3])
            CommandHandler.pending = True
            command = "match-confirm no-print"
            tfile.truncate()
            tfile.close()
            print("about to run")
            handle_command(command, channel, user)
        elif sys.argv[-1] == "addfile":
            tfile = open("entry.txt", 'r+')
            stuff = tfile.read().split("\n")
            channel = stuff[2]
            user = "******"  # also jackson.
            print(stuff)
            command = "add-competitor " + stuff[0] + " " + stuff[
                1] + " no-print"
            tfile.truncate()
            tfile.close()
            handle_command(command, channel, user)
        elif sys.argv[-1] == "cancelfile":
            tfile = open("entry.txt", 'r+')
            stuff = tfile.read().split("\n")
            channel = stuff[0]
            user = "******"
            command = "match-cancel no-print"
            print(stuff)
            tfile.truncate()
            tfile.close()
            handle_command(command, channel, user)

        while True:
            command, channel, user = parse_slack_output(
                slack_client.rtm_read())
            if command and channel:
                handle_command(command, channel, user)
            time.sleep(READ_WEBSOCKET_DELAY)
    else:
        print("Connection failed. Invalid Slack token or bot ID?")
Ejemplo n.º 7
0
 def run(self):
     self.csock.connect(("localhost",25566))
     p = self.recivePack()
     print("recived: ",p, CommandHandler.validDict(CommandHandler.getAsDict(p)))
     time.sleep(1)
     while True:
         p = self.recivePack()
         if (p is b''):
             break
         print("recived: ",p, CommandHandler.validDict(CommandHandler.getAsDict(p)))
     print("done")
Ejemplo n.º 8
0
    def saveCroppedImage(self):
        Logger.info("Saving cropped image")

        currentImage = self.imageHandler.readImage(self.rawImagePath)
        if CommandHandler.areBoundsSet():
            bounds = CommandHandler.getBounds()
            croppedImage = self.imageHandler.cropAndRotateRectangleInImage(
                currentImage, bounds)
        else:
            bounds = self.getBoundingRectForTable(currentImage)
            croppedImage = self.imageHandler.cropImageByBoundingRect(
                currentImage, bounds)

        cv.imwrite(self.croppedImagePath, croppedImage)
Ejemplo n.º 9
0
    def c_handler(self, *arg, **karg):
        def _c_handler(bot, update, args=None):
            message = ''
            if (args != None):
                message = ' '.join(args)
            reply = self.handler(message=message)
            if reply is None:
                return
            if isinstance(reply, (str, unicode)):
                update.effective_message.reply_text(reply)
            else:
                try:
                    reply_markup = _generateMenu(reply[sadDec._MENU_INDEX_])
                    update.effective_message.reply_text(
                        reply[sadDec._MESSAGE_INDEX_],
                        reply_markup=reply_markup)
                except IndexError:
                    logging.error("Bad menu formatting")

        _newCommandHandler = CommandHandler._Command(
            _c_handler,
            funcName=self.handler.funcName,
            passArgs=True,
            description=self.handler.description)
        return _newCommandHandler
Ejemplo n.º 10
0
 def run(self):
     self.running = True
     while self.running:
         print("do random dict")
         t = [random.randint(128,255),random.randint(0,255),random.randint(0,255)]
         self.parent.dict = CommandHandler.getAsDict(t)
         time.sleep(2)
Ejemplo n.º 11
0
def handle_incoming_messages():
    data = request.json
    try:
        sender = data['entry'][0]['messaging'][0]['sender']['id']
        message = data['entry'][0]['messaging'][0]['message']['text'].decode('UTF-8')
    except:
    	pass
    try:
        postback = data['entry'][0]['messaging'][0]['postback']['payload']
    except:
        pass
    if 'message' in locals():
        CommandHandler.message(sender, message)
    if 'postback' in locals():
        CommandHandler.postback(sender, postback)
    return "ok"
Ejemplo n.º 12
0
 def setup_bot(self):
     """
     Setup routine for new bot. Does the following things:
         1. Select virtual server specified by self.sid
         2. Set bot nickname to the Name specified by self.bot_name
         3. Move the bot to the channel specified by self.default_channel
         4. Register command and event handlers
     :return:
     """
     try:
         self.ts3conn.use(sid=self.sid)
     except ts3.TS3Connection.TS3QueryException:
         self.logger.exception("Error on use SID")
         exit()
     try:
         self.channel = self.get_channel_id(self.default_channel)
         self.ts3conn.clientupdate(["client_nickname=" + self.bot_name])
         self.ts3conn.clientmove(self.channel,
                                 int(self.ts3conn.whoami()["client_id"]))
     except ts3.TS3Connection.TS3QueryException:
         self.logger.exception("Error on setting up client")
         self.ts3conn.quit()
         return
     self.command_handler = CommandHandler.CommandHandler(self.ts3conn)
     self.event_handler = EventHandler.EventHandler(
         ts3conn=self.ts3conn, command_handler=self.command_handler)
     try:
         self.ts3conn.register_for_server_events(
             self.event_handler.on_event)
         self.ts3conn.register_for_private_messages(
             self.event_handler.on_event)
     except ts3.TS3Connection.TS3QueryException:
         self.logger.exception("Error on registering for events.")
         exit()
Ejemplo n.º 13
0
 def printCommand(self):
     tdict = self.dict
     if tdict is not self.oldDict:
         print("----------------------")
         for k in tdict:
             print(k, tdict[k])
         print(CommandHandler.getAsByteArray(tdict))
     self.oldDict = tdict
Ejemplo n.º 14
0
 def privmsg(self, client, user, channel, msg):
     comm = ch.parseCommand(client.nickname, msg)
     if comm:
         if comm["command"] == "herp":
             client.msg(channel, "derp")
     
     elif (re.search("what day is it\?", msg)):
         client.msg(channel, whatDay())
Ejemplo n.º 15
0
    def areImagesEqual(self, imageA, imageB):
        self.equalityThreshold = CommandHandler.getSensitivity()

        grayA = self.getGrayscale(imageA)
        grayB = self.getGrayscale(imageB)

        score = self.calculateEqualityScore(grayA, grayB)
        ScoreKeeper.score = score

        return score > (1 - self.equalityThreshold)
Ejemplo n.º 16
0
 def sendCommand(self,dir,speed):
     dict = CommandHandler.blankDict()
     if  (dir <= 0):
         dict["steering_direction"] = 0
         dict["steering_position"] = -dir
     else:
         dict["steering_direction"] = 1
         dict["steering_position"] = dir
     if (speed <= 0):
         dict["motor_direction"] = 0
         dict["motor_speed"] = -speed
     else:
         dict["motor_direction"] = 1
         dict["motor_speed"] = speed
     dict["time"] = int(time.time())
     commandArray = CommandHandler.getAsByteArray(dict)
     print("sending command")
     print("----------------------")
     for k in dict:
         print(k, dict[k])
     print(commandArray)
     self.sock.sendPack(commandArray)
Ejemplo n.º 17
0
def on_touch_down(touch):
    #start collecting points in touch.ud
    CommandHandler.execute(Command("Mouse left click","Click the left mouse button","leftpress " + str(touch.x) + " " + str(touch.y)));
    userdata = touch.ud
    userdata['line'] = Line(points=(touch.x, touch.y))
    
    #The moment you have two touch points: use their locations as references.
    if len(EventLoop.touches) == 2:
        global V2SWIPE_REF
        global H2SWIPE_REF
        global ROTATE_REF
        global PINCH_REF
        global GTHRESHOLD
        global GTHRESHOLD2

        t = EventLoop.touches
        V2SWIPE_REF = [(t[0].x,t[0].y),(t[1].x,t[1].y)]
        H2SWIPE_REF = [(t[0].x,t[0].y),(t[1].x,t[1].y)]
        ROTATE_REF = [(t[0].x,t[0].y),(t[1].x,t[1].y)]
        PINCH_REF = [(t[0].x,t[0].y),(t[1].x,t[1].y)]
    
    return None    #TODO Return actual gesture object
Ejemplo n.º 18
0
 def setup_bot(self):
     """
     Setup routine for new bot. Does the following things:
         1. Select virtual server specified by self.sid
         2. Set bot nickname to the Name specified by self.bot_name
         3. Move the bot to the channel specified by self.default_channel
         4. Register command and event handlers
     :return:
     """
     try:
         self.ts3conn.use(sid=self.sid)
     except ts3.TS3Connection.TS3QueryException:
         self.logger.exception("Error on use SID")
         exit()
     try:
         try:
             self.ts3conn.clientupdate(["client_nickname=" + self.bot_name])
         except TS3QueryException as e:
             if e.type == TS3QueryExceptionType.CLIENT_NICKNAME_INUSE:
                 self.logger.info(
                     "The choosen bot nickname is already in use, keeping the default nickname"
                 )
             else:
                 raise e
         try:
             self.channel = self.get_channel_id(self.default_channel)
             self.ts3conn.clientmove(
                 self.channel, int(self.ts3conn.whoami()["client_id"]))
         except TS3QueryException as e:
             if e.type == TS3QueryExceptionType.CHANNEL_ALREADY_IN:
                 self.logger.info(
                     "The bot is already in the configured default channel")
             else:
                 raise e
     except TS3QueryException:
         self.logger.exception("Error on setting up client")
         self.ts3conn.quit()
         return
     self.command_handler = CommandHandler.CommandHandler(self.ts3conn)
     self.event_handler = EventHandler.EventHandler(
         ts3conn=self.ts3conn, command_handler=self.command_handler)
     try:
         self.ts3conn.register_for_server_events(
             self.event_handler.on_event)
         self.ts3conn.register_for_channel_events(
             0, self.event_handler.on_event)
         self.ts3conn.register_for_private_messages(
             self.event_handler.on_event)
     except ts3.TS3Connection.TS3QueryException:
         self.logger.exception("Error on registering for events.")
         exit()
Ejemplo n.º 19
0
    def isTableFree(self, imagePathA, imagePathB):
        imageA = self.imageHandler.readImage(imagePathA)
        imageB = self.imageHandler.readImage(imagePathB)

        if CommandHandler.areBoundsSet():
            bounds = CommandHandler.getBounds()
            croppedA = self.imageHandler.cropAndRotateRectangleInImage(
                imageA, bounds)
            croppedB = self.imageHandler.cropAndRotateRectangleInImage(
                imageB, bounds)
        else:
            tableABounds = self.tableFinder.getBoundingRectForTable(imageA)
            tableBBounds = self.tableFinder.getBoundingRectForTable(imageB)

            largestBounds = self.imageHandler.getLargestBoundingRect(
                tableABounds, tableBBounds)

            croppedA = self.imageHandler.cropImageByBoundingRect(
                imageA, largestBounds)
            croppedB = self.imageHandler.cropImageByBoundingRect(
                imageB, largestBounds)

        return self.imageComparator.areImagesEqual(croppedA, croppedB)
Ejemplo n.º 20
0
def main():
    s = socket.socket()
    s.connect((Config.HOST, Config.PORT))
    s.send("PASS {}\r\n".format(Config.PASS).encode("utf-8"))
    s.send("NICK {}\r\n".format(Config.NICK).encode("utf-8"))
    s.send("JOIN #{}\r\n".format(Config.CHAN).encode("utf-8"))

    chat_message = re.compile(r"^:\w+!\w+@\w+\.tmi\.twitch\.tv PRIVMSG #\w+ :")
    Utilities.chat(s, "SpotBot has started running!")

    thread.start_new_thread(OpOperations.thread_fill_op_list, ())

    while True:
        response = s.recv(1024).decode("utf-8")
        if response == "PING :tmi.twitch.tv\r\n":
            s.send("PONG :tmi.twitch.tv\r\n".encode("utf-8"))
        else:
            user = re.search(r"\w+", response).group(0)
            message = chat_message.sub("", response)
            message = message.strip()
            CommandHandler.handle_command(user, message, s)
            print(response)
        sleep(1)
Ejemplo n.º 21
0
    def __init__(self, data, bots, config, section):
        (self.host, self.port, self.name, self.pswd) = data
        self._handle_data_reset()

        # Open the database for this bot.
        self.db = shelve.open("{0}@{1}.db".format(
            self.name, self.host).replace(".", "-").replace("/", "-"),
                              writeback=True)

        # Store the list of bots.
        self._bots = bots
        self.config = config
        self.section = section

        # Initialize various classes.
        self.ch = CommandHandler(self)
        self.pi = PlayerInfo(self)
        self.kl = KillsLog(self)
        self.cmds = Commands(self)
        BaseSocket.__init__(self)
        self.commands_load()

        ts = time.time()
        self.who_stamp = ts + self.config.getint("General", "who_delay")
Ejemplo n.º 22
0
def handle_command(command, channel, user):
    """
        Receives commands directed at the bot and determines if they
        are valid commands. If so, then acts on the commands. If not,
        returns back what it needs for clarification.
    """
    new_command = command
    if command[0] == ":":
        new_command = command[1:]

    response, ochannel = CommandHandler.execute_command(
        new_command, channel, user)
    slack_client.api_call("chat.postMessage",
                          channel=ochannel,
                          text=response,
                          as_user=True)
Ejemplo n.º 23
0
    def __init__(self):
            threading.Thread.__init__(self)
            ##first thing to run##
            self.socket = CarSocket.CarSocket(parent = self)
            self.socket.connect("localhost",25566) #host ip
            #self.socket.hostServerSocket(hostname="192.168.0.117", port=25565) #change host ip
            self.setDaemon(False)
            self.socket.setDaemon(False)
            

            io.setmode(io.BCM)
            self.dict = self.oldDict= CommandHandler.blankDict()
            #self.motor = MotorClass.DCMotorClass(17,18,500,100,io) #for dc, not used on new car.

            self.motor = MotorClass.StepperMotor(17,18,20,21,1,io)
            self.motor.setDaemon(False)
            self.motor.start()
            self.servo = ServoClasses.ServoClass(27,100,io)
Ejemplo n.º 24
0
    def __init__(self, data, bots, config, section):
        (self.host, self.port, self.name, self.pswd) = data
        self._handle_data_reset()

        # Open the database for this bot.
        self.db = shelve.open("{0}@{1}.db".format(self.name, self.host).replace(".", "-").replace("/", "-"), writeback = True)

        # Store the list of bots.
        self._bots = bots
        self.config = config
        self.section = section

        # Initialize various classes.
        self.ch = CommandHandler(self)
        self.pi = PlayerInfo(self)
        self.kl = KillsLog(self)
        self.cmds = Commands(self)
        BaseSocket.__init__(self)
        self.commands_load()

        ts = time.time()
        self.who_stamp = ts + self.config.getint("General", "who_delay")
Ejemplo n.º 25
0
    def getMaskForTable(self, poolImage):
        self.th_green_low = numpy.array(CommandHandler.getThGreenLow())
        self.th_green_high = numpy.array(CommandHandler.getThGreenHigh())

        hsvImage = cv.cvtColor(poolImage, cv.COLOR_BGR2HSV)
        return self.getMask(hsvImage)
Ejemplo n.º 26
0
class Bot(BaseSocket):
    ## Initializes the game bot.
    ## @param data Tuple containing the bot's server, port, name and password.
    ## @param bots List of bots.
    ## @param config ConfigParser instance.
    ## @param section Section in the config with the settings for this bot.
    def __init__(self, data, bots, config, section):
        (self.host, self.port, self.name, self.pswd) = data
        self._handle_data_reset()

        # Open the database for this bot.
        self.db = shelve.open("{0}@{1}.db".format(self.name, self.host).replace(".", "-").replace("/", "-"), writeback = True)

        # Store the list of bots.
        self._bots = bots
        self.config = config
        self.section = section

        # Initialize various classes.
        self.ch = CommandHandler(self)
        self.pi = PlayerInfo(self)
        self.kl = KillsLog(self)
        self.cmds = Commands(self)
        BaseSocket.__init__(self)
        self.commands_load()

        ts = time.time()
        self.who_stamp = ts + self.config.getint("General", "who_delay")

    ## Load the possible commands.
    def commands_load(self):
        self.config.read(['config.cfg'])
        # List of recognized commands.
        self.commands = [
            ("^what does(?: (?:the )?acronym)? (\w+) (?:stand for|mean)(?:\?)?$", self.cmds.player_command_acronym),
            ("^(?:wtf|what) is (\w+)(?:\?)?$", self.cmds.player_command_acronym),
            ("^when was ([a-zA-Z0-9_-]+) last (?:on|online|logged in|here|seen)(?:\?)?$", self.cmds.player_command_seen),
            ("^seen ([a-zA-Z0-9_-]+)(?:\?)?$", self.cmds.player_command_seen),
            ("^(?:when (?:have (?:you|u) last seen|did (?:you|u) last see)|(?:last )?seen|have (?:you|u) seen|did (?:you|u) see) ([a-zA-Z0-9_-]+)(?:\?)?$", self.cmds.player_command_seen),
            ("^(?:what|which) (\w+) is ([a-zA-Z0-9_-]+)(?:\?)?$", self.cmds.player_command_info),

            ("^wh(?:o|ich player(s)?) (?:(?:has |have )?died|got killed)(?: the)? most(?: often)?( in(?: the)? arena)?(?:\?)?$", self.cmds.player_command_died),
            ("^wh(?:ich|at) (?:mo(?:b|nster)|beast|thing|creature)(s)? (?:is|are|r)(?: (?:the )?most)? (?:lethal|dangerous)(?:\?)?$", self.cmds.player_command_lethal),
            ("^wh(?:o|ich player(s)?) (?:has|have) killed(?: (?:the )?most)(?: players)? in(?: the)? arena(?:\?)?$", self.cmds.player_command_arena),
            ("^how (?:many times|much) (?:has|did) ([a-zA-Z0-9_-]+) die(?:d)?( in(?: the)? arena)?(?:\?)?$", self.cmds.player_command_died_player),
            ("^how (?:many times|much) (?:has|did) (.+) kill(?:ed)?( in(?: the)? arena)?(?:\?)?$", self.cmds.player_command_killed_count),
            ("^how (?:many times|much) (?:has|did) (.+) kill(?:ed)? ([a-zA-Z0-9_-]+)( in(?: the)? arena)?(?:\?)?$", self.cmds.player_command_killed_player),

            ("^reload commands(?:\.)?$", self.cmds.player_commands_reload),
            ("^chat (.+)$", self.cmds.player_command_chat),
            ("^(?:how much is )?(\d+) (\w+)(?: coin(?:s)?)? in (\w+)(?: coin(?:s)?)?(?:\?)?$", self.cmds.player_command_currency),
            ("^shut(?: )?down$", self.cmds.player_command_quit),
        ]

        # Is there a commands section?
        if not self.config.has_section("Commands"):
            return

        for (name, value) in self.config.items("Commands"):
            (regex, s) = re.match("\"(.+)\" (.+)", value).groups()
            self.commands.append((regex, s))

    ## Closes the bot.
    def close(self):
        self.db.close()
        self.disconnect()
        self._bots.remove(self)

    ## Sends connect data to the game server.
    def _post_connect(self):
        self.send(b"version 1055 1055 Atrinikbot")
        self.send(b"setup bot 1")

    ## Handles queue command sending.
    def _command_queue_handler(self, cmd):
        self.send_command(cmd)

    ## Send data to the server.
    ## @param s The data to send.
    def send(self, s):
        if type(s) != type(bytes()):
            s = s.encode()

        l = len(s)
        s = struct.pack("BB", (l >> 8 & 0xFF), l & 0xFF) + s
        l += 2
        sent = 0

        while sent < l:
            sent += self.socket.send(s[sent:])

    ## Send game command to the server.
    ## @param s The command to send.
    def send_command(self, s):
        self.send("cm {0}".format(s))

    ## Reset internal data used when reading data from socket.
    def _handle_data_reset(self):
        self._readbuf = b""
        self._readbuf_len = 0
        self._header_len = 0
        self._cmd_len = -1

    ## Handle reading data from socket.
    def handle_data(self):
        starttime = time.time()

        while True:
            if time.time() - starttime > 0.5:
                break

            # Less than 2 bytes read (possibly 0 so far), choose how much to read.
            if self._readbuf_len < 2:
                # If we read something already, check for bit marker and read more
                # if applicable, as this is as 3-byte header.
                if self._readbuf_len > 0 and struct.unpack("B", self._readbuf[:1])[0] & 0x80:
                    toread = 3 - self._readbuf_len
                # Standard 2-byte header.
                else:
                    toread = 2 - self._readbuf_len
            # Exactly 2 bytes read; if the bit marker is set, read 1 more, as this
            # a 3-byte header instead of the standard 2-byte one.
            elif self._readbuf_len == 2 and struct.unpack("B", self._readbuf[:1])[0] & 0x80:
                toread = 1
            else:
                # We got the header data, try to parse it.
                if self._readbuf_len <= 3:
                    # Figure out the header length.
                    self._header_len = 3 if struct.unpack("B", self._readbuf[:1])[0] & 0x80 else 2
                    self._cmd_len = 0

                    # Unpack the header.
                    unpacked = struct.unpack("{0}B".format(self._header_len), self._readbuf[:self._header_len])
                    i = 0

                    # 3-byte header.
                    if self._header_len == 3:
                        self._cmd_len += (unpacked[i] & 0x7f) << 16
                        i += 1

                    # 2-byte header or continuation of the above 3-byte one.
                    self._cmd_len += unpacked[i] << 8
                    i += 1
                    self._cmd_len += unpacked[i]

                # Now we know exactly how much data to read to complete the
                # command.
                toread = self._cmd_len + self._header_len - self._readbuf_len

            try:
                # Try to read the data.
                data = self.socket.recv(toread)
            except socket.error:
                return

            # Failed; reset connection.
            if not data:
                self._handle_data_reset()
                self._mark_reconnect()
                return

            # Store the data and update the data's total length.
            self._readbuf += data
            self._readbuf_len += len(data)

            # Have we completed reading the data for the command yet?
            if self._readbuf_len == self._cmd_len + self._header_len:
                # Strip off the header bytes.
                self._readbuf = self._readbuf[self._header_len:]
                # Get the command ID.
                (cmd_id,) = struct.unpack("B", self._readbuf[:1])

                # Command #0 marks compressed data.
                if cmd_id == 0:
                    # Figure out the uncompressed length.
                    ucomp_len = struct.unpack("I", self._readbuf[1:5][::-1])
                    # Uncompress the data.
                    self._readbuf = zlib.decompress(self._readbuf[5:])
                    # Get the actual command ID now.
                    (cmd_id,) = struct.unpack("B", self._readbuf[:1])

                # Handle the command.
                self.ch.handle_command(cmd_id, self._readbuf[1:])
                # Reset the internal pointers.
                self._handle_data_reset()

    ## Handle anything extra.
    def handle_extra(self):
        ts = time.time()

        # Check if it's time to send a /who command yet.
        if ts >= self.who_stamp:
            self.who_stamp = ts + self.config.getint("General", "who_delay")
            self.send_command("/who")

        # Handle command queue.
        self._command_queue_handle()

    ## Handle chat.
    ## @param name Player that activated the chat.
    ## @param msg The message player said.
    ## @param chat Chat type used (tell, shout, say, etc).
    def handle_chat(self, name, msg, chat):
        # Default message if we can't match any regex.
        ret = "I cannot answer that query."
        # Remove extraneous spaces between words.
        msg = " ".join(msg.split())

        # Try to parse the commands.
        for (regex, cmd) in self.commands:
            match = re.match(regex, msg, re.I)

            if match:
                if type(cmd) == type(str()):
                    ret = cmd.format(name)
                else:
                    ret = cmd(name, match.groups())

                break

        if chat == "tell":
            self.send_command("/tell {0} {1}".format(name, ret))
        elif chat == "say":
            self.send_command("/say {0}".format(ret))
Ejemplo n.º 27
0
import sys
import os
import CommandHandler


if __name__ == "__main__":
    CommandHandler.CommandHandler()

    exit(1)
Ejemplo n.º 28
0
class Bot(BaseSocket):
    ## Initializes the game bot.
    ## @param data Tuple containing the bot's server, port, name and password.
    ## @param bots List of bots.
    ## @param config ConfigParser instance.
    ## @param section Section in the config with the settings for this bot.
    def __init__(self, data, bots, config, section):
        (self.host, self.port, self.name, self.pswd) = data
        self._handle_data_reset()

        # Open the database for this bot.
        self.db = shelve.open("{0}@{1}.db".format(
            self.name, self.host).replace(".", "-").replace("/", "-"),
                              writeback=True)

        # Store the list of bots.
        self._bots = bots
        self.config = config
        self.section = section

        # Initialize various classes.
        self.ch = CommandHandler(self)
        self.pi = PlayerInfo(self)
        self.kl = KillsLog(self)
        self.cmds = Commands(self)
        BaseSocket.__init__(self)
        self.commands_load()

        ts = time.time()
        self.who_stamp = ts + self.config.getint("General", "who_delay")

    ## Load the possible commands.
    def commands_load(self):
        self.config.read(['config.cfg'])
        # List of recognized commands.
        self.commands = [
            ("^what does(?: (?:the )?acronym)? (\w+) (?:stand for|mean)(?:\?)?$",
             self.cmds.player_command_acronym),
            ("^(?:wtf|what) is (\w+)(?:\?)?$",
             self.cmds.player_command_acronym),
            ("^when was ([a-zA-Z0-9_-]+) last (?:on|online|logged in|here|seen)(?:\?)?$",
             self.cmds.player_command_seen),
            ("^seen ([a-zA-Z0-9_-]+)(?:\?)?$", self.cmds.player_command_seen),
            ("^(?:when (?:have (?:you|u) last seen|did (?:you|u) last see)|(?:last )?seen|have (?:you|u) seen|did (?:you|u) see) ([a-zA-Z0-9_-]+)(?:\?)?$",
             self.cmds.player_command_seen),
            ("^(?:what|which) (\w+) is ([a-zA-Z0-9_-]+)(?:\?)?$",
             self.cmds.player_command_info),
            ("^wh(?:o|ich player(s)?) (?:(?:has |have )?died|got killed)(?: the)? most(?: often)?( in(?: the)? arena)?(?:\?)?$",
             self.cmds.player_command_died),
            ("^wh(?:ich|at) (?:mo(?:b|nster)|beast|thing|creature)(s)? (?:is|are|r)(?: (?:the )?most)? (?:lethal|dangerous)(?:\?)?$",
             self.cmds.player_command_lethal),
            ("^wh(?:o|ich player(s)?) (?:has|have) killed(?: (?:the )?most)(?: players)? in(?: the)? arena(?:\?)?$",
             self.cmds.player_command_arena),
            ("^how (?:many times|much) (?:has|did) ([a-zA-Z0-9_-]+) die(?:d)?( in(?: the)? arena)?(?:\?)?$",
             self.cmds.player_command_died_player),
            ("^how (?:many times|much) (?:has|did) (.+) kill(?:ed)?( in(?: the)? arena)?(?:\?)?$",
             self.cmds.player_command_killed_count),
            ("^how (?:many times|much) (?:has|did) (.+) kill(?:ed)? ([a-zA-Z0-9_-]+)( in(?: the)? arena)?(?:\?)?$",
             self.cmds.player_command_killed_player),
            ("^reload commands(?:\.)?$", self.cmds.player_commands_reload),
            ("^chat (.+)$", self.cmds.player_command_chat),
            ("^(?:how much is )?(\d+) (\w+)(?: coin(?:s)?)? in (\w+)(?: coin(?:s)?)?(?:\?)?$",
             self.cmds.player_command_currency),
            ("^shut(?: )?down$", self.cmds.player_command_quit),
        ]

        # Is there a commands section?
        if not self.config.has_section("Commands"):
            return

        for (name, value) in self.config.items("Commands"):
            (regex, s) = re.match("\"(.+)\" (.+)", value).groups()
            self.commands.append((regex, s))

    ## Closes the bot.
    def close(self):
        self.db.close()
        self.disconnect()
        self._bots.remove(self)

    ## Sends connect data to the game server.
    def _post_connect(self):
        self.send(b"version 1055 1055 Atrinikbot")
        self.send(b"setup bot 1")

    ## Handles queue command sending.
    def _command_queue_handler(self, cmd):
        self.send_command(cmd)

    ## Send data to the server.
    ## @param s The data to send.
    def send(self, s):
        if type(s) != type(bytes()):
            s = s.encode()

        l = len(s)
        s = struct.pack("BB", (l >> 8 & 0xFF), l & 0xFF) + s
        l += 2
        sent = 0

        while sent < l:
            sent += self.socket.send(s[sent:])

    ## Send game command to the server.
    ## @param s The command to send.
    def send_command(self, s):
        self.send("cm {0}".format(s))

    ## Reset internal data used when reading data from socket.
    def _handle_data_reset(self):
        self._readbuf = b""
        self._readbuf_len = 0
        self._header_len = 0
        self._cmd_len = -1

    ## Handle reading data from socket.
    def handle_data(self):
        starttime = time.time()

        while True:
            if time.time() - starttime > 0.5:
                break

            # Less than 2 bytes read (possibly 0 so far), choose how much to read.
            if self._readbuf_len < 2:
                # If we read something already, check for bit marker and read more
                # if applicable, as this is as 3-byte header.
                if self._readbuf_len > 0 and struct.unpack(
                        "B", self._readbuf[:1])[0] & 0x80:
                    toread = 3 - self._readbuf_len
                # Standard 2-byte header.
                else:
                    toread = 2 - self._readbuf_len
            # Exactly 2 bytes read; if the bit marker is set, read 1 more, as this
            # a 3-byte header instead of the standard 2-byte one.
            elif self._readbuf_len == 2 and struct.unpack(
                    "B", self._readbuf[:1])[0] & 0x80:
                toread = 1
            else:
                # We got the header data, try to parse it.
                if self._readbuf_len <= 3:
                    # Figure out the header length.
                    self._header_len = 3 if struct.unpack(
                        "B", self._readbuf[:1])[0] & 0x80 else 2
                    self._cmd_len = 0

                    # Unpack the header.
                    unpacked = struct.unpack("{0}B".format(self._header_len),
                                             self._readbuf[:self._header_len])
                    i = 0

                    # 3-byte header.
                    if self._header_len == 3:
                        self._cmd_len += (unpacked[i] & 0x7f) << 16
                        i += 1

                    # 2-byte header or continuation of the above 3-byte one.
                    self._cmd_len += unpacked[i] << 8
                    i += 1
                    self._cmd_len += unpacked[i]

                # Now we know exactly how much data to read to complete the
                # command.
                toread = self._cmd_len + self._header_len - self._readbuf_len

            try:
                # Try to read the data.
                data = self.socket.recv(toread)
            except socket.error:
                return

            # Failed; reset connection.
            if not data:
                self._handle_data_reset()
                self._mark_reconnect()
                return

            # Store the data and update the data's total length.
            self._readbuf += data
            self._readbuf_len += len(data)

            # Have we completed reading the data for the command yet?
            if self._readbuf_len == self._cmd_len + self._header_len:
                # Strip off the header bytes.
                self._readbuf = self._readbuf[self._header_len:]
                # Get the command ID.
                (cmd_id, ) = struct.unpack("B", self._readbuf[:1])

                # Command #0 marks compressed data.
                if cmd_id == 0:
                    # Figure out the uncompressed length.
                    ucomp_len = struct.unpack("I", self._readbuf[1:5][::-1])
                    # Uncompress the data.
                    self._readbuf = zlib.decompress(self._readbuf[5:])
                    # Get the actual command ID now.
                    (cmd_id, ) = struct.unpack("B", self._readbuf[:1])

                # Handle the command.
                self.ch.handle_command(cmd_id, self._readbuf[1:])
                # Reset the internal pointers.
                self._handle_data_reset()

    ## Handle anything extra.
    def handle_extra(self):
        ts = time.time()

        # Check if it's time to send a /who command yet.
        if ts >= self.who_stamp:
            self.who_stamp = ts + self.config.getint("General", "who_delay")
            self.send_command("/who")

        # Handle command queue.
        self._command_queue_handle()

    ## Handle chat.
    ## @param name Player that activated the chat.
    ## @param msg The message player said.
    ## @param chat Chat type used (tell, shout, say, etc).
    def handle_chat(self, name, msg, chat):
        # Default message if we can't match any regex.
        ret = "I cannot answer that query."
        # Remove extraneous spaces between words.
        msg = " ".join(msg.split())

        # Try to parse the commands.
        for (regex, cmd) in self.commands:
            match = re.match(regex, msg, re.I)

            if match:
                if type(cmd) == type(str()):
                    ret = cmd.format(name)
                else:
                    ret = cmd(name, match.groups())

                break

        if chat == "tell":
            self.send_command("/tell {0} {1}".format(name, ret))
        elif chat == "say":
            self.send_command("/say {0}".format(ret))
Ejemplo n.º 29
0
def signalCommand(g):
    if not g:
        pass
    else:
        c = ProfileManager.getCommand(g)
        CommandHandler.execute(c)
Ejemplo n.º 30
0
#First check if user account exists
fileFound = FileHandler.DoesAccountExist()
if (not fileFound):
    #Create user account since it doesn't exist
    try:
        CreateAccount()
        console.out(17)  #Success, account created
    except Exception:
        console.out(18)  #Failure
        raise

#Now get the user to log in to their account
credentialPass = False

validationKey = Encryptor.GenerateSALT()
while (not credentialPass):
    verification = VerifyUser()
    if (not verification[0]):
        if (verification[1] == "Invalid"):
            #console.cls()
            console.out(24, 0.03)
    else:
        #Success, user has logged in
        securityKey = Encryptor.GenerateSecurityKey()
        FileHandler.CreateSecurityFile(
            Encryptor.OneWayEncryptor(securityKey, validationKey), username)
        Command = CMD.CommandHandler(username, verification[1])
        credentialPass = verification

PasswordLocker()
Ejemplo n.º 31
0
    Logger.info("Comparing images")

    if oldImage.is_file():
        try:
            isAvailable = pooltableChecker.isTableFree(currentImagePath,
                                                       oldImagePath)
        except Exception as e:
            isAvailable = None
            Logger.exception(e)

    if isAvailable != wasAvailable:
        Logger.info('Posting availability: ' + str(isAvailable))
        mattermost_client.updateMattermostAvailable(isAvailable)

    wasAvailable = isAvailable
    copyfile(currentImagePath, ConfigHandler.getRawImagePath())
    currentImage.rename(oldImagePath)


mattermost_client.postToCommandChannel("Pool-ping is up and running")

while CommandHandler.getRunMain():
    try:
        time.sleep(CommandHandler.getInterval())
        camera.takePicture()
        checkAvailability()
        CommandHandler.reactToCommands()
    except Exception as e:
        Logger.exception(e)

mattermost_client.postToCommandChannel("Pool-ping is shutdown")
Ejemplo n.º 32
0
from MailBox import *
from MailHandlerInterface import *

# Mailbox handlers:
from CommandHandler import *




logger.info('creating MailBox')
mb = MailBox('email_settings.ini', "C:/Users/user/Desktop/automation")

#
# register handlers to treat unread messages
#
mb.add_mailbox_handler(CommandHandler(mb, 'CommandHandlerConfigs.json'))
#mb.add_mailbox_handler(___here___)


# main loop
seed(1)
while True:
    logger.debug('checking mailbox')
    mb.process_unread_messages()
    wait_seconds = int(random()*100)%50 + 15


    logger.debug('waiting {} seconds'.format(wait_seconds))
    separator = ""
    for s in range(80):
        separator = separator + " ="
Ejemplo n.º 33
0
def run():
    while True:
        user_input = input("Enter a command: ")

        split_user_input = user_input.split()

        #validate

        command = split_user_input[0]
        options = split_user_input[1:]

        option_dictionary = {}
        for option in options:
            split_option = option.split(":")
            if len(split_option) == 1:
                option_dictionary[split_option[0]] = ""
            else:
                option_dictionary[split_option[0]] = split_option[1]

        packet_bytes = ""

        if command == "help":
            CommandHandler.handle_help("")
        elif command == "exit":
            break
        elif command == "device-get-service":
            packet_bytes = CommandHandler.handle_device_get_service(
                option_dictionary)
        elif command == "device-get-host-info":
            packet_bytes = CommandHandler.handle_device_get_host_info(
                option_dictionary)
        elif command == "device-get-host-firmware":
            packet_bytes = CommandHandler.handle_device_get_host_firmware(
                option_dictionary)
        elif command == "device-get-wifi-info":
            packet_bytes = CommandHandler.handle_device_get_wifi_info(
                option_dictionary)
        elif command == "device-get-wifi-firmware":
            packet_bytes = CommandHandler.handle_device_get_wifi_firmware(
                option_dictionary)
        elif command == "device-get-power":
            packet_bytes = CommandHandler.handle_device_get_power(
                option_dictionary)
        elif command == "device-set-power":
            packet_bytes = CommandHandler.handle_device_set_power(
                option_dictionary)
        elif command == "device-get-label":
            packet_bytes = CommandHandler.handle_device_get_label(
                option_dictionary)
        elif command == "device-set-label":
            packet_bytes = CommandHandler.handle_device_set_label(
                option_dictionary)
        elif command == "device-get-version":
            packet_bytes = CommandHandler.handle_device_get_version(
                option_dictionary)
        elif command == "device-get-info":
            packet_bytes = CommandHandler.handle_device_get_info(
                option_dictionary)
        elif command == "device-get-location":
            packet_bytes = CommandHandler.handle_device_get_location(
                option_dictionary)
        elif command == "device-set-location":
            packet_bytes = CommandHandler.handle_device_set_location(
                option_dictionary)
        elif command == "device-get-group":
            packet_bytes = CommandHandler.handle_device_get_group(
                option_dictionary)
        elif command == "device-set-group":
            packet_bytes = CommandHandler.handle_device_set_group(
                option_dictionary)
        elif command == "device-echo-request":
            packet_bytes = CommandHandler.handle_device_echo_request(
                option_dictionary)
        elif command == "light-get-state":
            packet_bytes = CommandHandler.handle_light_get_state(
                option_dictionary)
        elif command == "light-set-color":
            packet_bytes = CommandHandler.handle_light_set_color(
                option_dictionary)
        elif command == "light-set-waveform":
            packet_bytes = CommandHandler.handle_light_set_waveform(
                option_dictionary)
        elif command == "light-get-power":
            packet_bytes = CommandHandler.handle_light_get_power(
                option_dictionary)
        elif command == "light-set-power":
            packet_bytes = CommandHandler.handle_light_set_power(
                option_dictionary)
        elif command == "light-set-waveform-optional":
            packet_bytes = CommandHandler.handle_light_set_waveform_optional(
                option_dictionary)
        elif command == "light-get-infrared":
            packet_bytes = CommandHandler.handle_light_get_infrared(
                option_dictionary)
        elif command == "light-set-infrared":
            packet_bytes = CommandHandler.handle_light_set_infrared(
                option_dictionary)
        else:
            print("invalid command. type help for availble commands")

        print()

        if packet_bytes == "":
            continue
        else:
            PacketBroadcaster.broadcast_packet("172.16.10.255", 56700,
                                               packet_bytes)
def main():
    print("\n\n{:^80}\n".format(printBold("***** AADC Voice Control Client *****")))
    print("\n{:^80}\n".format(printBold("((( o )))")))
    # print('\nConnect to:\t[a] ' + bcolors.UNDERLINE + 'Car 26'  + bcolors.ENDC + '\t[b] ' + bcolors.UNDERLINE + 'Car 27'  + bcolors.ENDC +'\t[l] ' + bcolors.UNDERLINE + 'localhost' + bcolors.ENDC +'\n')

    command_handler = CommandHandler(car_ips, control_server_port, SQS_POLL_TIMEOUT)
    
    try:
        while True:
            # STEP 1: connect to the car servers
            s1 = ">>> Stage 1/3: Connect to Cars <<<" + bcolors.ENDC
            print(bcolors.OKGREEN + "\n________________________________________________________________________________\n")
            print("\n{:^80}\n".format(s1))
            
            connected = command_handler.connectToCars()

            if not connected:
                print(bcolors.WARNING + "no connected server found!" + bcolors.ENDC)
                continue
            else:
                print("\nConnected.")
            
            command_handler.printConnectionStats()
            command_handler.printCarStats()

            # STEP 2: connect to AWS
            s2 = ">>> Stage 2/3: Connect to AWS <<<" + bcolors.ENDC
            print(bcolors.OKGREEN + "\n________________________________________________________________________________\n")
            print("\n{:^80}\n".format(s2))

            command_handler.connectToAWS()

            # STEP 3: start the VoiceControl service
            s2 = ">>> Stage 3/3: Connect to AWS <<<" + bcolors.ENDC
            print(bcolors.OKGREEN + "\n________________________________________________________________________________\n")
            print("\n{:^80}\n".format(s2))

            command_handler.startHandler()
                
    except KeyboardInterrupt:
        print('\nexiting.')
        exit()