コード例 #1
0
def main():
    """
    Main function: call experiment's routines
    """

    # New experiment
    Exp = Core()

    Exp.init(root_folder, custom=False)

    # Instantiate Trial and experiment
    trial = Trial(design=Exp.design, settings=Exp.config.settings, userfile=Exp.user.datafilename,
                  pause_interval=int(Exp.config.settings['setup']['pauseInt']))

    while trial.status is not False:
        trial.setup()

        if trial.status is True:

            valid = np.random.uniform(0.0, 1.0) < 0.95
            trial.stop(valid)
            trial.write_data({'intensity': 0, 'correct': 'left'})

    data = trial.load_data()

    # Check that all the conditions have been played
    levels = Exp.design.allconditions['timing']
    trials_per_condition = np.zeros((1, len(levels)))
    for row in data:
        if row['Replay'] == 'False':
            ind = [i for i, j in enumerate(levels) if j == float(row['timing'])]
            trials_per_condition[0, ind[0]] += 1
    print(trials_per_condition)
コード例 #2
0
ファイル: HomeController.py プロジェクト: JailsonS/mvc_python
 def btnClicked(self, caption):
     if caption == "Open Customers DB":
         c = Core.openController("show")
         c.main()
     elif caption == "Add customer":
         c = Core.openController("add")
         c.main()
     elif caption == "Show customers with TreeView":
         c = Core.openController("showTreeView")
         c.main()
コード例 #3
0
    def __init__(self):

        config = configparser.ConfigParser()
        config.read(sys.argv[1])

        self.__core__ = Core(config)
        self.__core__.serviceManager.initializeServices()
        self.__core__.serviceManager.startServices()
コード例 #4
0
ファイル: ShowController.py プロジェクト: JailsonS/mvc_python
class ShowController(Controller):
    #-----------------------------------------------------------------------
    #        Constructor
    #-----------------------------------------------------------------------
    def __init__(self):
        self.customers = Customers()
        self.showView = self.loadView("show")
        self.core = Core()

    #-----------------------------------------------------------------------
    #        Methods
    #-----------------------------------------------------------------------
    """
        @return All customers in database
    """

    def getCustomers(self):
        data = self.customers.getAll()
        return data

    """
        Opens EditController
        
        @param id_customer Customer id that will be edited
    """

    def btnEdit(self, id_customer):
        customer = self.customers.get(id_customer)
        c = self.core.openController("edit")
        c.main(customer, self.showView)

    """
        Deletes the chosen customer and updates the ShowView
        
        @param id_customer Customer id that will be edited
    """

    def btnDel(self, id_customer):
        self.customers.delete(id_customer)
        self.showView.update()
        messagebox.showinfo("Delete customer",
                            "Customer deleted with success!")

    """
        @Override
    """

    def main(self):
        self.showView.main()
コード例 #5
0
ファイル: main.py プロジェクト: Fperdreau/EasyExp
def main():
    """
    Main function: call experiment's routines
    """

    # Get CLI arguments
    cli = True if len(sys.argv) > 1 and sys.argv[1] == 'cli' else False

    # Create new experiment
    experiment = Core()

    # Initialize experiment
    experiment.init(root_folder, cli=cli)

    # Open main window and run the experiment
    experiment.run()
コード例 #6
0
ファイル: morphux.py プロジェクト: Josyann/Morphux-IRC-Bot
 def connect(self):
     self.s = Core(self.config)
     if (self.config["identify"] != 0):
         self.s.identify()
     self.s.join()
     self.s.send(self.config["welcomeMessage"])
コード例 #7
0
 def run():
     try:
         app = Core.openController("home")
         app.main()
     except Exception as e:
         print(str(e))
コード例 #8
0
ファイル: CoreTest.py プロジェクト: JailsonS/mvc_python
 def testName(self):
     controller = Core.openController("Home")
     self.assertIsInstance(controller, HomeController)
コード例 #9
0
ファイル: morphux.py プロジェクト: abclive/Morphux-IRC-Bot
	def 	connect(self):
		self.s = Core(self.config)
		if (self.config["identify"] != 0):
			self.s.identify()
		self.s.join()
		self.s.send(self.config["welcomeMessage"])
コード例 #10
0
ファイル: morphux.py プロジェクト: abclive/Morphux-IRC-Bot
class	Morphux:

	# Construct function
	# @param path of the config file (Optional)
	def 	__init__(self, path = "/etc/morphux/configBot.json"):
		fd = open(path)
		self.config = json.load(fd)
		self.currentUsers = {}
		self.join = {}
		self.leave = {}
		self.quit = {}
		self.nickChange = {}
		self.before = {}
		self.after = {}
		self.commands = {}

	# Connect the bot to the server and the chan
	def 	connect(self):
		self.s = Core(self.config)
		if (self.config["identify"] != 0):
			self.s.identify()
		self.s.join()
		self.s.send(self.config["welcomeMessage"])

	# Main Loop
	def 	loop(self):
		while 1:
			line = self.s.getLine()
			before = 1
			#print(line);
			# Treat Line
			self.getHeadersLine(line)
			if ("JOIN" in line):
				self.onJoin(line)
			elif ("PART" in line):
				self.onLeave(line)
			elif ("QUIT" in line):
				self.onQuit(line)
			elif ("NICK" in line):
				self.onNickChange(line)
			elif ("PRIVMSG" in line):
				infos = self.getInfo(line)
				for name, function in self.before.items():
					if (function(self, line) == 0):
						before = 0
				if (before == 0):
					self.s.CorePrint("Aborting treatement");
				elif (infos != False):
					if (infos["command"] in self.commands):
						self.commands[infos["command"]]["function"](self, infos)
						print("New command ["+ infos['nick'] +"]: " + infos["command"])
					else:
						self.sendMessage(self.config["errorMessage"], infos["nick"])
			for name, function in self.after.items():
				function(self, line)

	# Send message
	# @param: string
	# @param: string (Optional)
	def 	sendMessage(self, string, user = False):
		if (user != False):
			self.s.send(user + ": " + string)
		else:
			self.s.send(string)

	# Get Line Information
	# @param: string
	def 	getInfo(self, line):
		infos = {}
		infos["fullLine"] = line
		args = line.split(":", 2)[2]
		args = args.split(" ")
		args = filter(None, args)
		if (args[0][0] != self.config["symbol"]):
			return False
		args[0] = args[0][1:]
		infos["command"] = args[0]
		args.remove(args[0])
		if (infos["command"] == "help"):
			self.showHelp(args)
			return False
		infos["args"] = args
		user = line.split(":", 2)[1]
		infos["fullUser"] = user.split(" ")[0]
		infos["nick"] = user.split("!", 2)[0]
		return infos;

	# Load Modules
	# @param: path (Optional)
	def loadModules(self, path = "modules"):
		res = {}
		import os
		lst = os.listdir(path)
		dir = []
		for d in lst:
			s = os.path.abspath(path) + os.sep + d
			if os.path.isdir(s) and os.path.exists(s + os.sep + "__init__.py"):
				dir.append(d)
		for d in dir:
			res[d] = __import__(path + "." + d + "." + d, fromlist = ["*"])
			res[d] = getattr(res[d], d.title())
		self.modules = res
		self.getCommands()

	# Get modules in dictionnary
	def getCommands(self):
		commands = {}
		for name, klass in self.modules.items():
			self.s.CorePrint("Loading '"+ name +"' module...")
			klass = klass()
			result = klass.command()
			commands = result["command"]
			pprint(commands)
			if ("onJoin" in result):
				for name, function in result["onJoin"].items():
					self.join[name] = function
			if ("onLeave" in result):
				for name, function in result["onLeave"].items():
					self.leave[name] = function
			if ("onQuit" in result):
				for name, function in result["onQuit"].items():
					self.quit[name] = function
			if ("onNickChange" in result):
				for name, function in result["onNickChange"].items():
					self.nickChange[name] = function
			if ("before" in result):
				for name, function in result["before"].items():
					self.before[name] = function
			if ("after" in result):
				for name, function in result["after"].items():
					self.after[name] = function
			for name, function in commands.items():
				commands[name] = function
			self.s.printOk("OK")
			self.commands.update(commands)


	# On User Join
	# @param: string
	def onJoin(self, line):
		user = line.split(" ")
		user[0] = user[0][1:]
		self.currentUsers[user[0].split("!")[0]] = True
		if (user[0].split("!")[0] == self.config['nick']):
			return
		for name, function in self.join.items():
			function(self, user[0].split("!")[0])

	# On Nick Change
	# @param: string
	def onNickChange(self, line):
		user = line.split(" ")
		user[0] = user[0][1:]
		userName = user[0].split("!")
		newNick = user[2][1:]
		if (userName[0] in self.currentUsers):
			del self.currentUsers[userName[0]]
			self.currentUsers[newNick] = True
		if (newNick == self.config['nick']):
			return
		for name, function in self.nickChange.items():
			function(self, userName[0], newNick)


	# Get Initial list of Users
	# @param: string
	def getHeadersLine(self, line):
		line = line.split("\n")
		for value in line:
			users = value.split(":")
			if (len(users) >= 2):
				details = users[1].split(" ")
				if (len(details) >= 2):
					if (details[1] == "353"):
						users = users[2].split(" ")
						for nickName in users:
							nickName = nickName.split("\r\n")[0]
							nickName = nickName.split("\r")[0]
							if (nickName[0] == '@'):
								nickName = nickName[1:]
								self.currentUsers[nickName] = {"isAdmin": 1}
							else:
								self.currentUsers[nickName] = True

	# On User Leave
	# @param: string
	def onLeave(self, line):
		user = line.split(" ")[0][1:]
		nickName = user.split("!")[0]
		if (nickName in self.currentUsers):
			del self.currentUsers[nickName]
		for name, function in self.leave.items():
			function(self, nickName)

	# On User QUIT
	# @param: string
	def onQuit(self, line):
		user = line.split(" ")[0][1:]
		nickName = user.split("!")[0]
		if (nickName in self.currentUsers):
			del self.currentUsers[nickName]
		for name, function in self.quit.items():
			function(self, nickName)

	# If User is connected
	# @param: string
	def userExists(self, nick):
		if (nick in self.currentUsers):
			return True
		else:
			return False

	# If User is Admin
	# @param: string
	def isAdmin(self, nick):
		if (self.userExists(nick)):
			if (self.currentUsers[nick] != True):
				if ('isAdmin' in self.currentUsers[nick]):
					return True
		return False

	# Show Help for a command
	# @param: list
	def showHelp(self, args):
		if (args[0] in self.commands):
			usage = self.commands[args[0]]["usage"]
			help = self.commands[args[0]]["help"]
			self.sendMessage(args[0] +": <"+ usage +"> ("+help+")")
		else:
			self.sendMessage("Can't find command " + args[0])

	# Kick an user
	def kick(self, user, reason):
		self.s.kick(user, reason)
コード例 #11
0
class Interceptor(object):
    def __init__(self):
        self.form = None
        self.core = Core()
        self.absolute_path = self.get_absolute_path()
        # self.core.train_nb_classifier() last testing accuracy = 62 percent
        pass

    @staticmethod
    def get_absolute_path():
        """
        This method gets the absolute path to the current working directory according to the operating system
        :return: The absolute path to the current working directory
        :rtype: basestring
        """
        system = pl_system()
        if system == 'Darwin':
            return getcwd()
        elif system == 'Linux':
            return path.dirname(getcwd())
        else:
            return getcwd()

    def intercept(self, request):
        """

        :param request: a string that determines the action to be executed
        :type request: basestring
        :return:
        :rtype:
        """
        print request
        try:
            if request == 'Analyse' or request == 'Query':
                query = self.form.get_text_field('Query').get_value().lower()
                start_new_thread(self.analyse, (query, ))

                return True
            elif request == 'Quit':
                self.stop()

        except Exception as e:
            self.stop()
            print str(e)

    def analyse(self, query):
        try:
            start_time = time()
            sentence = self.form.components['labels_panel'].labels['sentence']
            language = self.form.components['labels_panel'].labels['language']
            result = self.form.components['labels_panel'].labels['result']
            elapsed_time = self.form.components['labels_panel'].labels['time']
            sentence.setText('Sentence in english:  Loading ...')
            language.setText('Original language:  Loading ...')
            result.setText('Prediction: Loading ...')
            elapsed_time.setText('Elapsed Time:  Loading ...')
            for lang in language_codes:
                if lang['alpha2'] == detect(query):
                    language.setText('Original language: ' + lang['English'] +
                                     '\n')

            translated_query = translator.translate(query, 'en', detect(query))
            chunked_text = ''
            for chunk in chunkstring(
                    'Sentence in english: ' + translated_query, 90):
                chunked_text += (chunk + '\n')
            sentence.setText(chunked_text + '\n')
            sentence.repaint()
            result.repaint()
            result.setText('Prediction: ' +
                           self.core.predict(translated_query))
            elapsed_time.setText('Elapsed Time: ' +
                                 str(round((time() - start_time) * 1000)) +
                                 ' ms')
            result.repaint()
            QApplication.processEvents()
        except Exception as e:
            print e
            self.stop()

    def set_form(self, form):
        self.form = form

    def stop(self):
        print 'Stop'
        exit(0)
コード例 #12
0
 def __init__(self):
     self.form = None
     self.core = Core()
     self.absolute_path = self.get_absolute_path()
     # self.core.train_nb_classifier() last testing accuracy = 62 percent
     pass
コード例 #13
0
main_loop = asyncio.get_event_loop()

downloader = MasterDownloader(config, [
    YoutubeDownloader(config),
    FileDownloader(config),
    HtmlDownloader(config),
    LinkDownloader(config),
])
# modules = [DiscordComponent(config, discord.Client(loop=main_loop)), TgFrontend(config)]
modules = [
    DiscordComponent(config, discord.Client(loop=main_loop)),
    StatusWebServer(config)
]
# modules = [VLCStreamer(config), TgFrontend(config)]

core = Core(config, components=modules, downloader=downloader, loop=main_loop)

# Start prometheus server
prometheus_client.start_http_server(8910)

# Run event loop
try:
    main_loop.run_forever()
except (KeyboardInterrupt, SystemExit):
    pass
logger.info("Main event loop has ended")
logger.debug("Cleaning...")
try:
    core.cleanup()
except AttributeError:
    traceback.print_exc()
コード例 #14
0
 def btnEdit(self, id_customer):
     customer = self.customers.get(id_customer)
     c = Core.openController("edit")
     c.main(customer, self.showView)
コード例 #15
0
def run_easyexp_simulation(conditions=None):
    """
    Run simulation using the EasyExp framework
    :param conditions: dictionary providing experiment conditions. If not provided, then conditions.json will be loaded
    :type conditions: dict
    :return:
    """
    # New experiment
    Exp = Core()

    Exp.init(root_folder, conditions=conditions)

    # Instantiate Trial and experiment
    trial = Trial(design=Exp.design, settings=Exp.config.settings, userfile=Exp.user.datafilename)

    options = Exp.design.allconditions['options']
    Method = trial.method
    Method.options = options

    stairs = {}
    for t in Exp.design.design:
        if t['staircaseID'] not in stairs:
            stairs.update({str(t['staircaseID']): {'true': np.random.uniform(options['stimRange'][0],
                                                                             options['stimRange'][1])}})

    sd = 0.10 * (options['stimRange'][1] - options['stimRange'][0])  # std

    while trial.status is not False:
        trial.setup()

        if trial.status is True:
            intensity = Method.update(int(trial.parameters['staircaseID']), int(trial.parameters['staircaseDir']))

            mu = stairs[(trial.parameters['staircaseID'])]['true']

            internal_rep = intensity + sd * np.random.normal()
            resp_curr = internal_rep > mu

            logging.getLogger('EasyExp').info('ID: {} mu: {} intensity: {} internal: {} response: {}'.format(
                trial.parameters['staircaseID'], mu, intensity, internal_rep, resp_curr))

            # Simulate lapse
            valid = np.random.uniform(0.0, 1.0) <= 1.0
            trial.stop(valid)

            # Write data
            trial.write_data({'intensity': intensity, 'correct': resp_curr})

    # Load data from datafile
    data = trial.load_data()

    # Analysis
    # Plot staircase results
    import copy
    res = dict()
    default_fields = {
        'id': None,
        'intensities': [],
        'responses': [],
        'n': [],
        'bin_intensities': [],
        'bin_responses': []
    }

    ntrials = {}
    for trial in data:
        if trial['Replay'] == 'False':
            stair_id = trial['staircaseID']
            if stair_id not in res.keys():
                fields = copy.deepcopy(default_fields)
                res.update({stair_id: fields})
                res[stair_id]['id'] = stair_id
                ntrials[stair_id] = 0

            ntrials[stair_id] += 1
            res[stair_id]['intensities'].append(float(trial['intensity']))
            res[stair_id]['responses'].append(1 if trial['correct'] == "True" else 0)

    print('Completed trials per staircase:')
    print(ntrials)

    for ind in res.keys():
        stair = res[ind]
        bins = np.linspace(min(stair['intensities']), max(stair['intensities']), 10)
        indices = np.digitize(stair['intensities'], bins)
        stair['responses'] = np.array(stair['responses'])
        stair['bin_responses'] = np.zeros((1, len(bins)))
        stair['n'] = np.zeros((1, len(bins)))
        for b in range(1, len(bins)):
            stair['n'][0, b-1] = len(stair['responses'][indices == b])
            total_correct = np.sum(stair['responses'][indices == b])
            stair['bin_responses'][0, b-1] = (total_correct / float(stair['n'][0, b-1])) if stair['n'][0, b-1] > 0 else 0.0
        stair['bin_intensities'] = bins

    # Plot responses
    marker_size = (stair['n'][0, :] / float(np.max(stair['n'][0, :]))) * 20
    for i in range(len(bins)):
        plt.plot(bins[i], stair['bin_responses'][0, i], 'o', markersize=marker_size[i])

    plt.xlabel('Stimulus intensity')
    plt.ylabel('p(correct)')
    plt.show()

    trues = []
    estimates = []
    for stair, result in res.iteritems():
        intensities = result['intensities']
        responses = result['responses']
        stairs[stair]['estimate'] = intensities[-1]
        trues.append(stairs[stair]['true'])
        estimates.append(stairs[stair]['estimate'])
        responses = ['True' if i == True else 'False' for i in responses]

        plot_staircase(intensities, responses, stairs[stair]['true'])

    plot_correlation(trues, estimates)
コード例 #16
0
ファイル: morphux.py プロジェクト: Morphux/Morphux-IRC-Bot
 def     connect(self):
     self.s = Core(self.config)
コード例 #17
0
ファイル: ShowController.py プロジェクト: JailsonS/mvc_python
 def __init__(self):
     self.customers = Customers()
     self.showView = self.loadView("show")
     self.core = Core()
コード例 #18
0
ファイル: morphux.py プロジェクト: Josyann/Morphux-IRC-Bot
class Morphux:

    # Construct function
    # @param path of the config file (Optional)
    def __init__(self, path="/etc/morphux/configBot.json"):
        fd = open(path)
        self.config = json.load(fd)
        self.currentUsers = {}
        self.join = {}
        self.leave = {}
        self.quit = {}
        self.nickChange = {}
        self.before = {}
        self.after = {}
        self.commands = {}

    # Connect the bot to the server and the chan
    def connect(self):
        self.s = Core(self.config)
        if (self.config["identify"] != 0):
            self.s.identify()
        self.s.join()
        self.s.send(self.config["welcomeMessage"])

    # Main Loop
    def loop(self):
        while 1:
            line = self.s.getLine()
            before = 1
            print line
            self.getHeadersLine(line)
            if ("JOIN" in line):
                self.onJoin(line)
            elif ("PART" in line):
                self.onLeave(line)
            elif ("QUIT" in line):
                self.onQuit(line)
            elif ("NICK" in line):
                self.onNickChange(line)
            elif ("PRIVMSG" in line):
                infos = self.getInfo(line)
                for name, function in self.before.items():
                    print name
                    if (function(self, line) == 0):
                        before = 0
                if (before == 0):
                    self.s.CorePrint("Aborting treatement")
                elif (infos != False):
                    if (infos["command"] in self.commands):
                        self.commands[infos["command"]]["function"](self,
                                                                    infos)
                        print("New command [" + infos['nick'] + "]: " +
                              infos["command"])
                    else:
                        self.sendMessage(self.config["errorMessage"],
                                         infos["nick"])
            for name, function in self.after.items():
                function(self, line)

    # Send message
    # @param: string
    # @param: string (Optional)
    def sendMessage(self, string, user=False):
        if (user != False):
            self.s.send(user + ": " + string)
        else:
            self.s.send(string)

    # Get Line Information
    # @param: string
    def getInfo(self, line, force=0):
        infos = {}
        infos["fullLine"] = line
        args = line.split(":", 2)[2]
        args = args.split(" ")
        args = filter(None, args)
        if (args[0][0] != self.config["symbol"] and force == 0):
            return False
        if (force == 0):
            args[0] = args[0][1:]
        infos["command"] = args[0]
        args.remove(args[0])
        if (infos["command"] == "help"):
            self.showHelp(args)
            return False
        infos["args"] = args
        user = line.split(":", 2)[1]
        infos["fullUser"] = user.split(" ")[0]
        infos["nick"] = user.split("!", 2)[0]
        return infos

    # Load Modules
    # @param: path (Optional)
    def loadModules(self, path="modules"):
        res = {}
        import os
        lst = os.listdir(path)
        dir = []
        for d in lst:
            s = os.path.abspath(path) + os.sep + d
            if os.path.isdir(s) and os.path.exists(s + os.sep + "__init__.py"):
                dir.append(d)
        for d in dir:
            res[d] = __import__(path + "." + d + "." + d, fromlist=["*"])
            res[d] = getattr(res[d], d.title())
        self.modules = res
        self.getCommands()

    # Get modules in dictionnary
    def getCommands(self):
        commands = {}
        for name, klass in self.modules.items():
            self.s.CorePrint("Loading '" + name + "' module...")
            klass = klass()
            result = klass.command()
            commands = result["command"]
            pprint(commands)
            if ("onJoin" in result):
                for name, function in result["onJoin"].items():
                    self.join[name] = function
            if ("onLeave" in result):
                for name, function in result["onLeave"].items():
                    self.leave[name] = function
            if ("onQuit" in result):
                for name, function in result["onQuit"].items():
                    self.quit[name] = function
            if ("onNickChange" in result):
                for name, function in result["onNickChange"].items():
                    self.nickChange[name] = function
            if ("before" in result):
                for name, function in result["before"].items():
                    self.before[name] = function
            if ("after" in result):
                for name, function in result["after"].items():
                    self.after[name] = function
            for name, function in commands.items():
                commands[name] = function
            self.s.printOk("OK")
            self.commands.update(commands)

    # On User Join
    # @param: string
    def onJoin(self, line):
        user = line.split(" ")
        user[0] = user[0][1:]
        nickName = user[0].split("!")
        if (nickName[0] == '@'):
            nickName = nickName[1:]
            self.currentUsers[nickName] = {"isAdmin": 1}
        else:
            self.currentUsers[user[0].split("!")[0]] = True
        if (user[0].split("!")[0] == self.config['nick']):
            return
        for name, function in self.join.items():
            function(self, user[0].split("!")[0])

    # On Nick Change
    # @param: string
    def onNickChange(self, line):
        user = line.split(" ")
        user[0] = user[0][1:]
        userName = user[0].split("!")
        newNick = user[2][1:]
        if (userName[0] in self.currentUsers):
            del self.currentUsers[userName[0]]
            self.currentUsers[newNick] = True
        if (newNick == self.config['nick']):
            return
        for name, function in self.nickChange.items():
            function(self, userName[0], newNick)

    # Get Initial list of Users
    # @param: string
    def getHeadersLine(self, line):
        line = line.split("\n")
        for value in line:
            users = value.split(":")
            if (len(users) >= 2):
                details = users[1].split(" ")
                if (len(details) >= 2):
                    if (details[1] == "353"):
                        users = users[2].split(" ")
                        for nickName in users:
                            nickName = nickName.split("\r\n")[0]
                            nickName = nickName.split("\r")[0]
                            if (nickName[0] == '@'):
                                nickName = nickName[1:]
                                self.currentUsers[nickName] = {"isAdmin": 1}
                            else:
                                self.currentUsers[nickName] = True

    # On User Leave
    # @param: string
    def onLeave(self, line):
        user = line.split(" ")[0][1:]
        nickName = user.split("!")[0]
        if (nickName in self.currentUsers):
            del self.currentUsers[nickName]
        for name, function in self.leave.items():
            function(self, nickName)

    # On User QUIT
    # @param: string
    def onQuit(self, line):
        user = line.split(" ")[0][1:]
        nickName = user.split("!")[0]
        if (nickName in self.currentUsers):
            del self.currentUsers[nickName]
        for name, function in self.quit.items():
            function(self, nickName)

    # If User is connected
    # @param: string
    def userExists(self, nick):
        if (nick in self.currentUsers):
            return True
        else:
            return False

    # If User is Admin
    # @param: string
    def isAdmin(self, nick):
        if (self.userExists(nick)):
            if (self.currentUsers[nick] != True):
                if ('isAdmin' in self.currentUsers[nick]):
                    return True
        return False

    # Show Help for a command
    # @param: list
    def showHelp(self, args):
        if (len(args) != 0):
            if (args[0] in self.commands):
                usage = self.commands[args[0]]["usage"]
                help = self.commands[args[0]]["help"]
                self.sendMessage(args[0] + ": <" + usage + "> (" + help + ")")
            else:
                self.sendMessage("Can't find command " + args[0])
        else:
            help = ""
            for name in self.commands:
                help = help + name + " "
            self.sendMessage("Commands available: " + help)

    # Kick an user
    def kick(self, user, reason):
        self.s.kick(user, reason)
コード例 #19
0
    def __init__(self, config, root_path):
        Core.__init__(self, config, root_path)
        self.charactername = config.character
        self.owner = config.owner
        self.status = ""
        self.greetings_list = {}

        # Register Message Actions
        self.private_msg_handler = Reaction()
        self.private_msg_handler.add_action("EXCEPTION",
                                            self._hook_exception_handler)
        self.private_msg_handler.add_action("!join", self._hook_join_by_name)
        self.private_msg_handler.add_action("!leave", self._hook_leave)
        self.private_msg_handler.add_action("!add_admin", self._hook_add_admin)
        self.private_msg_handler.add_action("!remove_admin",
                                            self._hook_remove_admin)
        self.private_msg_handler.add_action("!admins", self._hook_admins)
        self.private_msg_handler.add_action("!channels", self._hook_channels)

        self.private_msg_handler.add_action("!status", self._hook_set_status)

        self.private_msg_handler.add_action("!save", self._hook_save_all)
        self.private_msg_handler.add_action("!load", self._hook_load_all)

        self.private_msg_handler.add_action("!invite",
                                            self._hook_invite_to_channel)
        self.private_msg_handler.add_action("!kick", self._hook_kick)
        self.private_msg_handler.add_action("!help", self._hook_help_page)

        self.private_msg_handler.add_action("!allusers",
                                            self._hook_list_all_users)

        self.private_msg_handler.add_action("!DIE", self._hook_die)

        self.private_msg_handler.add_action("!ch_info",
                                            self._hook_get_users_in_channel)
        self.private_msg_handler.add_action(
            "!debug_ors", self._order_list_of_open_private_channels)
        self.private_msg_handler.add_action(
            "!debug_cha", self._order_list_of_official_channels)
        self.private_msg_handler.add_action("!__", self._hook_sysinfo)

        self.owner_manpage.add_command("!add_admin <name>",
                                       "add a User to admins")
        self.owner_manpage.add_command("!remove_admin <name>",
                                       "remove User from admins")
        self.owner_manpage.add_command("!__", "system information")

        self.admin_manpage.add_command("!ch_info <channel>",
                                       "returns info of channel")
        self.admin_manpage.add_command("!join <channel>", "Bot joins channel")
        self.admin_manpage.add_command("!leave <channel>",
                                       "Bot leaves channel")
        self.admin_manpage.add_command("!status <text>",
                                       "Set Bots Status to text")
        self.admin_manpage.add_command("!invite <channel>, <user>",
                                       "invite user to channel")

        self.everyone_manpage.add_command("!channels",
                                          "returns a list of channels")
        self.everyone_manpage.add_command("!admins",
                                          "returns a list of admins")
        self.everyone_manpage.add_command(
            "!greetme <title:optional>",
            "bot will greet you, when you log in with the title")
        self.everyone_manpage.add_command("!dontgreetme",
                                          "bot will no longer greet you")