def process(result:'json',commands:list): ''' Takes the json and list of commands and processes them accordingly and returns the output. If there is an incorrect command,an error message will print. ''' Commands.createOutput(result,commands)
def subscribe_to_alarms(alarms, settings): # Did we subscribe to even one alarm? success = False # Connect to the server t = socket.socket(socket.AF_INET, socket.SOCK_STREAM) t.settimeout(RESPONSE_TIMEOUT) t.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) t.bind((settings['address'], settings['port'])) t.connect((settings['server_address'], settings['server_port'])) # Ask the server to subscribe us for each alarm for alarm in alarms: command_string = Commands.create_command_string(('B', alarm)) t.send(command_string) Log.debug('Subscription request for alarm "%s" sent.' % alarm) # Receive data command_string = t.recv(BUFFER_SIZE) # Print the command Log.debug('Got response "%s"' % command_string) # Parse the command command = Commands.parse_command(command_string) if command[0] == 'FB': Log.debug('Already subscribed to alarm "%s".' % alarm) success = True elif command[0] == 'S': Log.debug('Successfully subscribed to alarm "%s".' % alarm) success = True elif command[0] == 'FN': Log.error('Server says alarm "%s" does not exist.' % alarm) else: Log.error('Unable to parse response from server.') t.close() return success
def remove_subscription(ip, port, alarm_name): # TODO: This is global and should probably not be global subscriptions, alarm_queue # Does the alarm exist if alarm_name not in alarm_queue.names: return Commands.create_command_string(('FN', alarm_name)) # Try to delete the subscription client_obj = Client.Client(ip, port) if alarm_name in alarm_queue.names: if alarm_name in subscriptions: if any(c for c in subscriptions[alarm_name] if c == client_obj): try: index = subscriptions[alarm_name].index(client_obj) del subscriptions[alarm_name][index] except ValueError: # Not subscribed return Commands.create_command_string(('FB', alarm_name)) # Not subscribed else: return Commands.create_command_string(('FB', alarm_name)) else: # Not subscribed return Commands.create_command_string(('FB', alarm_name)) # Tell the client they've been removed from the list return Commands.create_command_string(('S', alarm_name))
def __getNorthAndGravityVectorsInSensorFrame(self, sensorId): command = Commands.getCommandAsChr(Commands.GET_NORTH_AND_GRAVITY_VECTORS_IN_SENSOR_FRAME) lengthOfReturnData = Commands.getReturnDataLength(Commands.GET_NORTH_AND_GRAVITY_VECTORS_IN_SENSOR_FRAME) format = Commands.getRetrunDataFormat(Commands.GET_NORTH_AND_GRAVITY_VECTORS_IN_SENSOR_FRAME) binaryCommand = self.__getWirelessBinaryCommand(command, sensorId) receivedData = self.__getRawDataAndRetryIfGetCommandFailed(sensorId,binaryCommand,lengthOfReturnData) return (self.__getFormatedData(receivedData,format))
def __init__(self): Config.config(self) self.activeDict = {} for channel in self.info['CHAN']: self.activeDict[channel] = {} Commands.redditAPI(self) Soaker.Soaker(self) self.Connect() self.Main()
def message(serv, source, target, text): host = Irc.get_host(source) Commands.Tracking.activity(source,target,serv) if target != serv.nick and source == '[email protected]' and 'tipped' in text and 'to dogesoak' in text.lower(): try: usr = text.split()[1] req = Request(serv, target, usr) val = int(text.split('much ',1)[1][2:].split(' ',1)[0]) try: Commands.soak(req,[str(val)]) except: req.say('An error occurred.') #req.serv.send('PRIVMSG','Doger','tip ') except: print 'soaker error' if Commands.lreq and target == serv.nick and source.split('!',1)[0] == 'Doger': Commands.balancerepl(text) if text[0] == '!' or target == serv.nick: if serv.is_ignored(host): print(serv.nick + ": (ignored) <" + Irc.get_nickname(source) + "> " + text) return print(serv.nick + ": <" + Irc.get_nickname(source) + "> " + text) t = time.time() score = serv.flood_score.get(host, (t, 0)) score = max(score[1] + score[0] - t, 0) + 4 if score > 40 and not serv.is_admin(source): serv.ignore(host, 240) serv.send("PRIVMSG", Irc.get_nickname(source), "You're sending commands too quickly. Your host is ignored for 240 seconds") return serv.flood_score[host] = (t, score) if text[0] == '!': text = text[1:] src = Irc.get_nickname(source) if target == serv.nick: reply = src else: reply = target if text.find(" ") == -1: command = text args = [] else: command, args = text.split(" ", 1) args = args.split(" ") if command[0] != '_': cmd = Commands.commands.get(command.lower(), None) if not cmd.__doc__ or cmd.__doc__.find("admin") == -1 or serv.is_admin(source): if cmd: req = Request(serv, reply, source) try: ret = cmd(req, args) except Exception as e: type, value, tb = sys.exc_info() traceback.print_tb(tb) req.reply(repr(e))
def __getTaredOrientationAsQuaternion(self, sensorId,needToReturnSensorId = True): command = Commands.getCommandAsChr(Commands.GET_TARED_ORIENTATION_AS_QUATERNION) format = Commands.getRetrunDataFormat(Commands.GET_TARED_ORIENTATION_AS_QUATERNION) lengthOfReturnData = Commands.getReturnDataLength(Commands.GET_TARED_ORIENTATION_AS_QUATERNION) binaryCommand = self.__getWirelessBinaryCommand(command, sensorId) receivedData = self.__getRawDataAndRetryIfGetCommandFailed(sensorId,binaryCommand,lengthOfReturnData) if needToReturnSensorId is True: return (self.__getFormatedData(receivedData,format)) else: return (self.__getFormatedDataWithoutSensorId(receivedData,format))
def __getUntaredOrientationAsQuaternion(self, sensorId = 0,needToReturnSensorId = True): command = Commands.getCommandAsChr(Commands.GET_UNTARED_ORIENTATION_AS_QUATERNION) lengthOfReturnData = Commands.getReturnDataLength(Commands.GET_UNTARED_ORIENTATION_AS_QUATERNION) format = Commands.getRetrunDataFormat(Commands.GET_UNTARED_ORIENTATION_AS_QUATERNION) binaryCommand = self.__getWirelessBinaryCommand(command, sensorId) receivedData = self.__getRawDataAndRetryIfGetCommandFailed(sensorId,binaryCommand,lengthOfReturnData) if needToReturnSensorId is True: return (self.__getFormatedData(receivedData,format)) else: #Note: starting byte is sensorId followed by data, need to remove index 0 if you dont want to get sensorId as return data return (self.__getFormatedData(receivedData,format))[1:]
def unloadExtension(name): name=[x for x in getExtensions() if x.lower()==name.lower()] if not len(name): return True name=name[0] global loadedExtensions module=[i for i in loadedExtensions if i.__name__==name] if len(module)!=1: return False module=module[0] loadedExtensions.remove(module) tools.delete_modules_from_dir(os.path.join("extensions", name)) LadderLogHandlers.unregister_package(module.__name__) Commands.unregister_package(module.__name__) sys.stderr.write("[EXTENSION] Unloaded extension "+module.__name__+"\n")
def __init__(self, state): self.commands = Commands(state) self.options = ['ignoreGravity', 'ignoreDrag', 'unattractable'] self.particleWeapons = { 'name': 'Particle', 'aimed': WeaponCursorAimed(state, 'Particle Aimed', delay=0.01), 'stationary': WeaponSpawnAtPosition(state, 'Particle stationary', delay=0.01), 'cursor': WeaponSpawnAtCursor(state, 'Particle at cursor', delay=0.01), 'options': Particle(state).values.getAllNameValue() } self.timeWeapons = { 'name': 'Time', 'aimed': WeaponSpawnAtCursor(state, 'Time Aimed', Timebubble), 'stationary': WeaponSpawnAtPosition(state, 'Time stationary', Timebubble), 'cursor': WeaponSpawnAtCursor(state, 'Time cursor', Timebubble), 'options': Timebubble(state, Vector(), Vector()).values.getAllNameValue() } self.gravityWeapons = { 'name': 'Attractor', 'aimed': WeaponCursorAimed(state, 'Gravity Aimed', Attractor), 'stationary': WeaponSpawnAtPosition(state, 'Gravity stationary', Attractor), 'cursor': WeaponSpawnAtCursor(state, 'Gravity cursor', Attractor), 'options': Attractor(state, Vector(), Vector()).values.getAllNameValue() } self.selectWeapon = self.particleWeapons self.state = state self.pressed = [] self.pressed_last_frame = [] self.mousebuttons = [False, False, False, False ,False, False] self.attractorTime = 0 self.commands.register('toggleHelp', K_F1, {'start': self.toggleHelp})
def __init__(self): self.graph = Graph.graph() self.listCities = Commands.listCitiesCmd(self.graph) self.getCityInfo = Commands.getCityInfoCmd(self.graph) self.getStats = Commands.getStatsCmd(self.graph) self.getMap = Commands.getMapCmd(self.graph) self.editDatabase = Commands.editDatabaseCmd(self.graph) self.writeJSON = Commands.writeJSON(self.graph) self.shortestRoute = Commands.findShortestRoute(self.graph) self.addJSON = Commands.addJSON(self.graph) self.quit = Commands.quitCmd(self.graph) self.handler = EventHandler.handler(self.listCities, self.getCityInfo, self.getStats, self.getMap, self.editDatabase, self.writeJSON, self.shortestRoute, self.addJSON, self.quit)
def load(): '''This function has to be called to load the configuration-file from disk to memory to be used by the application. ''' global __cfg if not check(): default() cfg = ConfigParser.RawConfigParser() cfg.read( os.path.join( __cfg_path, __cfg_file ) ) __cfg = { } __cfg[ 'Hosting' ] = { 'port': cfg.getint( 'Hosting', 'port' ), 'server': cfg.get( 'Hosting', 'server' ), 'max_conn': cfg.getint( 'Hosting', 'max_conn' ), } Commands.load()
def add_subscription(ip, port, alarm_name): # TODO: This is global and should probably not be global subscriptions, alarm_queue # Does the alarm exist if alarm_name not in alarm_queue.names: return Commands.create_command_string(('FN', alarm_name)) # Try to add the subscription client_obj = Client.Client(ip, port) if alarm_name in alarm_queue.names: if alarm_name in subscriptions: # Already subscribed if any(c for c in subscriptions[alarm_name] if c == client_obj): return Commands.create_command_string(('FB', alarm_name)) else: subscriptions[alarm_name].append(client_obj) else: subscriptions[alarm_name] = [client_obj] # Tell the client they've been added to the list return Commands.create_command_string(('S', alarm_name))
def __init__(self, parent, title=''): if hasattr(Globals.pref, 'searchwin_pos') and hasattr(Globals.pref, 'searchwin_size'): searchwin_pos = Globals.pref.searchwin_pos searchwin_size = Globals.pref.searchwin_size wx.Dialog.__init__(self, parent, -1, title, searchwin_pos, searchwin_size, style=wx.RESIZE_BORDER|wx.DEFAULT_DIALOG_STYLE) else: wx.Dialog.__init__(self, parent, -1, title, size=(600, 400), style=wx.RESIZE_BORDER|wx.DEFAULT_DIALOG_STYLE) self.Center() self.SetBackgroundColour(wx.SystemSettings.GetColour(wx.SYS_COLOUR_BTNFACE)) sizer = wx.BoxSizer(wx.VERTICAL) sizer1 = wx.BoxSizer(wx.HORIZONTAL) label = wx.StaticText(self, -1, tr("Search for:")) sizer1.Add(label, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 2) self.text = wx.TextCtrl(self, -1, "", style=wx.TE_PROCESS_ENTER) self.impact_check = wx.CheckBox(self, -1, tr("Impact Mode")) self.autoclose_check = wx.CheckBox(self, -1, tr("Auto Close")) sizer1.Add(self.text, 1, wx.ALL, 2) sizer1.Add(self.impact_check, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 2) sizer1.Add(self.autoclose_check, 0, wx.ALL|wx.ALIGN_CENTER_VERTICAL, 2) self.list = CheckList.List(self, columns=[ (tr("Function"), 300, 'left'), (tr("ShortCuts"), 120, 'left'), (tr("Impact"), 80, 'left'), ], style=wx.LC_REPORT | wx.SUNKEN_BORDER | wx.LC_SINGLE_SEL) self.commandar = Commands.getinstance() self.cmdbuf = {} self.load(self.commandar.search('')) sizer.Add(sizer1, 0, wx.EXPAND) sizer.Add(self.list, 1, wx.EXPAND, 2) btnCancel = wx.Button(self, wx.ID_CANCEL, tr("Cancel")) sizer.Add(btnCancel, 0, wx.ALIGN_CENTER, 2) wx.EVT_CLOSE(self, self.OnClose) wx.EVT_SIZE(self, self.OnSize) wx.EVT_BUTTON(self, wx.ID_CANCEL, self.OnClose) wx.EVT_TEXT(self.text, self.text.GetId(), self.OnChange) wx.EVT_KEY_DOWN(self.text, self.OnKeyDown) wx.EVT_LIST_ITEM_ACTIVATED(self.list, self.list.GetId(), self.OnEnter) wx.EVT_CHECKBOX(self.impact_check, self.impact_check.GetId(), self.OnCheckImpact) wx.EVT_CHECKBOX(self.autoclose_check, self.autoclose_check.GetId(), self.OnCheckAutoClose) self.impact_check.SetValue(Globals.pref.commands_impact) self.autoclose_check.SetValue(Globals.pref.commands_autoclose) Globals.mainframe.command_mode = True self.SetSizer(sizer) self.SetAutoLayout(True)
def listen(settings): # Create a socket and listen for packets sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.bind((settings['address'], settings['port'])) sock.listen(1) Log.debug('Listening on port %i' % settings['port']) # This is our main listening thread while True: # Accept incoming connection connection, address = sock.accept() server = address[0] + ':' + str(address[1]) Log.debug('Connection from %s' % server) # Receive data command_string = connection.recv(BUFFER_SIZE) # Print the command Log.debug('Received command %s from %s.' % (command_string, server)) # Parse the command command = Commands.parse_command(command_string) response = 'E general' if command: response = Commands.create_command_string(('F', command[1])) # Handle the alarm if command[0] == 'A': Log.debug('Alarm %s triggered.', command[1]) result = dispatch_alarm(command[1]) # Success if result: response = Commands.create_command_string(('S', command[1])) # Invalid command else: Log.error('Invalid command "%s" from server.', command[0]) # Invalid command else: Log.error('Invalid command from server.') connection.send(response) # Close the connection from the server connection.close() # Close the socket sock.close()
def main(): maybe_init_db() op = OptionParser(usage="usage: %prog [options] ladbr [arg1...]") op.add_option("-f", "--finished", dest="finished", action="store_true", help="show only finished tasks") op.add_option("-d", "--due", dest="due", help="specify a due date") op.add_option("-s", "--sort",dest="sort", default="due", help="sort by created, alpha, pri, due date") (options, args) = op.parse_args() if len(args) == 0: return handle_error("Must supply a command", op) command = args.pop(0) try: command = Commands.match(command, options, args) except Commands.ArgError, e: return handle_error(e.value, op)
def on_first_char(win, event): global _impact_mode, buf if _impact_mode: key = event.GetKeyCode() if key < 127: buf.append(chr(key)) showinfo(' '.join(buf)) Mixin.reload_obj(Commands) commandar = Commands.getinstance() s = commandar.impact_search(''.join(buf)) if len(s) == 1: #find a cmd showinfo(' '.join(buf + ['('+s[0][0]+')'])) cmd_id = s[0][-1] commandar.run(cmd_id) buf = [] elif len(s) == 0: buf = [] return True
def on_first_char(win, event): global _impact_mode, buf if _impact_mode: key = event.GetKeyCode() if key < 127: buf.append(chr(key)) showinfo(' '.join(buf)) Mixin.reload_obj(Commands) commandar = Commands.getinstance() s = commandar.impact_search(''.join(buf)) if len(s) == 1: #find a cmd showinfo(' '.join(buf + ['(' + s[0][0] + ')'])) cmd_id = s[0][-1] commandar.run(cmd_id) buf = [] elif len(s) == 0: buf = [] return True
def callback_choose_game_clue(bot, update): callback = update.callback_query log.info('callback_choose_mode called: %s' % callback.data) regex = re.search("(-[0-9]*)\*choosegameclue\*(.*)\*([0-9]*)", callback.data) cid, strcid, opcion, uid, struid = int( regex.group(1)), regex.group(1), regex.group(2), int( regex.group(3)), regex.group(3) if cid == -1: bot.edit_message_text("Cancelado", uid, callback.message.message_id) return game = Commands.get_game(cid) mensaje_edit = "Has elegido el grupo {0}".format(game.groupName) bot.edit_message_text(mensaje_edit, uid, callback.message.message_id) command_clue(bot, update, [opcion, cid, uid])
def Test(): import Abby import Commands filename = 'stuff.abby' abby = Abby.Abby() abby.Open(filename, False) print 'Test console...' stream = Console() print 'stream:', stream stream.writeline('hello!') print print 'Get some objects to export...' fish = abby.Get(exactname='fish') cmd = Commands.List(abby, fish) print cmd layout = cmd.Do() print layout.ob print print 'Test the stream factory...' filename = 'testcsv.txt' stream = Factory(filename, 'w') print 'stream:', stream print print 'Test writing to csv file...' status = stream.WriteFromLayout(layout) print status print print 'Test writing to tabdelim file...' filename = 'testtabs.txt' stream = Factory(filename, 'w', 'Tab') print 'stream:', stream status = stream.WriteFromLayout(layout) print status print abby.Close(False) # discard all changes
def account(instance, source, account): curtime = time.time() if account == "*": account = False nick = Irc.get_nickname(source, "") with Global.account_lock: for channel in Global.account_cache: if nick in Global.account_cache[channel]: if channel in Config.config["welcome_channels"] and not account and not Transactions.check_exists(nick) and (nick not in Global.welcome_list or Global.welcome_list[nick] + (60*10) < curtime): Global.welcome_list[nick] = curtime Irc.instance_send(instance, ("PRIVMSG", channel, "Welcome our newest Rogeteer - %s! Try &help, &rogerme and &faucet to get started!" % (nick)), priority = 20, lock = False) elif channel in Config.config["welcome_channels"] and account and Transactions.check_exists(nick) and (nick not in Global.welcome_list or Global.welcome_list[nick] + (60*10) < curtime): Global.welcome_list[nick] = curtime welcome_str = str(Commands.random_line('quotes_welcome')) Irc.instance_send(instance, ("NOTICE", nick, "Welcome back %s! %s" % (nick, welcome_str)), priority = 20, lock = False) Global.account_cache[channel][nick] = account Logger.log("w", "Propagating %s=%s into %s" % (nick, account, channel)) if account != None and account != False: Expire.bump_last(account)
def transform_op(surfaces, scale=None, radius=None, move=None, rotate=0, axis=(0, 0, 1), center=None, coordinateSystem=None): if len(surfaces) == 0: return import Matrix as M csys = coordinateSystem if csys is None: csys = surfaces[0].model.openState c = a = None need_center = not (scale is None and radius is None and rotate == 0) if need_center: if not center is None or not axis is None: import Commands as C c, a = C.parse_center_axis(center, axis, csys, 'surface transform')[:2] if not c is None: ctf = M.xform_matrix(csys.xform) c = M.apply_matrix(ctf, c) if not a is None: ctf = M.xform_matrix(csys.xform) a = M.apply_matrix_without_translation(ctf, a) if c is None: from Measure import inertia axes, d2, c = inertia.surface_inertia(surfaces) # global coords if c is None: ctf = M.xform_matrix(csys.xform) M.apply_matrix_without_translation(ctf, (0, 0, 0)) import transform if scale is None and not radius is None: rmax = max(transform.surface_radius(p, c) for p in surfaces) scale = radius / rmax if rmax > 0 else 1 transform.transform_surface_pieces(surfaces, scale, rotate, a, c, move)
def delete_word(update, context): data = update.message.text if 'deleteing_word' not in context.user_data: context.user_data['deleteing_word'] = data TYPING(update) ci = JDTools.get_word(data) if (ci is None): REPLY(update, '%s 词不存在' % data) context.user_data.clear() return -1 pinyins = list(ci.pinyins()) if len(pinyins) == 1: context.user_data['deleteing_word_pinyin'] = " ".join(pinyins[0]) REPLY(update, "彻底删除 %s 词" % (context.user_data['deleteing_word'])) CHOOSE(update, '确定要删除吗', ['是的']) else: CHOOSE(update, '请选择要删除的读音', [" ".join(pinyin) for pinyin in pinyins]) elif 'deleteing_word_pinyin' not in context.user_data: context.user_data['deleteing_word_pinyin'] = data REPLY(update, "删除 %s 词读音 %s" % (context.user_data['deleteing_word'], data)) CHOOSE(update, '确定要删除吗', ['是的']) else: word = context.user_data['deleteing_word'] pinyin = context.user_data['deleteing_word_pinyin'] TYPING(update) result = Commands.safe_delete_word(word, pinyin) REPLY(update, "\n".join(MARK(result))) context.user_data.clear() LOG(result) return -1 return 4
def command_remove(bot, update, args): log.info('command_pass called') uid = update.message.from_user.id cid = update.message.chat_id game = Commands.get_game(cid) elegido = -1 if check_invalid_pick(args) else int(args[0]) #bot.send_message(game.cid, "{} {}".format(elegido, len(game.board.state.fadedarcanasOnTable)+1)) fadeded_on_table = len(game.board.state.fadedarcanasOnTable) + 1 if (elegido > 0) and (elegido < fadeded_on_table): arcana_quitada = game.board.state.fadedarcanasOnTable.pop(elegido - 1) bot.send_message( game.cid, "Se ha removido la arcana *{}* con habilidad *{}*".format( arcana_quitada["Título reverso"], arcana_quitada["Texto reverso"]), ParseMode.MARKDOWN) else: bot.send_message( game.cid, "Debes ingresar un numero del 1 a {} (incluido)".format( fadeded_on_table - 1), ParseMode.MARKDOWN)
def delete_char(update, context): data = update.message.text if 'deleteing_char' not in context.user_data: context.user_data['deleteing_char'] = data TYPING(update) zi = JDTools.get_char(data) if (zi is None): REPLY(update, '%s 字不存在' % data) context.user_data.clear() return -1 pinyins = list(zi.pinyins()) if len(pinyins) == 1: context.user_data['deleteing_char_pinyin'] = pinyins[0] REPLY(update, "彻底删除 %s 字" % (context.user_data['deleteing_char'])) CHOOSE(update, '确定要删除吗', ['是的']) else: CHOOSE(update, '请选择要删除的读音', pinyins) elif 'deleteing_char_pinyin' not in context.user_data: context.user_data['deleteing_char_pinyin'] = data REPLY(update, "删除 %s 字读音 %s" % (context.user_data['deleteing_char'], data)) CHOOSE(update, '确定要删除吗', ['是的']) else: char = context.user_data['deleteing_char'] pinyin = context.user_data['deleteing_char_pinyin'] TYPING(update) result = Commands.safe_delete_char(char, pinyin) REPLY(update, "\n".join(MARK(result))) context.user_data.clear() LOG(result) return -1 return 5
def test_function_export__after_function_import__with_file_shapes_groups_and_ornaments_should_yield_same_file(self): canvas = Canvas() canvas.pack() _input = Commands(canvas, []).import_('shapes_groups_and_ornaments.txt') self.assertEqual(8, len(canvas.find_all())) groups = [] shapes = [] for shape in _input: if type(shape) == Group: groups.append(shape) else: shapes.append(shape) output = Commands(canvas, shapes).export_(shapes, groups) with open('shapes_groups_and_ornaments.txt') as f: _input = f.read() self.assertEqual(len(output.split('\n')), len(_input.split('\n')))
def command_guess(bot, update, args): try: log.info('command_guess called') #Send message of executing command cid = update.message.chat_id uid = update.message.from_user.id game = Commands.get_game(cid) if (len(args) < 1 or game.board.state.fase_actual != "Adivinando" or uid != game.board.state.active_player.uid): # and uid not in ADMIN: bot.send_message( game.cid, "No es el momento de adivinar, no eres el que tiene que adivinar o no has ingresado algo para adivinar", ParseMode.MARKDOWN) return args_text = ' '.join(args) if args_text.lower() == game.board.state.acciones_carta_actual.lower(): #Adivino correctamente! Aumento el puntaje game.board.state.progreso += 1 bot.send_message(game.cid, "*CORRECTO!!!*", ParseMode.MARKDOWN) game.board.discards.append(game.board.state.acciones_carta_actual) JustOneController.start_next_round(bot, game) else: #Preguntar al revisor mensaje = "*Revisor* {0} confirme por favor!".format( helper.player_call(game.board.state.reviewer_player)) bot.send_message(game.cid, mensaje, ParseMode.MARKDOWN) chat_donde_se_pregunta = uid opciones_botones = {"correcto": "Si", "incorrecto": "No"} helper.simple_choose_buttons( bot, cid, game.board.state.reviewer_player.uid, game.board.state.reviewer_player.uid, "reviewerconfirm", "¿Es correcto lo que se adivinó ({1})? Palabra: {0}".format( game.board.state.acciones_carta_actual, args_text), opciones_botones) except Exception as e: bot.send_message(uid, str(e)) log.error("Unknown error: " + str(e))
def reverse_core_select(self): if (Settings.LINKED): if (Settings.core_dir == 0): self.coreReverse_pushButton.setIcon(Settings.reverse) self.frameReverse_pushButton.setIcon(Settings.reverse) else: self.coreReverse_pushButton.setIcon(Settings.forward) self.frameReverse_pushButton.setIcon(Settings.forward) Commands.reverse_core_select(self) Commands.reverse_frame_select(self) else: if (Settings.core_dir == 0): self.coreReverse_pushButton.setIcon(Settings.reverse) else: self.coreReverse_pushButton.setIcon(Settings.forward) Commands.reverse_core_select(self)
def run(self): Commands.extract_lights() on_stat = False sleep(5) Commands.deploy_lights() on_stat = True while True: for x in range(Settings.cycle_time * 60): sleep(1) if not Settings.cycle_running: on_stat = False break if on_stat: Commands.extract_lights() on_stat = False else: Commands.deploy_lights() on_stat = True if not Settings.cycle_running: break
def command_roll(bot, update, args): import Commands if args: text_tirada = '¡Tu tirada de ' + ' '.join(args) else: text_tirada = '¡Tu tirada' cid = update.message.chat_id uid = update.message.from_user.id tirada = random.randint(1, 101) sumar = sum([int(s.replace('+', '')) for s in args if "+" in s]) restar = sum([int(s.replace('-', '')) for s in args if "-" in s]) if tirada > 97: tirada2 = random.randint(1, 101) tirada += tirada2 + sumar - restar text_tirada += ' es *%s!*' % (str(tirada)) elif tirada < 4: tirada2 = random.randint(1, 101) tirada += -tirada2 + sumar - restar text_tirada += ' es *%s!*' % (str(tirada)) elif tirada == 27: text_tirada += ' es *Épico*!' else: text_tirada += ' es *%s!*' % (str(tirada + sumar - restar)) bot.send_message(cid, "%s" % (text_tirada), ParseMode.MARKDOWN) #ot.send_message(cid, "Se sumo {}. Se resto {}".format(sumar, restar), ParseMode.MARKDOWN) # Si hay un juego creado guardo en el historial game = Commands.get_game(cid) if game and uid in game.playerlist: #bot.send_message(cid, "Grabo en base de datos", ParseMode.MARKDOWN) player = game.playerlist[uid] texthistory = "Jugador *%s* - %s" % (player.name, text_tirada) game.history.append("%s" % (texthistory))
def reply_options(bot, update): user = update.message.from_user user_reply = update.message.text if (user_reply == 'Leyes'): url = Websites.LAWS_SITES[InformationCommand.index_laws] custom_keyboard = [['Mas_informacion', 'Cancelar']] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) bot.sendMessage(update.message.chat_id, text=url, reply_markup=ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, resize_keyboard=True)) return REPLY_LEYES elif (user_reply == 'Reformas'): InformationCommand.reformas(bot, update) elif (user_reply == 'Partidos'): custom_keyboard = [['PP', 'PSOE', 'Podemos', 'Ciudadanos'], ['IU', 'ERC', 'CDC', 'PNV']] reply_markup = telegram.ReplyKeyboardMarkup(custom_keyboard) bot.sendMessage(update.message.chat_id, text='Selecciona uno de los partidos políticos:', reply_markup=ReplyKeyboardMarkup(custom_keyboard, one_time_keyboard=True, resize_keyboard=True)) return PARTIDOS elif (user_reply == 'Graficos'): InformationCommand.graficos(bot, update) elif (user_reply == 'Estadisticas'): InformationCommand.estadisticas(bot, update) elif (user_reply == 'Busqueda'): InformationCommand.busqueda(bot, update) bot.sendMessage(update.message.chat_id, text='Introduce un criterio de búsqueda:') return BUSQUEDA elif (user_reply == 'Cancelar'): pass else: bot.sendMessage(update.message.chat_id, text='Disculpa, no te he entendido :(') return Commands.informacion(bot, update) return ConversationHandler.END
def constructCommand(self, ontology): import os """Return the command (includes constructing it if necessary) to invoke the reasoner.""" self.args = commands.get_system_command(self.name, ontology) ending = None if ontology.resolve: ending = Filemgt.read_config(self.name, 'all_ending') if ending is None: ending = "" ending = ending + Filemgt.read_config(self.name, 'ending') self.output_file = Filemgt.get_full_path(ontology.name, folder=Filemgt.read_config( 'output', 'folder'), ending=ending) self.ontology = ontology logging.getLogger(__name__).debug('Reasoner command: ' + str(self.args)) return self.args
def lose(self, completion=None, boosters=None): """ Attemps to lose level. :return: True in case of success, False otherwise. :rtype: bool """ if completion is None: completion = None if boosters is not None: for booster in boosters: if not isinstance(booster, Boosters.Booster): booster = self.__client.boosters[booster] if booster.count == 0: booster.buy() booster.spend() cmd = Commands.LoseLevelCommand(self.__client, self.qualified_id, completion, boosters) Net.send(cmd) return not cmd.rejected
def clip_op(volumes, center=None, coordinateSystem=None, radius=None, color=None, mesh=False, replace=True): if not center is None: import Commands as C center, axis, csys = C.parse_center_axis(center, None, coordinateSystem, 'surface clip') import clip for v in volumes: if center is None or coordinateSystem is None: c = center else: import Matrix as M c = M.xform_xyz(center, coordinateSystem.xform, v.openState.xform) clip.spherical_clip(v, c, radius, color, mesh, replace)
def command_propose(bot, update, args, user_data): try: cid = update.message.chat_id uid = update.message.from_user.id if len(args) > 0: # Obtengo todos los juegos de base de datos de los que usan clue mensaje_error = "" games_tipo = MainController.getGamesByTipo('SayAnything') btns, cid = get_choose_game_buttons( games_tipo, uid, allow_only="", restrict="active_player", fase_actual='Proponiendo Pistas', button_value='prop', callback_command='choosegamepropSA') user_data[uid] = ' '.join(args) if len(btns) != 0: if len(btns) == 1: #Si es solo 1 juego lo hago automatico game = Commands.get_game(cid) add_propose(bot, game, uid, ' '.join(args)) else: txtBoton = "Cancel" datos = "-1*choosegameclue*" + "prop" + "*" + str(uid) btns.append( [InlineKeyboardButton(txtBoton, callback_data=datos)]) btnMarkup = InlineKeyboardMarkup(btns) bot.send_message( uid, "En cual de estos grupos queres mandar la pista?", reply_markup=btnMarkup) else: mensaje_error = "No hay partidas en las que puedas hacer /resp" bot.send_message(uid, mensaje_error) except Exception as e: bot.send_message(uid, str(e)) log.error("Unknown error: " + str(e))
def run(self): Commands.clear_lights() sleep(1) Commands.deploy_lights() while True: for x in range(Settings.cycle_time*60): sleep(1) if not Settings.cycle_running: break Commands.clear_lights() for x in range(Settings.cycle_time*60): sleep(1) if not Settings.cycle_running: break Commands.deploy_lights() if not Settings.cycle_running: break
def command_guess(bot, update, args): cid = update.message.chat_id game = Commands.get_game(cid) # TODO poner restriccion del jugador activo #if game.board.state.fase_actual != "Predecir" or uid == game.board.state.active_player.uid: if game.board.state.fase_actual != "Predecir": bot.send_message( game.cid, "Fase actual *{}*".format(game.board.state.fase_actual), ParseMode.MARKDOWN) bot.send_message( game.cid, "No es el momento de adivinar o no eres el que tiene que adivinar", ParseMode.MARKDOWN) return elegido = -1 if check_invalid_pick(args) else int(args[0]) if elegido > 0 and elegido < 8: ArcanaController.resolve(bot, game, elegido) else: bot.send_message(game.cid, "El número debe ser entre 1 y 7", ParseMode.MARKDOWN)
def send_vote_buttons(bot, game, uid, message_id=None): mensaje = "Debes votar sobre las respuestas en el grupo *{1}*.\nEl jugado activo es: *{2}*\nLa frase es: *{0}*".format( game.board.state.acciones_carta_actual, game.groupName, game.board.state.active_player.name) opciones_botones = {} i = 0 for vote in game.board.state.ordered_votes: votos_a_respuesta = [ (val[0], val[1], val[2]) for index, val in enumerate(game.board.state.votes_on_votes) if val[2] == i ] jugadores_votos_a_respuesta = "".join( ("({})".format(o[0].name[:2])) for o in votos_a_respuesta) jugadores_votos_a_respuesta = jugadores_votos_a_respuesta if len( jugadores_votos_a_respuesta ) < 24 else jugadores_votos_a_respuesta[:20] + '...' opciones_botones[i] = "{0} {1}".format(jugadores_votos_a_respuesta, vote.content['propuesta']) i += 1 opciones_botones[-1] = "Terminar" btnMarkup = Commands.simple_choose_buttons_only_buttons( bot, game.cid, uid, "voteRespuestaSA", opciones_botones) if message_id: bot.edit_message_text( "{0}\n*Ingresa/Modifica* tus votos".format(mensaje), chat_id=uid, message_id=message_id, parse_mode=ParseMode.MARKDOWN, reply_markup=btnMarkup) else: bot.send_message(uid, "{0}*Ingresa/Modifica* tus votos".format(mensaje), parse_mode=ParseMode.MARKDOWN, reply_markup=btnMarkup)
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")
async def on_message(message): # This is an object. Name should be fetched with .name, not str(author)! author = message.author # Adds a reaction to messages at random RandomNum = CTRNG.updaterng() if RandomNum['bool']: Reactions = [emoji.emojize(":whale:"), emoji.emojize(":dolphin:")] Reaction = Reactions[RandomNum['num'] % 2] await client.add_reaction(message, Reaction) # This iterates over my dictionary of commands, imported from Commands. # The keys are the commands, and what the message needs to start with. # All of the functions in EmbedCommands return a discord.Embed object for command, function in EmbedCommands.items(): if message.content.startswith(command): EM = function(author, message) EM.set_footer(text=message.content) await client.send_message(message.channel, embed=EM) # Example: !1st !2nd !3rd TimeCommandREGEX = re.compile("!\d+[nsrt][tdh]|!-\d+[nsrt][tdh]") if TimeCommandREGEX.match(message.content.split(" ")[0]): EM = Commands.time(author, message) EM.set_footer(text=message.content) await client.send_message(message.channel, embed=EM)
def p_set_stmt(p): ## '''set : SET objectrefs property TO STRING''' ## obj = p[2] ## propname = p[3] ## propvalue = p[5] ## p[0] = Commands.Set(abby, obj, propname, propvalue) ## '''set : SET property TO STRING''' # '''set_stmt : SET property TO propvalue''' '''set_stmt : SET attributeref TO propvalue | attributeref EQUALS propvalue ''' # limit to attributerefs and propvalues for now - # setting an objectref to something could come later n = len(p.slice) if (n == 5): attrib = p[2] propvalue = p[4] else: attrib = p[1] propvalue = p[3] # p[0] = Commands.Set(abby, obj, prop, propvalue) p[0] = Commands.Set(abby, attrib, propvalue) log.debug('p_set_stmt: %s', p[0])
def callback_finish_config_justone(bot, update): log.info('callback_finish_config_justone called') callback = update.callback_query try: regex = re.search("(-[0-9]*)\*choosedicc\*(.*)\*([0-9]*)", callback.data) cid, strcid, opcion, uid, struid = int( regex.group(1)), regex.group(1), regex.group(2), int( regex.group(3)), regex.group(3) mensaje_edit = "Has elegido el diccionario: {0}".format(opcion) try: bot.edit_message_text(mensaje_edit, cid, callback.message.message_id) except Exception as e: bot.edit_message_text(mensaje_edit, uid, callback.message.message_id) game = Commands.get_game(cid) game.configs['diccionario'] = opcion finish_config(bot, game, opcion) except Exception as e: bot.send_message(ADMIN[0], 'No se ejecuto el comando debido a: ' + str(e)) bot.send_message(ADMIN[0], callback.data)
def update_coords(self): """Update WCS and MCS""" try: focus = self.focus_get() except: focus = None if focus is not self.xwork: self.xwork.delete(0, Tk.END) self.xwork.insert(0, cmd.padFloat(OCV.drozeropad, OCV.CD["wx"])) if focus is not self.ywork: self.ywork.delete(0, Tk.END) self.ywork.insert(0, cmd.padFloat(OCV.drozeropad, OCV.CD["wy"])) if focus is not self.zwork: self.zwork.delete(0, Tk.END) self.zwork.insert(0, cmd.padFloat(OCV.drozeropad, OCV.CD["wz"])) self.xmachine["text"] = cmd.padFloat(OCV.drozeropad, OCV.CD["mx"]) self.ymachine["text"] = cmd.padFloat(OCV.drozeropad, OCV.CD["my"]) self.zmachine["text"] = cmd.padFloat(OCV.drozeropad, OCV.CD["mz"])
def run(self): Commands.clear_lights() sleep(1) while Settings.cycle_running: Commands.deploy_lights(Settings.commands_list) for x in range(Settings.cycle_time * 60): sleep(1) if not Settings.cycle_running: break if Settings.cycle_running: Commands.clear_lights() for x in range(Settings.cycle_time * 60): sleep(1) if not Settings.cycle_running: break
def test_things(self): self.assertEquals( Commands.CreateAccount( "1, AKelly, password, Null, Null, Andrew, Kelly, 262-262-2626," " 414-414-4141, 5698"), "Account successfully created.") user = User user.permission = 1 user2 = User user2.databaseID = 45 self.assertEquals( Commands.DeleteAccount(user.permission, user2.databaseID), user2.username + "'s account has " "been deleted.") user3 = User self.assertEquals(Commands.EditAccount(user.permission, user3), "Account has been edited.") self.assertEquals( Commands.CreatCourse("CourseName, CourseNumber", "Course created.")) self.assertEquals(Commands.Email("This is the email"), "Email sent.") self.assertEquals(Commands.AccessData("table name"), "data") #ALLL THE DAtA
def read(self): """ Marks message as read. """ return not Net.send( Commands.ReadMessageCommand(self.__client, self.__id)).rejected
def updatePlayerMainKeyboard(self, bot, player): Commands.sendPlayerMainKeyboard(bot, player, GameStrings.GAME_STATUS_MESSAGE_KEYBOARD_UPDATED)
class Control: def __init__(self, state): self.commands = Commands(state) self.options = ['ignoreGravity', 'ignoreDrag', 'unattractable'] self.particleWeapons = { 'name': 'Particle', 'aimed': WeaponCursorAimed(state, 'Particle Aimed', delay=0.01), 'stationary': WeaponSpawnAtPosition(state, 'Particle stationary', delay=0.01), 'cursor': WeaponSpawnAtCursor(state, 'Particle at cursor', delay=0.01), 'options': Particle(state).values.getAllNameValue() } self.timeWeapons = { 'name': 'Time', 'aimed': WeaponSpawnAtCursor(state, 'Time Aimed', Timebubble), 'stationary': WeaponSpawnAtPosition(state, 'Time stationary', Timebubble), 'cursor': WeaponSpawnAtCursor(state, 'Time cursor', Timebubble), 'options': Timebubble(state, Vector(), Vector()).values.getAllNameValue() } self.gravityWeapons = { 'name': 'Attractor', 'aimed': WeaponCursorAimed(state, 'Gravity Aimed', Attractor), 'stationary': WeaponSpawnAtPosition(state, 'Gravity stationary', Attractor), 'cursor': WeaponSpawnAtCursor(state, 'Gravity cursor', Attractor), 'options': Attractor(state, Vector(), Vector()).values.getAllNameValue() } self.selectWeapon = self.particleWeapons self.state = state self.pressed = [] self.pressed_last_frame = [] self.mousebuttons = [False, False, False, False ,False, False] self.attractorTime = 0 self.commands.register('toggleHelp', K_F1, {'start': self.toggleHelp}) def pre_event(self): return self.mousebuttons = [False, False, False, False ,False, False] def handle_event(self, event): if event.type == pygame.MOUSEBUTTONDOWN: self.mousebuttons[event.button] = True if event.type == pygame.MOUSEBUTTONUP: self.mousebuttons[event.button] = False def multiplyModificators(self, value): if self.pressed[K_LCTRL] and self.pressed[K_LSHIFT]: return value * 1000 elif self.pressed[K_LCTRL]: return value * 100 elif self.pressed[K_LSHIFT]: return value * 10 return value def frame(self): self.pressed_last_frame = self.pressed self.pressed = self.state.pygame.key.get_pressed() relative = self.state.pygame.mouse.get_rel() self.commands.handle() if self.pressed[K_LCTRL]: self.state.block_cursor = True else: self.state.block_cursor = False for x in xrange(0, K_9 - K_0 + 1): if self.pressed[K_0 + x]: self.selectSlot(x) if self.pressed[K_w]: self.state.camera.forward() self.state.movement.up() if self.pressed[K_s]: self.state.camera.back() self.state.movement.down() if self.pressed[K_a]: self.state.camera.left() self.state.movement.left() if self.pressed[K_d]: self.state.movement.right() self.state.camera.right() if self.mousebuttons[5] or self.pressed[K_e]: self.state.pointerPull = self.state.pointerPull + self.multiplyModificators(10) if self.mousebuttons[4] or self.pressed[K_q]: self.state.pointerPull = self.state.pointerPull - self.multiplyModificators(10) if self.pressed[K_t]: self.state.physics.clearAttractors() if self.pressed[K_y]: self.state.physics.clearParticles() if self.pressed[K_v]: self.state.physics.clearTimebubbles() if self.pressed[K_g]: self.state.gametimeScale = self.state.gametimeScale - self.multiplyModificators(0.05) if self.state.gametimeScale <= 0: self.state.gametimeScale = 0.05 if self.pressed[K_h]: self.state.gametimeScale = self.state.gametimeScale + self.multiplyModificators(0.05) if self.state.block_cursor: self.state.camera.rotate_pitch(relative[1]) self.state.camera.rotate_yaw(relative[0]) else: self.state.mouse.frame(relative) if self.mousebuttons[1]: self.spawnSelectedAimed() if self.mousebuttons[3]: self.spawnSelectedCursor() if self.pressed[K_SPACE]: self.spawnSelectedStationary() def selectSlot(self, value): if value == 1: self.selectWeapon = self.particleWeapons if value == 2: self.selectWeapon = self.gravityWeapons if value == 3: self.selectWeapon = self.timeWeapons if value == 4: self.toggleOption('ignoreGravity') if value == 5: self.toggleOption('ignoreDrag') if value == 6: self.toggleOption('unattractable') def particleSetOptions(self, particle): for x in self.selectWeapon['options']: particle.values.set(x, self.selectWeapon['options'][x]) def spawnSelectedAimed(self): self.selectWeapon['aimed'].fire() self.particleSetOptions(self.selectWeapon['aimed'].particle) def spawnSelectedStationary(self): self.selectWeapon['stationary'].fire() self.particleSetOptions(self.selectWeapon['stationary'].particle) def spawnSelectedCursor(self): self.selectWeapon['cursor'].fire() self.particleSetOptions(self.selectWeapon['cursor'].particle) def toggleOption(self, option): self.selectWeapon['options'][option] = not self.selectWeapon['options'][option] def toggleHelp(self): self.state.showHelp = not self.state.showHelp
def InvalidCommand(command, player, ip, access, *args): # Check if the command is valid #### if not player in Player.players: log.error("Player „"+player+"“ doesn't exist.") Armagetronad.PrintPlayerMessage(player, Messages.PlayerNotExist, Messages.PlayerColorCode) return command=command[1:] if command.strip()=="": if "buffer" in Player.players[player].data: Player.players[player].data["buffer"].append(" ".join(args) ) else: Player.players[player].data["buffer"]=[" ".join(args)] Armagetronad.PrintPlayerMessage(player," ".join(args) ) return saved_command=command command=[realcommand for realcommand in Commands.getCommands() if realcommand.lower()==command] if len(command)>1: log.warning("More than one function for command "+command[0]+". Chosing 1st one.") elif len(command)<1: Armagetronad.PrintPlayerMessage(player, Messages.CommandNotFound.format(command=saved_command) ) return command=command[0] if command in Commands.disabled: Armagetronad.PrintPlayerMessage(player, Messages.DisabledCommand) return if Global.state in Commands.not_in_state: if command in Commands.not_in_state[Global.state]: Armagetronad.PrintPlayerMessage(player, Messages.WrongState.format(command=command) ) return if Global.state in Commands.only_in_state: for state, commands in Commands.only_in_state.items(): if command in commands and Global.state!=state: Armagetronad.PrintPlayerMessage(player, Messages.WrongState.format(command=command) ) return if not AccessLevel.isAllowed(command,access): Armagetronad.PrintPlayerMessage(player, Messages.NotAllowed.format(command=command) ) return if not Commands.checkUsage(command, access, *args): Armagetronad.PrintPlayerMessage(player, Commands.getHelp(command,access)) return # Process command #### def ProcessCommand(command, args): global runningCommands args=(access,player) + args try: #imp.reload(sys.modules[Commands.commands[command].__module__]) Commands.commands[command](*args) except Exception as e: raise e try: runningCommands.remove(threading.current_thread() ) except: log.debug("Command thread already removed. Command:"+command) pass if command=="reload_script": # we need to do this here raise Global.ReloadException() t=Thread(target=ProcessCommand, args=(command, args), name="HandleCommand"+command.capitalize() ) t.daemon=True global runningCommands runningCommands.append(t) t.start()
def find_penny_comment(flat_comments, processing, mods): global shutdown # Don't care about where the comments are so flatten the comment tree for comment in flat_comments: # Divide the body of all of the comments so we can scan each line correctly if comment.id not in processing: continue replied = False response = [] commentauthor = comment.author wholecomment = comment.body list = wholecomment.splitlines(True) reply = '' for current in list: # Looking at each line of a body comment turn it lower case and cut out v2 current = current.lower() current = current.replace("v2", "") # Scan for mention of pennybot and respond if "pennybot," not in current: continue print("Found a Penny comment at: " + time.asctime(time.localtime(time.time()))) lookingfor = "pennybot," # Remove pennybot from the string start scanning for response indexcount = current.index(lookingfor) + 9 current = current.lstrip(current[:indexcount]) current = current.strip() replied = True if current.startswith("suggestion"): reply ="Thank you for the command suggestions! \n Creator! /u/Weerdo5255 ! Someone has made an excellent suggestion for a command! \n (PennyBotV2 has saved this suggestion, even if the creator does not respond!)" file = open("Suggestions.txt", "a") file.write(str(wholecomment) + "FROM:" + str(commentauthor) + "\n") file.close() #Emergency shutdown elif current.startswith("shutdown"): print(commentauthor) if commentauthor in mods or commentauthor == "Weerdo5255": reply = "Emergency Shutdown Initiated! Bye!" shutdown = True else: reply = "You are not Pyrrha!" else: reply = Commands.penny_commands(current) response.append(reply) if replied: print(comment.submission.permalink) print(response) string = "" for x in response: string += x + " \n \n" comment.reply(string) db = sqlite3.connect("Processed.db") cursor = db.cursor() cursor.execute('INSERT INTO Processed VALUES (?, ?, ?, ?, ?, ?)', (str(comment.id), int(comment.created_utc), str(comment.body), str(comment.author), str(replied), str(reply))) cursor.execute("DELETE FROM Processed WHERE time <= strftime('%s') - 86400 * 2;") db.commit() return comment.id
def on_message(message): # when a message is recieved it is stored in the message object if message.author == client.user: #so the bot doesnt respond to itself return with open('USERS.json') as file: # reading users database into 'people' object people = json.load(file) author = str(message.author).lower() if author not in people['users']: # If the message author is not in the database people['users'][author] = {'level' : 0,'blacklist' : False} # create author in user database and write them to the file with open('USERS.json', 'w') as outfile: json.dump(people, outfile) print('Added ' + author + ' to database.') if message.content.startswith(botPrefix): # If message start with the botPrefix userInput = message.content.split() if userInput[0][1:] in Commands.commandList : # if it matches a command in the commandList if restrict == False or (restrict and people['users'][author]['level'] >= 2): # If commands are restricted to ONLY moderators if people['users'][author]['blacklist']: # if the user that send the message is on the blacklist if userInput[0][1:] in Commands.commandList: #if the user also has entered a command response = 'You are blacklisted' else: if userInput[0] == botPrefix + 'commands': response = Commands.commands() if userInput[0] == botPrefix + "blacklist" and people['users'][author]['level'] >= 2: # blacklist [view|add|remove] [_NAME_] response = Commands.blacklist(userInput) if userInput[0] == botPrefix + 'fish': response = Commands.fish(author,userInput) if userInput[0] == botPrefix + 'driveby': client.send_message(message.channel,Commands.driveby(),'test', tts='True') if userInput[0] == botPrefix + 'dice': response = Commands.dice(userInput) if userInput[0] == botPrefix + 'countdown': response = Commands.countdown(userInput) if userInput[0] == botPrefix + 'islive': response = Commands.islive(userInput) if userInput[0] == botPrefix + 'twitch': response = Commands.twitch(userInput) if userInput[0] == botPrefix + 'throw': response = Commands.throw(userInput) if userInput[0] == botPrefix + 'hug': response = Commands.hug(userInput) if userInput[0] == botPrefix + 'feat': response = Commands.feat(userInput) if userInput[0] == botPrefix + 'joy': response = Commands.joy(userInput) if userInput[0] == botPrefix + 'kidder': response = Commands.kidder(userInput) if userInput[0] == botPrefix + '8ball': response = Commands.eightBall() if userInput[0] == botPrefix + 'lenny': response = Commands.lenny(userInput) if userInput[0] == botPrefix + 'hayden': response = Commands.hayden(userInput) if userInput[0] == botPrefix + "shane": response = Commands.shane() if userInput[0] == botPrefix + 'hello': response = Commands.hello(author,userInput) if userInput[0] == botPrefix + "var": response = Commands.var(userInput) else: response = 'Commands have been restricted to Moderaters only.' client.send_message(message.channel,response)
op.add_option("-d", "--due", dest="due", help="specify a due date") op.add_option("-s", "--sort",dest="sort", default="due", help="sort by created, alpha, pri, due date") (options, args) = op.parse_args() if len(args) == 0: return handle_error("Must supply a command", op) command = args.pop(0) try: command = Commands.match(command, options, args) except Commands.ArgError, e: return handle_error(e.value, op) Commands.run(command, options, args) return 0 def handle_error(error, op): print error op.print_help() return 1 def maybe_init_db(): db_path = Config.db_path if not os.path.isfile(db_path): os.makedirs(os.path.dirname(db_path)) db = sqlite3.connect(db_path) c = db.cursor()
def parse(self, inputString): self.state.player.setLastAction(None) inputString = inputString.lower() inputArray = inputString.split() #Break apart their input into the action and the target(or object) self.command = "" self.target = "" self.recipient = "" for word in inputArray: #remove unnecessary prepositions from the input if word in ("the","of","to","from","at","through","on","towards","away"): inputArray.remove(word) if len(inputArray) < 1: #Check for an empty input string return None self.command = inputArray.pop(0) if len(inputArray) >= 1: for word in inputArray: if ((self.command == "use") and (word == "on")) or ((self.command == "ask") and (word == "about")): #check if the command is a two word command self.command += (" " + word) self.addRecipient(inputArray.index(word) + 1, inputArray) #Start adding the rest of the words to the recipient, starting with the break #position after "on". Then end the loop so we skip the rest of the words self.target += word + " " self.target = self.target.strip() if self.command == "heavy": nextCom = inputArray.pop(0) if nextCom == "attack": self.command = "heavy attack" if (self.command == "go") or (self.command == "travel") or (self.command == "move") or (self.command == "walk"): resultString = Commands.go(self.state.player, self.target) elif (self.command == "north") or (self.command == "south") or (self.command == "east") or (self.command == "west"): resultString = Commands.go(self.state.player, self.command) elif (self.command == "use") or (self.command == "activate"): resultString = Commands.use(self.state.player, self.target) elif (self.command == "use on"): resultString = Commands.useOn(self.state.player, self.target, self.recipient) elif (self.command == "get") or (self.command == "take") or (self.command == "acquire") or (self.command == "grab") or (self.command == "fetch") or (self.command == "procure") or (self.command == "attain"): resultString = Commands.get(self.state.player, self.target) elif (self.command == "drop") or (self.command == "discard") or (self.command == "ditch"): resultString = Commands.drop(self.state.player, self.target) elif (self.command == "attack"): resultString = Commands.attack(self.state.player, self.target) elif (self.command == "heavy attack"): resultString = Commands.heavyAttack(self.state.player, self.target) elif (self.command == "shoot"): resultString = Commands.shoot(self.state.player, self.target) elif (self.command == "reload"): resultString = Commands.reload(self.state.player) elif (self.command == "defend") or (self.command == "guard"): resultString = Commands.defend(self.state.player) elif (self.command == "exorcise"): resultString = Commands.exorcise(self.state.player, self.target) elif (self.command == "advance"): resultString = Commands.advance(self.state.player, self.target) elif (self.command == "retreat"): resultString = Commands.retreat(self.state.player, self.target) elif (self.command == "equip"): resultString = Commands.equip(self.state.player, self.target) elif (self.command == "open"): resultString = Commands.openThing(self.state.player, self.target) elif (self.command == "close"): resultString = Commands.closeThing(self.state.player, self.target) elif (self.command == "drink"): resultString = Commands.drink(self.state.player, self.target) elif (self.command == "wait"): resultString = Commands.wait(self.state.player) elif (self.command == "read"): resultString = Commands.read(self.state.player, self.target) elif (self.command == "talk"): resultString = Commands.talk(self.state.player, self.target) elif (self.command == "ask about"): resultString = Commands.ask(self.state.player, self.target, self.recipient) elif (self.command == "look") or (self.command == "examine") or (self.command == "check") or (self.command == "scrutinize") or (self.command == "analyze") or (self.command == "inspect"): resultString = Commands.look(self.state.player, self.target) elif (self.command == "inventory") or (self.command == "inv") or (self.command == "i") or (self.command == "items") or (self.command == "stuff"): resultString = Commands.inventory(self.state.player) elif (self.command == "char") or (self.command == "stats"): resultString = Commands.stats(self.state.player) elif (self.command == "save"): resultString = StateControl.save(self.state) elif (self.command == "quit") or (self.command == "exit"): resultString = StateControl.quit() else: resultString = "I don't understand that." self.state.player.setLastAction(self.command) return resultString
def receive(self): return Commands.parse_command(self.socket.recv(self.buffer_size))
for n in sorted(SimpleMode.modes.keys()): m=SimpleMode.modes[n] Armagetronad.PrintPlayerMessage(player, " 0x88ff44"+m.name+": 0x888800"+m.desc) ## @brief Lock the current mode. def lockMode(acl, player): global locked locked=True Armagetronad.PrintPlayerMessage(player, "0xff0000Mode locked.") ## @brief Unlock the current mode. def unlockMode(acl, player): global locked locked=False Armagetronad.PrintPlayerMessage(player, "0x00ff88Mode unlocked.") ## @brief Change lives. # @param lives New lives. (Number of respawns) def setLives(acl, player, lives): try: SimpleMode.current_lives=int(lives) except ValueError: Armagetronad.PrintPlayerMessage(player, "0xff4400Invalid format!") else: Armagetronad.PrintMessage(Messages.LivesChanged.format(new_lives=lives, player=Player.players[player].name)) Commands.add_help_group("modes", "Commands about modes (edit, add, ...)") Commands.register_commands(addMode,editMode, deleteMode, lockMode, unlockMode, group="modes") Commands.register_commands(mode, modes, group="voting") Commands.register_commands(setLives, group="misc")
# See how long we'll have to wait now if len(alarm_queue) > 0: alarm = alarm_queue.peek() wait = alarm.wait_time() Log.debug('Next alarm in %i seconds. Sleeping until then.' % wait) # If two alarms occur at the same time, wait will be zero or negative. # No point in sleeping if that's the case. if wait > 0: time.sleep(wait) # Remove the alarm from the queue alarm = alarm_queue.pop() # If anybody cares about this alarm, alert them if alarm.name in subscriptions: clients = subscriptions[alarm.name] Log.debug('Alerting %i clients about alarm "%s"' % (len(clients), alarm.name)) # Notify all subscribed clients for client in clients: # Spin off a thread to talk to the client #t_handle = thread.start_new_thread(alert_client, (client, alarm)) c = Client.OutgoingClient(client.ip, client.port, handle_alarm_response) c.send_command(Commands.create_command_string(('A', alarm.name))) else: Log.debug('No subscriptions to alarm "%s"' % alarm.name) # Sleep for 1 second to prevent the alarm from firing again time.sleep(1) # Stick the alarm back in the queue if it repeats if not alarm.once: alarm_queue.enqueue(alarm)
# @param name The name of the extension to load. def loadExt(acl, player, name): Armagetronad.PrintPlayerMessage(player, "Loading "+name+ " ...") try: if extensions.loadExtension(name): raise Exception() else: Armagetronad.PrintPlayerMessage(player, "0x00ff00Succeeded ---------- 0xaaaaaa"+name+" [+]") except: Armagetronad.PrintPlayerMessage(player, "0xff0000Failed ----------- 0xaaaaaa"+name+" [+]") ## @brief Unload an extension # @param name The name of the extension to unload. def unloadExt(acl, player, name): Armagetronad.PrintPlayerMessage(player, "Unloading "+name+" ...") try: if extensions.unloadExtension(name): raise Exception() else: Armagetronad.PrintPlayerMessage(player, "0x00ff00Succeeded --------- 0xaaaaaa"+name+" [-]") except: Armagetronad.PrintPlayerMessage(player, "0xff0000Failed ---------- 0xaaaaaa"+name+" [-]") ## @brief List all available extensions. def listExt(acl, player): Armagetronad.PrintPlayerMessage("Available extensions: ") Armagetronad.PrintPlayerMessage(", ".join(extensions.getExtensions())) Commands.add_help_group("extensions", "Extension management tools") Commands.register_commands(loadExt, unloadExt, listExt, group="extensions")
def __setTareOrientationAsSameAsSuppliedOrientationInQuaternionDomain(self, sensorId, tareData): command = Commands.getCommandAsChr(Commands.TARE_WITH_QUATERNION) dataFormat = Commands.getDataFormat(Commands.TARE_WITH_QUATERNION) binaryCommand = self.__getWirelessBinaryCommand(command, sensorId, tareData, dataFormat) self.__retryIfSetCommandFailed(binaryCommand,"tareWithQuaternion", sensorId=sensorId)
def run(): Commands.arduino = Arduino(disabled=True, testMotor=(-100, 100), steering=(0, 179), button=None) # camera1 = Camera(windowName="camera", # cameraType="ELP180", # ) camera1 = Camera(windowName="camera", camSource="Orca 11-2-14 Roll 5.mp4", crop=(50, None, None, None), width=427, height=240 ) # camera1 = Camera(windowName="camera", # camSource="IMG_0524.m4v", # width=320, height=240 # ) Commands.knownDepth_meters, Commands.frameY_px = 50, camera1.height / 2 Commands.knownWidth_meters, Commands.frameWidth_px = 30, camera1.width captureProperties = dict( paused=False, showOriginal=False, enableDraw=True, currentFrame=0, enableCamera2=False ) if captureProperties['enableCamera2'] is True: camera2 = Camera(windowName="camera 2", cameraType="ELP") else: camera2 = None protocols = ["hill 1", " hill 2", "hill 2 transition", "hill 3 left 1", "hill 3 cross section 1", "hill 3 right", "hill 3 cross section 2", "hill 3 left 2", "transition to chute", "chute", "transition to hill 4", "hill 4", "hill 5"] current = 0 courseFinished = False keys = ['q', "esc", ' ', 'o', "right", "left", 's', 'h'] frame1 = None while courseFinished == False: key = camera1.getPressedKey() if captureProperties['paused'] is False or captureProperties['currentFrame'] != camera1.currentFrameNumber(): frame1 = camera1.updateFrame() if captureProperties['enableCamera2'] is True: frame2 = camera2.updateFrame() frame1 = Analyzers.overlayCameras(frame1, frame2) height, width = frame1.shape[0:2] captureProperties['currentFrame'] = camera1.currentFrameNumber() road, contours = Analyzers.filterOutNonRoad(frame1, showSelectedPoints=False) road = Analyzers.balanceFrame(road) # rawLines = Analyzers.filterOutNonAsphalt(road) road = Analyzers.filterOutNonAsphalt(road) rawLines = None streetLeft, streetRight, streetCenter = Analyzers.findStreetCenterAndEdges(contours, (height, width)) lines = Analyzers.filterOutIncorrectLines(rawLines, streetLeft, streetCenter, streetRight) if captureProperties['enableDraw'] is True: if captureProperties['showOriginal'] is False: frame1 = Analyzers.combineFilters(road, contours, (streetLeft, streetCenter, streetRight), lines) camera1.showFrame(frame1) # camera2.showFrame(frame2) if protocols[current] == "hill 1" or protocols[current] == "hill 2": Commands.centerSelfBetweenTwoLines(lines) elif protocols[current] == "hill 2 transition": Commands.offsetFromRoadEdgeBy(streetCenter, -3) elif protocols[current] == "hill 3 left 1": Commands.stayAwayFromLeftLineBy(lines, 0.3) elif protocols[current] == "hill 3 cross section 1": Commands.offsetFromRoadEdgeBy(streetRight, -0.3) elif protocols[current] == "hill 3 right": Commands.stayAwayFromRightLineBy(lines, 0.3) elif protocols[current] == "hill 3 cross section 2": Commands.offsetFromRoadEdgeBy(streetLeft, 0.3) elif protocols[current] == "hill 3 left 2": Commands.stayAwayFromLeftLineBy(lines, 0.3) elif protocols[current] == "transition to chute": Commands.driveTowardsStoredLandmark() elif protocols[current] == "chute" or protocols[current] == "transition to hill 4": Commands.offsetFromRoadEdgeBy(streetRight, -0.3) elif protocols[current] == "hill 4": Commands.offsetFromRoadEdgeBy(streetCenter, 0) elif protocols[current] == "hill 5": Commands.offsetFromRoadEdgeBy(streetCenter, 0) if Analyzers.verticalFinishLineFound(lines): courseFinished = True if Analyzers.checkForTransition(frame1, current, protocols) is True: current += 1 if 0 < camera1.getVideoFPS() < 3: captureProperties['paused'] = True if key in keys: if key == 'q' or key == "esc": camera1.stopCamera() courseFinished = True elif key == ' ': captureProperties['paused'] = not captureProperties['paused'] elif key == 'o': captureProperties['showOriginal'] = not captureProperties['showOriginal'] frame1 = camera1.updateFrame(False) elif key == "right": camera1.incrementFrame() elif key == "left": camera1.decrementFrame() elif key == 's': camera1.saveFrame(frame1) elif key == 'h': captureProperties['enableDraw'] = not captureProperties['enableDraw']
fileBeingAccessed = True PFSBase.writeToFile(saveFile, fileData) fileBeingAccessed = False print("Starting alex's program v1.0.2a") print("Loading save file") saveFile = os.getcwd() + "\\mutitool.pfs" fileBeingAccessed = False fileData = PFSBase.readFromFile(saveFile) print("Registering save handler") atexit.register(programEnd, isThread = False, saveFileEvery = 1) _thread.start_new_thread(programEnd, (True, 10)) print("For the list of commands type /help") print("") running = True while running: userinput = input() command = Commands.getCommandFromName(userinput) if(command is not 0): args = userinput.split(' ') args.remove(command.getName(command)) command.processCommand(command, args)