Example #1
0
    def handle(self, command):
        CommandHandler.handle(self, command)

        # save the username
        user = self.argument.split(";", 1)
        self.client.set_username(user[0])

        # get the password md5
        passwordmd5 = md5.new(user[1])

        # can't re-login
        if(self.__database.get_logged_in(user[0])):
            self.__logger.warn(user[0] + ": trying to re-login")
            self.client.buffer_send("/failed")
            self.client.quit()
            return

        # authenticate the user
        if(self.__database.authenticate(user[0], passwordmd5.hexdigest())):
            self.__database.set_logged_in(user[0], True)
            self.client.set_logged_in(True)
            self.client.broadcast(self.client.get_username() + " has logged in\n")
            self.client.buffer_send("/success")
        else:
            self.client.set_logged_in(False)
            self.client.buffer_send("/failed")
Example #2
0
    def __init__(self, client, database):
        CommandHandler.__init__(self, "/login", client)

        # get a logger
        self.__logger = logging.getLogger("chattest.server.commands.LoginCommandHandler")
        self.__logger.debug("Created a new LoginCommandHandler object...")

        # init member variables
        self.__database = database
Example #3
0
    def test_message_does_not_contain_command(self):
        message = Message("I just pooped my pants :(", "randomuser")
        channel = Channel(Config.CHANNEL_NAME)
        commandhandler = CommandHandler(channel)

        commandres, argumentres = commandhandler.message_contains_command(
            message)

        self.assertEqual(None, commandres)
        self.assertEqual(None, argumentres)
Example #4
0
 def test_register_password_length(self):
     """
     This function deals with test for registration data 
     and whether password with length of less than 8 characters 
     are not getting accepted.
     """
     user_test = CommandHandler()
     expected_result = "\n Password length should be more than 8 characters."
     obtained_result = user_test.register('test1', '122')
     self.assertEqual(expected_result, obtained_result)
     user_test.quit()
Example #5
0
    def test_message_contains_command(self):
        command = "!uptime"
        commandname = "uptime"
        message = Message(command, "randomuser")
        channel = Channel(Config.CHANNEL_NAME)
        commandhandler = CommandHandler(channel)

        commandres, argumentres = commandhandler.message_contains_command(
            message)

        self.assertEqual(commandname, commandres)
        self.assertEqual(None, argumentres)
Example #6
0
    def test_message_contains_command_with_arguments(self):
        command = "!bonus"
        commandname = "bonus"
        argument = "ToMiSmE 1000"
        message = Message(command + " " + argument, "randomuser")
        channel = Channel(Config.CHANNEL_NAME)
        commandhandler = CommandHandler(channel)

        commandres, argumentres = commandhandler.message_contains_command(
            message)

        self.assertEqual(commandname, commandres)
        self.assertEqual(argument, argumentres)
Example #7
0
    def test_register_successful_registration(self):
        """
        This function deals with test whether the user provided data
         is being registered successfully
        """

        user_test = CommandHandler()
        expected_result = "\nSuccessfully registered user"
        obtained_result = user_test.register("test2", "13791247nbdshrlfngls")
        self.assertEqual(expected_result, obtained_result)
        user_test.quit()
        shutil.rmtree(os.path.join("Root/test2"))
        shutil.rmtree(os.path.join("AccessSession/"))
Example #8
0
    def test_command_does_not_exists_is_not_triggered(self):
        command = "!boguscommand"
        message = Message(command, "randomuser")
        channel = Channel(Config.CHANNEL_NAME)
        channel.commands.append(
            Command(-1, Config.CHANNEL_NAME, "Blizzard id", True,
                    "My Blizzard ID is UncleBob#199", True, True, True, False,
                    False, False, None, None))
        commandhandler = CommandHandler(channel)

        commandres, can_trigger = commandhandler.is_command_triggered(message)

        self.assertEqual(None, commandres)
        self.assertEqual(None, can_trigger)
Example #9
0
    def test_command_exists_and_is_triggered(self):
        command = "!social"
        commandname = "social"
        message = Message(command, "randomuser")
        channel = Channel(Config.CHANNEL_NAME)
        channel.commands.append(
            Command(-1, Config.CHANNEL_NAME, "social", True,
                    "Join my Discord at www.discord.com", True, True, True,
                    True, True, True, None, None))
        commandhandler = CommandHandler(channel)

        commandres, can_trigger = commandhandler.is_command_triggered(message)

        self.assertEqual(commandname, commandres.name)
        self.assertEqual(True, can_trigger)
Example #10
0
def run():
    if os.geteuid() != 0:
        sys.stdout.write(
            'You need to have root privileges to run {0} commands.\n'
            'Please try again, this time using \'sudo\'.\n'.format(
                PackageInfo.pip_package_name))
        sys.stdout.flush()
        sys.exit(1)

    (opts, args) = ClientOptionParser().parse_args()
    logger = ClientLogger.setup(opts)

    try:
        with CommandHandler(opts, args) as handler:
            handler.on(Command.STOP, ClientDaemon.stop)
            handler.on(Command.START, __handle_start_command)
            handler.on(Command.STATUS, __handle_status_command)
            handler.on(Command.UPDATE, __handle_update_command)
            handler.on(Command.REMOVE, ClientDaemon.remove)
            handler.on(Command.RESTART, ClientDaemon.restart)
            return handler.handle_command()

    except Exception as e:
        logger.exception(e)
        sys.stdout.write(str(e))
        sys.stdout.flush()
        sys.exit(1)
Example #11
0
class MainLoop:
    option = Option()
    quit = False
    userInput = UserInput()
    commandHandler = CommandHandler()
    output = Output()
    execInstrution = ExecInstruction()

    def __init__(self, option):
        self.option = option
        self.start_loop()

    def start_loop(self):
        while not self.quit:
            self.output.load_prompt()
            try:
                cmd = self.userInput.read_input()

                if cmd:
                    self.option.payload = None
                    self.commandHandler.command_handler(cmd, self.option)

                    if self.option.payload:
                        self.execInstrution.run(self.option)

            except KeyboardInterrupt:
                self.output.write_message("use " + Color.pink + "\"quit\"" + Color.reset + " to exit")
Example #12
0
 def __init__(self):
     self.voice = VoiceHandler()
     self.command_handler = CommandHandler()
     self.commands = [
         k for k in list(self.command_handler.__class__.__dict__.keys())
         if "__" not in k
     ]
     self.listen_for_commands()
 def __init__(self):
     if AttendanceTaker.__instance != None:
         raise Exception("This class is a singleton!")
     else:
         AttendanceTaker.__instance = self
     self.educationSystem = EducationSystem.getInstance()
     self.educationSystem.initializeSystem()
     self.commandHandler = CommandHandler.getInstance()
Example #14
0
 def test_quit(self):
     """
     This function deals whether the server closing 
     the TCP connection between client and server in a
     proper way
     """
     user_test = CommandHandler()
     user_test.register('test', '12343535373')
     user_test.login('test', '12343535373')
     user_test.quit()
     expected_result = "\nLogged Out"
     obtained_result = user_test.quit()
     self.assertEqual(expected_result, obtained_result)
     shutil.rmtree(os.path.join("Root/"))
     shutil.rmtree("AccessSession/")
Example #15
0
def main():
    start = time.time()

    if len(sys.argv) == 1:
        CommandHandler.printHelp()

    elif sys.argv[1] == "test":
        weapon_generation(1, "SHOTGUN")
        exit(0)

    elif len(sys.argv) < 3:
        CommandHandler.printHelp()

    elif len(sys.argv) == 3:
        weapon_generation(int(sys.argv[1]), sys.argv[2])

    end = time.time()

    print("Time elapsed " + str(end - start))
Example #16
0
def main():
    arguments = docopt(__doc__)

    #if arguments["help"] == True and arguments["<command>"] != None: # Consider if needed also: module help [<command>]; check also docopt git help example
    if arguments["<command>"] == 'help':
        print __doc__
    else:
        cc = CommandChecker(  arguments   )
        ch = CommandHandler( cc.arguments )
        print "done"
        exit(ch.status)
Example #17
0
    async def on_message(self, message):
        if message.author == self.user:
            return

        # Handle the Commands with globalCall
        if (message.content.startswith(globalCall)):
            myCommand = CommandHandler()
            await myCommand.commandParser(message, globalCall)

        # Good night response
        if (message.content.lower() in ["good night","gn","goodnight"]):
            await (message.channel.send("Good night " + str(message.author)[:-5]))
Example #18
0
    def test_commands_output(self):
        """
        This function deals with testing commands output
        """

        commands = [
            "register : For registering the new user ,command:register <username> <password> \n",
            "login : To login, command:login <username> <password>,Note:password should be in integer\n",
            "quit : To logout, command:quit\n",
            "change_folder : To change the path, command:change_folder <name>\n",
            "list : list of all files in the path, command:list\n",
            "read_file : To read content from the file, command:read_file <name>\n",
            "write_file : To write content into the file, command:write_file <name>\n",
            "create_folder : To create new folder, command:create_folder <name>\n"
        ]
        description = ""
        for command in commands:
            description += command

        user_test = CommandHandler()
        obtained_result = user_test.commands()
        self.assertEqual(description, obtained_result)
Example #19
0
class StartActionThread(QThread):
    signal = pyqtSignal('PyQt_PyObject')

    def __init__(self, command=None):
        QThread.__init__(self)
        self.speaker = AssistantSpeaker()
        self.listener = AssistantListener()
        self.commandHandler = CommandHandler()
        self.command = command

    def run(self):

        if self.command is None:
            self.speaker.say("Tell me your command")
            self.command = self.listener.listen()

        # -1 means a WaitTimeoutException occured
        if (self.command == -1):
            self.speaker.say("Sorry, I could not understand the command")
        else:
            self.commandHandler.executeCommand(self.command)

        self.signal.emit("finished")
Example #20
0
    def test_login(self):
        """
        This function deals with test for login data
        """

        user_test = CommandHandler()
        user_test.register('test', '123456737')
        expected_result = ["\nWrong Password, try again"]
        obtained_result = []
        tests = [['test', '12345678']]
        for test in tests:
            obtained_result.append(user_test.login(test[0], test[1]))
        user_test.quit()
        self.assertListEqual(obtained_result, expected_result)
        shutil.rmtree(os.path.join("Root/"))
        shutil.rmtree("AccessSession/")
Example #21
0
async def handle_echo(reader, writer):
    '''
    This funtion acknowledges the connection from the client,
    acknowledges the messages from the client
    '''
    addr = writer.get_extra_info('peername')
    message = f"{addr} is connected !!!!"
    print(message)
    commandhandler = CommandHandler()
    while True:
        data = await reader.read(4096)
        message = data.decode().strip()
        if message == 'exit':
            break

        print(f"Received {message} from {addr}")
        mymsg = client_request(commandhandler, message)
        msg = str(mymsg).encode()
        writer.write(msg)
        await writer.drain()
    print("Close the connection")
    writer.close()
Example #22
0
from Bot import Bot
from CommandHandler import CommandHandler

bot = Bot("350263518:AAHTcAESb1VKuAT3cgiks0PMNPSinWlAs2I")

handler = CommandHandler(bot.bot)
handler.start_handle()
Example #23
0
    def handle(self, command):
        CommandHandler.handle(self, command)

        self.client.update_ping()
Example #24
0
    def __init__(self, client):
        CommandHandler.__init__(self, "/say", client)

        # get a logger
        self.__logger = logging.getLogger("chattest.server.commands.SayCommandHandler")
        self.__logger.debug("Created a new SayCommandHandler object...")
Example #25
0
 spotify = Spotify()
 Mopidy.clear_queue()
 tracks = spotify.get_tracks()
 for track in tracks:
     Mopidy.add_track(track["track"]["uri"])
 
 Mopidy.enable_consume()
 Mopidy.shuffle()
 Mopidy.play()
 
 slack = Slack(config.SLACK_TOKEN)
 READ_WEBSOCKET_DELAY = 1
 song = None
 Mopidy.set_volume(config.VOLUME)
 config.PLAYING_MAX = False
 if slack.connect():
     while True:
         channel, user, message = slack.read_message()
         response = CommandHandler.handle_message(channel, user, message)
         if response is not None:
             slack.send_message(response, channel)
         
         current_song = Mopidy.get_current_song()
         if song != current_song:
             slack.send_message(current_song, config.SLACK_CHANNEL)
             song = current_song
             Mopidy.set_volume(config.VOLUME)
             config.PLAYING_MAX = False
         time.sleep(READ_WEBSOCKET_DELAY)
 else:
     print("error connecting")    
Example #26
0
 def __init__(self, command=None):
     QThread.__init__(self)
     self.speaker = AssistantSpeaker()
     self.listener = AssistantListener()
     self.commandHandler = CommandHandler()
     self.command = command
Example #27
0
                   sample_width=asource.get_sample_width(),
                   channels=asource.get_channels())
    threading.Thread(target=handle_command, args=(command_name, )).start()

    listen_for_commands.counter += 1
    log("Waiting for a command...")


if __name__ == "__main__":

    # Delete all .wav files
    for file in glob.glob("*.wav"):
        remove(file)

    # Command utilities:
    handler = CommandHandler()

    # Auditok utilities:
    asource = ADSFactory.ads(sampling_rate=16000,
                             sample_width=2,
                             channels=1,
                             frames_per_buffer=512,
                             record=False,
                             block_dur=0.01)
    validator = AudioEnergyValidator(sample_width=asource.get_sample_width(),
                                     energy_threshold=50)
    tokenizer = StreamTokenizer(validator=validator,
                                min_length=100,
                                max_length=500,
                                max_continuous_silence=30)
    def handle(self, command):
        CommandHandler.handle(self, command)

        if(self.client.get_logged_in()):
            self.client.broadcast(self.client.get_username() + " has disconnected\n")
        self.client.quit()
from CommandHandler import CommandHandler

command_handler = CommandHandler()

command_handler.handle('dictate')
command_handler.handle('yoda')
command_handler.handle('execute', 'chrome.exe')
command_handler.handle('execute', 'edge')
command_handler.handle('execute', 'explorer')
command_handler.handle('google', 'agh')
command_handler.handle('down')
command_handler.handle('down')
command_handler.handle('home')
command_handler.handle('down')
command_handler.handle('down')
command_handler.handle('up')
command_handler.handle('select_all')
command_handler.handle('copy')
command_handler.handle('execute', 'notepad')
command_handler.handle('paste')
command_handler.handle('save', 'test')
command_handler.handle('undo')
command_handler.handle('close')
command_handler.handle('desktop')






Example #30
0
    def handle(self, command):
        CommandHandler.handle(self, command)

        self.client.update_ping(False)
        self.client.broadcast(self.client.get_username() + ": " + self.argument + "\n")
Example #31
0
    def handle(self, command):
        CommandHandler.handle(self, command)

        self.client.buffer_send("/help       - Display this help\n")
        self.client.buffer_send("/disconnect - Disconnect from the server\n")
        self.client.buffer_send("/say        - Say something\n")
Example #32
0
    #Log everything to a file. New file each day, keep 2 days
    loggingFileHandler = logging.handlers.TimedRotatingFileHandler(
        os.path.join(GlobalStore.scriptfolder, 'Program.log'),
        when='midnight',
        backupCount=2,
        delay=True,
        utc=True)
    loggingFileHandler.setLevel(logging.DEBUG)
    loggingFileHandler.setFormatter(loggingFormatter)
    logger.addHandler(loggingFileHandler)

    #Also print everything to the console
    loggingStreamHandler = logging.StreamHandler(sys.stdout)
    loggingStreamHandler.setLevel(logging.DEBUG)
    loggingStreamHandler.setFormatter(loggingFormatter)
    logger.addHandler(loggingStreamHandler)

    #Start up the CommandHandler and have it load in all the modules
    GlobalStore.commandhandler = CommandHandler()
    GlobalStore.commandhandler.loadCommands()

    #Get the config files we need to load from the argument parser
    serverfolderList = args.serverlist.split(',')
    #Start up the bots
    bothandler = BotHandler(serverfolderList)

    #Only quit once every bot and command finishes running
    gevent.wait()
    logger.info("All bots quit and all commands unloaded, exiting")
Example #33
0
def main():
    command_handler = CommandHandler()
    command_handler.run()