def on_closing(self): # Try to stop handler and let it do its thing before shutting down MessageHandler.stop_handler() if self.msg_handler is not None: self.msg_handler.join() # TODO Should this be removed and hopefully that the thread will be closed eventually? self.root.destroy()
def login(s, state, name, mode): ''' This command takes one argument, your name. A player name is a userid that uniquely identifies a player. Your name is entered with this command and is sent to the server. Return True if login success, False if login failed.''' if mode is None: mode = 'A' if mode and mode not in ['A', 'M']: print("Mode must be A or M\n") return # Send message to server s.send(LOGIN(name, mode)) # Receive response message from server s.recv_messages() # Check response from server response = s.read_message() while response: if response in [OK, ERR401]: MessageHandler.handle_login(s, state, response, name, mode) return else: MessageHandler.handle_unrecognized(s, state, response) response = s.read_message()
def btn_callback(self): if not self.is_connected: # Attempt to connect - check that the port is still connected if self.comports.get() in PortManager.serial_ports(): # Port is still up n runnin' self.btn["text"] = "Disconnect" self.comports.config(state="disabled") # Connect to the Arduino and start processing self.msg_handler = Thread(target=MessageHandler.message_handler, args=(self.comports.get(),)) self.msg_handler.start() # Change da flag fool! self.is_connected = True else: # Port not found - refresh list self.load_ports() else: # Disconnect from Arduino MessageHandler.stop_handler() self.msg_handler.join() # Change the flag BACK! self.is_connected = False # Disconnect. Refresh port list self.btn["text"] = "Connect" self.comports.config(state="enabled") self.load_ports()
def __init__(self,settings: dict): # private properties self._channels: list = settings.get('channels') self._user: str = settings.get('user') self._password: str = settings.get('password') self._caprequest: str = settings.get('caprequest') self._server = IrcController.IrcController(settings.get("server"),settings.get("port")) self._messageHandler: MessageHandler = MessageHandler.MessageHandler() self._sendQ: queue.SimpleQueue = queue.SimpleQueue() # public properties self.event: EventHandler = EventHandler self.COMMANDS: MessageHandler.COMMANDS = self._messageHandler.COMMANDS self.startWithThread=threading.Thread(target=self.start, daemon=True).start self.channels: dict = {} self.globalUserState: MessageHandler.globalUSerState = MessageHandler.globalUSerState() # Register System Event functions self.event.on(self.COMMANDS.CONNECTED, self._onConnected) self.event.on(self.COMMANDS.NOTICE, self._onNotice) self.event.on(self.COMMANDS.ROOMSTATE, self._onRoomState) self.event.on(self.COMMANDS.USERSTATE, self._setUserState) self.event.on(self.COMMANDS.MESSAGEIDS.ROOM_MODS, self._setChannelMods) self.event.on(self.COMMANDS.GLOBALUSERSTATE, self._setGlobalUserSate) self.event.on(self.COMMANDS.ROOMSTATE.EMOTE_ONLY, self._onEmotesOnly) self.event.on(self.COMMANDS.ROOMSTATE.FOLLOWERS_ONLY, self._onFollowersOnly) self.event.on(self.COMMANDS.ROOMSTATE.SLOW, self._onSlowMode) self.event.on(self.COMMANDS.ROOMSTATE.SUBS_ONLY, self._onSubsOnly) self.event.on(self.COMMANDS.ROOMSTATE.R9K, self._onR9k)
def exit(s, state): ''' This command allows player to exit ''' # Check if player logged in: # if not state.logged_in: # print("You are not logged in.\n") # return # Send exit message to server s.send(EXIT) print("Exiting ... \n") sys.exit() # Note: Remaining code won't execute/matter, # Since server will close connection immediately. # Update state state.initiated_exit = True state.clear_game() s.recv_messages() response = s.read_message() # Exit can be received from main while response: if response in [OK, QUIT]: MessageHandler.handle_quit(s, state, response) response = s.read_message()
def __init__(self, gametype, pgui): self.gui = pgui self.filesystem = FileSystem() self.iohandler = IOHandler(gametype, pgui) self.mapmanager = MapManager(self.filesystem.getData('map')) self.mapmanager.getVisibleObjects() self.messagehandler = MessageHandler( self.filesystem.getData("messages")) self.gamerun = False self.securitycamera = True self.talked = False
def handle_location(token, user, location): user.setLocation(location) data = to_json({ "recipient": { "id": user.get_id() }, "message": { "text": "Updated Location. What is it you are looking for?", "quick_replies": qr.quick_replies_list_smaps } }) MessageHandler.messagerequestpost(token, data)
def ask_for_location(user, token): data = to_json({ "recipient": { "id": user.get_id() }, "message": { "text": "I'd love to help you look. Could you send me a location?", "quick_replies": [{ "content_type": "location" }] } }) MessageHandler.messagerequestpost(token, data)
def __init__(self, settings: dict): """ """ # private properties self._channels: list = settings.get('channels') self._user: str = settings.get('user') self._password: str = settings.get('password') self._caprequest: str = settings.get('caprequest') self._server = IrcController.IrcController(settings.get("server"), settings.get("port")) self._messageHandler: MessageHandler = MessageHandler.MessageHandler() self._sendQ: queue.SimpleQueue = queue.SimpleQueue() # public properties self.event: EventHandler = EventHandler self.COMMANDS: COMMANDS = self._messageHandler.COMMANDS self.startWithThread = threading.Thread(target=self.start, daemon=True).start self.roomState: RoomState = MessageHandler.RoomState self.channels: dict = {} # Register System Event functions self.event.on(self.COMMANDS.CONNECTED, self._onConnected) self.event.on(self.COMMANDS.NOTICE, self._onNotice) self.event.on(self.COMMANDS.ROOMSTATE, self._onRoomState) self.event.on(self.COMMANDS.MESSAGEIDS.ROOM_MODS, self._setChannelMods)
def m_handler(self, *arg, **karg): _filter = karg["filter"] def _m_handler(bot, update): message = update.effective_message.text reply = self.handler(message=message) if reply is None: return if isinstance(reply, (str, unicode)): update.effective_message.reply_text(reply) else: try: reply_markup = _generateMenu(reply[sadDec._MENU_INDEX_]) update.effective_message.reply_text( reply[sadDec._MESSAGE_INDEX_], reply_markup=reply_markup) except IndexError: logging.error("Bad menu formatting") _newMessageHandler = MessageHandler.MessageHandler( _m_handler, _filter, funcName=self.handler.funcName, description=self.handler.description) return _newMessageHandler
def test_client_discovery_works(self): mh = MessageHandler.MessageHandler(self.client._client_id, testing=True) self.client.set_message_queue(mh) self.client.send_discovery() test = mh.get_queue().get_nowait() self.assertTrue(test is not None)
def main() -> None: MessageHandler.printStartup() while True: print("\nMenu") print("-" * 25) print("Options:") print("[1] Grade/modify an existing assignment") print("[2] Create a directory for a new assignment") print("[0] Exit") choice = InputHandler.input_range(0, 2) if choice == 1: grade() if choice == 2: make_dir() if choice == 0: return None
def _setRoomState(self, channel, tags): if channel not in self.channels: self.channels[channel]: str = MessageHandler.Channel() self.channels[channel].roomID = tags.get("room-id") for key in tags: if key != "room-id": setattr(self.channels[channel].roomState, key.replace('-', '_'), tags[key]) self.getMods(channel)
def run(self): msgHandler = MessageHandler() # self.trigger.emit(msgHandler) @msgHandler.bot.register() def addMessage(msg): print("Msg:\"" + msg.text + "\" received from " + msg.sender.remark_name + " is gonna pass to the main thread.") # msgListItemWidget = MsgListItemWidget(parent=ui.msgListWidget) # msgListItemWidget.setAllInfo("1.jpg", msg.sender.remark_name, msg.text) # msgListWidgetItem = QtWidgets.QListWidgetItem(ui.msgListWidget) # As a container # msgListWidgetItem.setSizeHint(msgListItemWidget.sizeHint()) # # ui.msgListWidget.addItem(msgListWidgetItem) # ui.msgListWidget.setItemWidget(msgListWidgetItem, msgListItemWidget) self.newMessage.emit(msg, msgHandler.bot.messages) msgHandler.botJoin()
def _addChannel(self, channel: str)->None: """[summary] :param channel: [description] :type channel: str """ if channel not in self.channels: channel = self._formatChannelName(channel) self.channels[channel]: MessageHandler.Channel = MessageHandler.Channel() self.channels[channel].name = channel
def __init__(self, server, sock, ip_addr): self.sock = sock self.ip_addr = ip_addr self.active = False self.send_queue = Queue.Queue() self.receiver = MessageReceiver(self.sock) self.sender = MessageSender(self.sock) self.handler = MessageHandler() self.server = server self.last_read_time = 0
def _setUserState(self, sender, message): """[summary] :param sender: [description] :type sender: [type] :param message: [description] :type message: [type] """ if message.channel not in self.channels: self.channels[message.channel]: MessageHandler.Channel = MessageHandler.Channel() for key in message.tags: setattr(self.channels[message.channel].userState, key.replace('-','_'), message.tags.get(key))
class PiDroidServer(Server): ''' ''' def onStart(self, ip, port): self.noOfClients = 0 self.clients = [] self.messenger = MessageHandler(port) print "Server has started.." def onStop(self): print "Server is stopping.." def onConnect(self, socket): self.noOfClients += 1 self.clients.append(socket) print "Client connected to server.." print self.noOfClients, "clients are connected" # if not socket.username == "guest" + str(self.noOfClients): socket.username = "******" + str(self.noOfClients) ''' socket.msgtype = "/all" socket.param = "" socket.ignBroadcast = False socket.invisible = False socket.send("To change it, use command /user") socket.send("For more commands, type /help") socket.send("Your username is " + socket.username) ''' def onMessage(self, socket, message): print "Client ", socket.username, " sent: ", message reply = self.messenger.dispatch(message) if reply != None: socket.send(reply) # Signify all is well return True def onDisconnect(self, socket): self.noOfClients -= 1 for index in range(0, len(self.clients)): if self.clients[index] == socket: del self.clients[index] break print socket.username + " has disconnected from server..", print self.noOfClients, " clients are connected"
def _setRoomState(self, message)->None: """ _setRoomState [summary] :param channel: [description] :type channel: str :param tags: [description] :type tags: list """ if message.channel not in self.channels: self.channels[message.channel]: MessageHandler.Channel = MessageHandler.Channel() self.channels[message.channel].roomID = message.tags.get(self.COMMANDS.ROOMSTATE.ROOM_ID) self.channels[message.channel].name = message.channel for key in message.tags: if key != self.COMMANDS.ROOMSTATE.ROOM_ID: setattr(self.channels[message.channel].roomState, key.replace('-','_'), message.tags.get(key)) self._getMods(message.channel)
def main(): import MessageHandler import Notifier import threading logger.setLevel(logging.INFO) logger.info("Instantiating the different components we need.") #Instantiating the different components we need. client = Client() monman = MonitorManager.MonitorManager() cexec = CommandInterface.CommandInterface() notifier = Notifier.Notifier(client.get_client_id()) messagehandler = MessageHandler.MessageHandler(client.get_client_id()) logger.info("Setting the outgoing message queue.") #Setting the outgoing message queue client.set_message_queue(messagehandler) monman.set_message_queue(messagehandler) ##TODO THIS SHIT IS TEMPORARY. MAKE A LOCK FACTORY CLASS OR SOMETHING. ##SETTING LOCKS FOR THE MONITORS SO WHEN THEY ARE BEING MODIFIED THEY CANT BE POLLED. lock = threading.RLock() monman.set_lock(lock) notifier._data_manager.set_lock(lock) logger.info("Giving client access to crucial components") #Giving client access to crucial components client.set_monitor_manager(monman) client.set_command_executor(cexec) client.set_notifier(notifier) #making the client visible on the nameserver client.register_to_name_server() #Sending a "Hey I"m here!" message to the server. client.send_discovery() #Starting the outgoing message queue messagehandler.start() #Beginning the monitoring cycle. client.begin_monitoring()
def __init__(self, ip): """ :param ip: Ip-address of RCM conected to computer. :return: """ self.nbr_of_measurements = 1 self.tol = [1e-6, 1e-6] # [abs_tol, rel_tol] self.msg_handler = MessageHandler.MessageHandler() self.msg_handler.set_ip(ip) self.nbr_of_anchors = 3 # same as len(self.anchors) self.anchors = [] for j in range(0, self.nbr_of_anchors): self.anchors += [Anchor.Anchor()] """ These are the instatioations of the Anchors (see Anchors.py) Change these whenever anchors are moved/replaced. """ self.__set_anchor__(0, 106, -1.0, -2.0) self.__set_anchor__(1, 114, -1.0, 2.0) self.__set_anchor__(2, 108, 2.0, 0.0)
def onStart(self, ip, port): self.noOfClients = 0 self.clients = [] self.messenger = MessageHandler(port) print "Server has started.."
import GraphHandler as g import MessageHandler as m exit = False baudrate = 15500 timeout = None port_name = "COM4" Gui = g.GraphHandler() MsgHandler = m.MessageHandler(port_name, baudrate_=baudrate, timeout_=timeout) MsgHandler.StartCommunication() while (not Gui.exit): for i in range(3 * g.NUMBER_OF_KINETIS): msg = MsgHandler.ReadFrame() MsgHandler.ManageMessage(msg, len(msg)) list_of_positions = MsgHandler.GetPositions() Gui.UpdateBoards(list_of_positions) MsgHandler.EndCommunication()
def onMessage(client, userdata, msg): """ Callback for when the client receives a message. Parses the topic and calls the corresponding message handler in MessageHandler.py :param client: Client that received the message :param userdata: Additional userdata of the client :param msg: The message received """ global numberReceivedMessages numberReceivedMessages += 1 print "Received", print numberReceivedMessages, print "total messages so far" logging.info("Received a message on topic %s", msg.topic) print "Received a message on topic " + msg.topic if msg.topic == "PositionRelay": MessageHandler.handlePositionRelayMsg(msg.payload, userdata) elif msg.topic == "PositionZero": MessageHandler.handlePositionZeroMsg(msg.payload, userdata) elif msg.topic == "RelayData": MessageHandler.handleRelayMsg(msg.payload, userdata) elif msg.topic == "MiscData": MessageHandler.handleMiscMsg(msg.payload, userdata) elif msg.topic == "allUnits": MessageHandler.handleAllCommandMsg(msg.payload, userdata) elif msg.topic == "unit" + str(userdata.params["userId"]): MessageHandler.handleSpecificCommandMsg(msg.payload, userdata) elif msg.topic == "unit" + str(userdata.params["userId"]) + "_timeSynchro": MessageHandler.handleServerInfoResponse(msg.payload, userdata) elif msg.topic == "serverInfoResponse": MessageHandler.handleServerInfoResponse(msg.payload, userdata) elif msg.topic == "queryServerInfo": MessageHandler.handleQueryServerInfo(msg.payload, userdata) elif msg.topic == "ConnectionMessage": MessageHandler.handleConnectionMessage(msg.payload, userdata) elif msg.topic == "newIp": MessageHandler.handleNewIpMessage(msg.payload, userdata) else: print "Received message on unknown topic", print msg.topic
def __init__(self, inputFile): """ Constructor @ In, inputFile, string, input file name @ Out, None """ self.printTag = 'RAVEN_PARSER' # print tag self.inputFile = inputFile # input file name self.outStreamsNames = {} # {'outStreamName':[DataObjectName,DataObjectType]} self.databases = {} # {name: full rel path to file with filename} self.varGroups = {} # variable groups, names and values if not os.path.exists(inputFile): raise IOError(self.printTag+' ERROR: Not found RAVEN input file') try: tree = ET.parse(open(inputFile,'r')) except IOError as e: raise IOError(self.printTag+' ERROR: Input Parsing error!\n' +str(e)+'\n') self.tree = tree.getroot() # expand the ExteranlXML nodes cwd = os.path.dirname(inputFile) xmlUtils.expandExternalXML(self.tree,cwd) # get the NAMES of the variable groups variableGroupNode = self.tree.find('VariableGroups') if variableGroupNode is not None: # make a messageHandler and messageUsesr to handle variable group creation ## if made generally available to this parser, this can be relocated and used generally messageHandler = MessageHandler.MessageHandler() messageHandler.initialize({'verbosity':'quiet'}) messageUser = MessageHandler.MessageUser() self.varGroups = mathUtils.readVariableGroups(variableGroupNode,messageHandler,messageUser) # do some sanity checks sequence = [step.strip() for step in self.tree.find('.//RunInfo/Sequence').text.split(",")] # firstly no multiple sublevels of RAVEN can be handled now for code in self.tree.findall('.//Models/Code'): if 'subType' not in code.attrib: raise IOError(self.printTag+' ERROR: Not found subType attribute in <Code> XML blocks!') if code.attrib['subType'].strip() == 'RAVEN': raise IOError(self.printTag+' ERROR: Only one level of RAVEN runs are allowed (Not a chain of RAVEN runs). Found a <Code> of subType RAVEN!') # find steps and check if there are active outstreams (Print) foundOutStreams = False foundDatabases = False for step in self.tree.find('.//Steps'): if step.attrib['name'] in sequence: for role in step: if role.tag.strip() == 'Output': mainClass, subType = role.attrib['class'].strip(), role.attrib['type'].strip() if mainClass == 'OutStreams' and subType == 'Print': outStream = self.tree.find('.//OutStreams/Print[@name="'+role.text.strip()+ '"]'+'/source') if outStream is None: continue # can have an outstream in inner but still use database return dataObjectType = None linkedDataObjectPointSet = self.tree.find('.//DataObjects/PointSet[@name="'+outStream.text.strip()+ '"]') if linkedDataObjectPointSet is None: linkedDataObjectHistorySet = self.tree.find('.//DataObjects/HistorySet[@name="'+outStream.text.strip()+ '"]') if linkedDataObjectHistorySet is None: # try dataset linkedDataObjectHistorySet = self.tree.find('.//DataObjects/DataSet[@name="'+outStream.text.strip()+ '"]') if linkedDataObjectHistorySet is None: raise IOError(self.printTag+' ERROR: The OutStream of type "Print" named "'+role.text.strip()+'" is linked to not existing DataObject!') dataObjectType, xmlNode = "HistorySet", linkedDataObjectHistorySet else: dataObjectType, xmlNode = "PointSet", linkedDataObjectPointSet self.outStreamsNames[role.text.strip()] = [outStream.text.strip(),dataObjectType,xmlNode] foundOutStreams = True elif mainClass == 'Databases' and subType == 'NetCDF': rName = role.text.strip() db = self.tree.find(f'.//Databases/NetCDF[@name="{rName}"]') if db is None: continue # can have a database in inner but still use outsream return if db.attrib['readMode'] == 'overwrite': dirs = db.attrib.get('directory', 'DatabaseStorage') name = db.attrib.get('filename', db.attrib['name']+'.nc') full = os.path.join(dirs, name) self.databases[rName] = full foundDatabases = True if not foundOutStreams and not foundDatabases: raise IOError(self.printTag+' ERROR: No <OutStreams><Print> or <Databases><NetCDF readMode="overwrite"> found in the active <Steps> of inner RAVEN!') # Now we grep the paths of all the inputs the SLAVE RAVEN contains in the workind directory. self.workingDir = self.tree.find('.//RunInfo/WorkingDir').text.strip() # Find the Files self.slaveInputFiles = self.findSlaveFiles(self.tree, self.workingDir)
def addConMesHandler(self, handler): """Adds conection message handler to MessageHandler script Args: handler (Callable): Handler function, must handle the following Args: (Relay node OLSR IP, Connected TriccKit IP)""" MessageHandler.addConMesHandler(handler)
import xarray as xr # find location of crow, message handler frameworkDir = os.path.abspath(os.path.join(*([os.path.dirname(__file__)]+[os.pardir]*4+['framework']))) sys.path.append(frameworkDir) from utils.utils import find_crow find_crow(frameworkDir) import MessageHandler # find location of data objects sys.path.append(os.path.join(frameworkDir,'DataObjects')) import HistorySet mh = MessageHandler.MessageHandler() mh.initialize({'verbosity':'debug', 'callerLength':10, 'tagLength':10}) print('Module undergoing testing:') print(HistorySet ) print('') def createElement(tag,attrib=None,text=None): """ Method to create a dummy xml element readable by the distribution classes @ In, tag, string, the node tag @ In, attrib, dict, optional, the attribute of the xml node @ In, text, str, optional, the dict containig what should be in the xml text """ if attrib is None: attrib = {}
class Test_MessageHandler(unittest.TestCase): MH = MessageHandler.MessageHandler() def test_1_PRIVMSG(self): event, message = self.MH.handleMessage( "@badge-info=;badges=global_mod/1,turbo/1;color=#0D4200;display-name=ronni;emotes=25:0-4,12-16/1902:6-10;id=b34ccfc7-4977-403a-8a94-33c6bac34fb8;mod=0;room-id=1337;subscriber=0;tmi-sent-ts=1507246572675;turbo=1;user-id=1337;user-type=global_mod :[email protected] PRIVMSG #ronni :Kappa Keepo Kappa" ) self.assertIsInstance(event, str) self.assertIsInstance(message, MessageHandler.Message) self.assertEqual(event, self.MH.COMMANDS.MESSAGE) self.assertEqual(len(message.tags), 13) self.assertEqual(len(message.tags.get("emotes")), 2) self.assertEqual(message.text, "Kappa Keepo Kappa") self.assertEqual(message.username, "ronni") self.assertEqual(message.channel, "#ronni") def test_2_CLEARCHAT(self): event, message = self.MH.handleMessage( ":tmi.twitch.tv CLEARCHAT #dallas :ronni") self.assertIsInstance(event, str) self.assertIsInstance(message, MessageHandler.Message) self.assertEqual(event, self.MH.COMMANDS.CLEARCHAT) def test_3_CLEARMSG(self): event, message = self.MH.handleMessage( "@login=ronni;target-msg-id=abc-123-def :tmi.twitch.tv CLEARMSG #dallas :HeyGuys" ) self.assertIsInstance(event, str) self.assertIsInstance(message, MessageHandler.Message) self.assertEqual(event, self.MH.COMMANDS.CLEARMSG) def test_4_GLOBALUSERSTATE(self): event, message = self.MH.handleMessage( "@badge-info=subscriber/8;badges=subscriber/6;color=#0D4200;display-name=dallas;emote-sets=0,33,50,237,793,2126,3517,4578,5569,9400,10337,12239;turbo=0;user-id=1337;user-type=admin :tmi.twitch.tv GLOBALUSERSTATE" ) self.assertIsInstance(event, str) self.assertIsInstance(message, MessageHandler.Message) self.assertEqual(event, self.MH.COMMANDS.GLOBALUSERSTATE) def test_5_ROOMSTATE(self): event, message = self.MH.handleMessage( "@emote-only=0;followers-only=0;r9k=0;slow=0;subs-only=0 :tmi.twitch.tv ROOMSTATE #dallas" ) self.assertIsInstance(event, str) self.assertIsInstance(message, MessageHandler.Message) self.assertEqual(event, self.MH.COMMANDS.ROOMSTATE) def test_6_USERNOTICE(self): event, message = self.MH.handleMessage( "@badge-info=;badges=staff/1,broadcaster/1,turbo/1;color=#008000;display-name=ronni;emotes=;id=db25007f-7a18-43eb-9379-80131e44d633;login=ronni;mod=0;msg-id=resub;msg-param-cumulative-months=6;msg-param-streak-months=2;msg-param-should-share-streak=1;msg-param-sub-plan=Prime;msg-param-sub-plan-name=Prime;room-id=1337;subscriber=1;system-msg=ronni\shas\ssubscribed\sfor\s6\smonths!;tmi-sent-ts=1507246572675;turbo=1;user-id=1337;user-type=staff :tmi.twitch.tv USERNOTICE #dallas :Great stream -- keep it up!" ) self.assertIsInstance(event, str) self.assertIsInstance(message, MessageHandler.Message) self.assertEqual(event, self.MH.COMMANDS.USERNOTICE) def test_7_USERSTATE(self): event, message = self.MH.handleMessage( "@badge-info=;badges=staff/1;color=#0D4200;display-name=ronni;emote-sets=0,33,50,237,793,2126,3517,4578,5569,9400,10337,12239;mod=1;subscriber=1;turbo=1;user-type=staff :tmi.twitch.tv USERSTATE #dallas" ) self.assertIsInstance(event, str) self.assertIsInstance(message, MessageHandler.Message) self.assertEqual(event, self.MH.COMMANDS.USERSTATE) def test_8_InvalidMessage(self): event, message = self.MH.handleMessage("3") self.assertIsNone(event) self.assertIsNone(message)
def do_POST(s): """Respond to a POST request.""" length = int(s.headers['Content-Length']) payload = s.rfile.read(length).decode('utf-8') if 'content-type' not in s.headers or s.headers['content-type'] == 'application/x-www-form-urlencoded': post_data = urlparse.parse_qs(payload) data = json.loads(post_data['payload'][0]) else: data = json.loads(payload) if 'X-GitHub-Event' in s.headers: eventType = s.headers['X-GitHub-Event'] else: eventType = '' if not world.testing: if not os.path.exists('requests/'): os.makedirs('requests') f = open('requests/' + eventType.replace('/','_') + strftime("%Y-%m-%d %H:%M:%S") + '.json', 'w') f.write(json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))) f.close() path = s.path.split('/') channel = configValue('channel') receivedcode = '' requireCode = configValue('passcode').strip() \ and configValue('passcode').strip().lower() != 'false' \ and configValue('passcode').strip().lower() != 'null' \ and configValue('passcode').strip().lower() != 'no' resetConfigOverrides() # Analyse the URL i = 0 for part in path: part = urllib.unquote(part) if i == 1 and requireCode: receivedcode = part part = part.replace('+','#') part = part.replace('~','#') part = part.replace('&','#') part = part.replace('^','#') # TODO: Throw out a warning when a URL specifies a configuration # value but we don't allow that if part.startswith("#") and not configValue('disallowChannelOverride'): channel = part elif '=' in part and not configValue('disallowConfigOverride'): explosion = part.split('=', 1) addConfigOverride(explosion[0], explosion[1]) i+=1 globals.channel = channel try: s.send_response(200) s.send_header('Content-type', 'text/plain') s.end_headers() s.wfile.write("Thanks!\n") s.wfile.write(s.path.split('/')) s.wfile.write("\n") except socket.error: pass if requireCode and receivedcode != configValue('passcode'): # The password is wrong s.wfile.write("The password is wrong\n") return # Handle Github secrets secret = getChannelSecret(channel) if secret is not None: if not 'X-Hub-Signature' in s.headers: s.wfile.write("This channel requires a secret\n") return digest = "sha1=%s" % (hmac.new(secret, payload, hashlib.sha1).hexdigest(),) log.debug("expected digest: %s", digest) provided = s.headers['X-Hub-Signature'] log.debug("provided digest: %s", provided) if not secureCompare(digest, provided): s.wfile.write("Invalid secret key\n") return brackets = parseBrackets(configValue('brackets')) themeName = configValue('theme') alphanumericPattern = re.compile('[\W_]+') themeClass = ''.join([alphanumericPattern.sub('', themeName).title(), 'Theme']) # Find the theme's class try: mod = getattr(themes, themeClass) klass = getattr(mod, themeClass) except AttributeError: # The theme was not found log.error("The '%s' theme was not found" % themeName) klass = themes.DefaultTheme.DefaultTheme repo = {} repo['unknown'] = 'repository' not in data repo['name'] = data.get('repository',{}).get('name') repo['owner'] = data.get('repository',{}).get('owner',{}).get('login') repo['fork'] = data.get('repository',{}).get('fork', False) repo['id'] = data.get('repository',{}).get('id', "%s/%s" % (repo['owner'], repo['name'])) theme = klass(repo, brackets) # # Handle different event types # msgs = [] theme.msgs = msgs if 'matrix' in data: TravisHandler.handle(data, theme) elif 'pages' in data: WikiHandler.handle(data, theme) elif 'screenshot_url' in data: NetlifyHandler.handle(data, theme) elif 'state' in data: StatusHandler.handle(data, theme) elif 'commits' in data: PushHandler.handle(data, theme) elif 'issue' in data or 'pull_request' in data: if 'comment' in data: IssueCommentHandler.handle(data, theme) else: IssueHandler.handle(data, theme) elif 'ref_type' in data: CreateDeleteHandler.handle(data, theme) elif 'release' in data: ReleaseHandler.handle(data, theme) elif 'zen' in data: PingHandler.handle(data, theme) elif 'message' in data: MessageHandler.handle(data, theme) elif 'eventName' in data: AppVeyorHandler.handle(data, theme) else: data['eventType'] = eventType UnknownHandler.handle(data, theme) theme.finalize() saveMessages(msgs) if not world.testing: for msg in msgs: for irc in world.ircs: irc.queueMsg(ircmsgs.privmsg(channel, msg))
def main(): if Utils.last_update(Utils.get_updates_json(url)) is None: update_id = 1 else: update_id = Utils.last_update(Utils.get_updates_json(url))['update_id'] while True: try: update = Utils.last_update(Utils.get_updates_json(url, update_id)) if update is not None: if update.get('message'): # Utils.send_mess(Utils.get_chat_id(update), MHandler.handleMessage(update)) r = MHandler.handle_message(update, lang) # print('HANDLED_MSG: ' + str(r)) Utils.log_mess('HANDLED_MSG', str(r)) response = 'none' for mess in r: # print('MSG: ' + str(mess)) Utils.log_mess('MSG', str(mess)) if mess == 'NONE': response = Utils.send_mess( Utils.get_chat_id(update), Utils.inte('stopbot', lang)) stop_bot() else: response = Utils.send_mess( Utils.get_chat_id(update), mess[0], mess[1]) if response: # print('RESPONSE: ' + str(response.json())) Utils.log_mess('RESPONSE', str(response.json()) + '\n\n', Utils.LogColors.RESPONSE) else: # print('STOPPING') stop_bot() elif update.get('callback_query'): callback_query = update.get('callback_query') # print('CALLBACK: ' + str(callback_query)) Utils.log_mess('CALLBACK', 'Query ' + str(callback_query), Utils.LogColors.OKBLUE) r = MHandler.handle_callback(update) # print('CALLBACK: ' + str(r)) Utils.log_mess('CALLBACK', str(r) + '\n\n', Utils.LogColors.OKBLUE) # name = 'You' # if callback_query.get('from').get('username'): # name = '@' + callback_query['from']['username'] # elif callback_query.get('from').get('first_name'): # name = callback_query.get('from').get('first_name') # Utils.send_mess(callback_query['message']['chat']['id'], name + ' told me ' + callback_query['data']) update_id = Utils.last_update( Utils.get_updates_json(url))['update_id'] + 1 except KeyboardInterrupt: stop_bot() except Exception as e: Utils.log_mess('ERROR', str(type(e)) + ' --> ' + str(e), Utils.LogColors.FAIL) Utils.log_mess( 'ERROR_READOUT', '\n' + Utils.LogColors.FAIL + Utils.list_to_lines( traceback.format_list( traceback.extract_tb(sys.exc_info()[2]))), Utils.LogColors.FAIL)
def handle_geosearch(token, recipient, text, client, amttodisplay=4): search_words = " ".join([ tok for tok, pos in pos_tag(word_tokenize(text)) if pos.startswith('N') or pos.startswith('J') ]) query_result = client.nearby_search(location='{},{}'.format( recipient.get_location().get_longitude(), recipient.get_location().get_latitude()), keyword=search_words, rankby="distance") gmaps = googlemaps.Client(s.GAPI) distmat = gmaps.distance_matrix(origins=[ (recipient.get_location().get_longitude(), recipient.get_location().get_latitude()) ], destinations=[ (str(place.geo_location['lat']), str(place.geo_location['lng'])) for place in query_result.places ], mode="walking") timeanddur = distmat['rows'][0]['elements'] if len(query_result.places) > 0: elements = [] for indx, place in enumerate(query_result.places[:amttodisplay]): image_url = None timeaway, disaway = timeanddur[indx]['duration']['text'].decode( 'utf-8'), timeanddur[indx]['distance']['text'].decode('utf-8') if (len(place.photos) > 0): photo = place.photos[0] photo.get(maxheight=500, maxwidth=500) image_url = photo.url element = { "title": place.name.encode('utf-8'), "image_url": image_url, "subtitle": "{} by walking. {}.".format(timeaway, disaway), "buttons": [{ "title": "Open in Maps", "type": "web_url", "url": place.url, "messenger_extensions": 'true', "webview_height_ratio": "tall", }] } element = json.dumps(element) elements.append(element) data = to_json({ "recipient": { "id": recipient.get_id() }, "message": { "attachment": { "type": "template", "payload": { "template_type": "list", "top_element_style": "compact", "elements": elements } } } }) else: data = to_json({ "recipient": { "id": recipient.get_id() }, "message": { "text": "Couldn't find {}".format(search_words) } }) MessageHandler.messagerequestpost(token, data)
def __init__(self,frameworkDir,verbosity='all',interactive=Interaction.No): """ Constructor @ In, frameworkDir, string, absolute path to framework directory @ In, verbosity, string, optional, general verbosity level @ In, interactive, Interaction, optional, toggles the ability to provide an interactive UI or to run to completion without human interaction @ Out, None """ self.FIXME = False #set the numpy print threshold to avoid ellipses in array truncation np.set_printoptions(threshold=np.inf) #establish message handling: the error, warning, message, and debug print handler self.messageHandler = MessageHandler.MessageHandler() self.verbosity = verbosity callerLength = 25 tagLength = 15 suppressErrs = False self.messageHandler.initialize({'verbosity':self.verbosity, 'callerLength':callerLength, 'tagLength':tagLength, 'suppressErrs':suppressErrs}) readtime = datetime.datetime.fromtimestamp(self.messageHandler.starttime).strftime('%Y-%m-%d %H:%M:%S') sys.path.append(os.getcwd()) #this dictionary contains the general info to run the simulation self.runInfoDict = {} self.runInfoDict['DefaultInputFile' ] = 'test.xml' #Default input file to use self.runInfoDict['SimulationFiles' ] = [] #the xml input file self.runInfoDict['ScriptDir' ] = os.path.join(os.path.dirname(frameworkDir),"scripts") # the location of the pbs script interfaces self.runInfoDict['FrameworkDir' ] = frameworkDir # the directory where the framework is located self.runInfoDict['RemoteRunCommand' ] = os.path.join(frameworkDir,'raven_qsub_command.sh') self.runInfoDict['NodeParameter' ] = '-f' # the parameter used to specify the files where the nodes are listed self.runInfoDict['MPIExec' ] = 'mpiexec' # the command used to run mpi commands self.runInfoDict['WorkingDir' ] = '' # the directory where the framework should be running self.runInfoDict['TempWorkingDir' ] = '' # the temporary directory where a simulation step is run self.runInfoDict['NumMPI' ] = 1 # the number of mpi process by run self.runInfoDict['NumThreads' ] = 1 # Number of Threads by run self.runInfoDict['numProcByRun' ] = 1 # Total number of core used by one run (number of threads by number of mpi) self.runInfoDict['batchSize' ] = 1 # number of contemporaneous runs self.runInfoDict['internalParallel' ] = False # activate internal parallel (parallel python). If True parallel python is used, otherwise multi-threading is used self.runInfoDict['ParallelCommand' ] = '' # the command that should be used to submit jobs in parallel (mpi) self.runInfoDict['ThreadingCommand' ] = '' # the command should be used to submit multi-threaded self.runInfoDict['totalNumCoresUsed' ] = 1 # total number of cores used by driver self.runInfoDict['queueingSoftware' ] = '' # queueing software name self.runInfoDict['stepName' ] = '' # the name of the step currently running self.runInfoDict['precommand' ] = '' # Add to the front of the command that is run self.runInfoDict['postcommand' ] = '' # Added after the command that is run. self.runInfoDict['delSucLogFiles' ] = False # If a simulation (code run) has not failed, delete the relative log file (if True) self.runInfoDict['deleteOutExtension'] = [] # If a simulation (code run) has not failed, delete the relative output files with the listed extension (comma separated list, for example: 'e,r,txt') self.runInfoDict['mode' ] = '' # Running mode. Curently the only mode supported is mpi but others can be added with custom modes. self.runInfoDict['Nodes' ] = [] # List of node IDs. Filled only in case RAVEN is run in a DMP machine self.runInfoDict['expectedTime' ] = '10:00:00' # How long the complete input is expected to run. self.runInfoDict['logfileBuffer' ] = int(io.DEFAULT_BUFFER_SIZE)*50 # logfile buffer size in bytes self.runInfoDict['clusterParameters' ] = [] # Extra parameters to use with the qsub command. self.runInfoDict['maxQueueSize' ] = None #Following a set of dictionaries that, in a manner consistent with their names, collect the instance of all objects needed in the simulation #Theirs keywords in the dictionaries are the the user given names of data, sampler, etc. #The value corresponding to a keyword is the instance of the corresponding class self.stepsDict = {} self.dataDict = {} self.samplersDict = {} self.modelsDict = {} self.distributionsDict = {} self.dataBasesDict = {} self.functionsDict = {} self.filesDict = {} # for each file returns an instance of a Files class self.metricsDict = {} self.OutStreamManagerPlotDict = {} self.OutStreamManagerPrintDict = {} self.stepSequenceList = [] #the list of step of the simulation #list of supported queue-ing software: self.knownQueueingSoftware = [] self.knownQueueingSoftware.append('None') self.knownQueueingSoftware.append('PBS Professional') #Dictionary of mode handlers for the self.__modeHandlerDict = CustomModes.modeHandlers #self.__modeHandlerDict['mpi'] = CustomModes.MPISimulationMode #self.__modeHandlerDict['mpilegacy'] = CustomModes.MPILegacySimulationMode #this dictionary contain the static factory that return the instance of one of the allowed entities in the simulation #the keywords are the name of the module that contains the specialization of that specific entity self.addWhatDict = {} self.addWhatDict['Steps' ] = Steps self.addWhatDict['DataObjects' ] = DataObjects self.addWhatDict['Samplers' ] = Samplers self.addWhatDict['Optimizers' ] = Optimizers self.addWhatDict['Models' ] = Models self.addWhatDict['Distributions' ] = Distributions self.addWhatDict['Databases' ] = Databases self.addWhatDict['Functions' ] = Functions self.addWhatDict['Files' ] = Files self.addWhatDict['Metrics' ] = Metrics self.addWhatDict['OutStreams' ] = {} self.addWhatDict['OutStreams' ]['Plot' ] = OutStreams self.addWhatDict['OutStreams' ]['Print'] = OutStreams #Mapping between an entity type and the dictionary containing the instances for the simulation self.whichDict = {} self.whichDict['Steps' ] = self.stepsDict self.whichDict['DataObjects' ] = self.dataDict self.whichDict['Samplers' ] = self.samplersDict self.whichDict['Optimizers' ] = self.samplersDict self.whichDict['Models' ] = self.modelsDict self.whichDict['RunInfo' ] = self.runInfoDict self.whichDict['Files' ] = self.filesDict self.whichDict['Distributions' ] = self.distributionsDict self.whichDict['Databases' ] = self.dataBasesDict self.whichDict['Functions' ] = self.functionsDict self.whichDict['Metrics' ] = self.metricsDict self.whichDict['OutStreams'] = {} self.whichDict['OutStreams']['Plot' ] = self.OutStreamManagerPlotDict self.whichDict['OutStreams']['Print'] = self.OutStreamManagerPrintDict # The QApplication ## The benefit of this enumerated type is that anything other than ## Interaction.No will evaluate to true here and correctly make the ## interactive app. if interactive: self.app = InteractiveApplication([],self.messageHandler, interactive) else: self.app = None #the handler of the runs within each step self.jobHandler = JobHandler() #handle the setting of how the jobHandler act self.__modeHandler = SimulationMode(self.messageHandler) self.printTag = 'SIMULATION' self.raiseAMessage('Simulation started at',readtime,verbosity='silent') self.pollingThread = threading.Thread(target=self.jobHandler.startLoop) ## This allows RAVEN to exit when the only thing left is the JobHandler ## This should no longer be necessary since the jobHandler now has an off ## switch that this object can flip when it is complete, however, if ## simulation fails before it is finished, we should probably still ensure ## that this thread is killed as well, so maybe it is best to keep it for ## now. self.pollingThread.daemon = True self.pollingThread.start()
def setUp(self): self.handler = MessageHandler.MessageHandler("shizuka.client.Mulder", testing=True)
def send_message_reddit(token, recipient, text, reddit): """Send the message text to recipient with id recipient. """ subreddit_name = "" if ("meme" in str(text.lower())): subreddit_name = "meirl" elif ("rarepuppers" in str(text.lower()) or "dog" in str(text.lower()) or "puppers" in str(text.lower())): subreddit_name = "rarepuppers" elif ("black") in str(text.lower()) or "blackpeople" in str(text.lower()): subreddit_name = "blackpeopletwitter" elif ("christian") in str(text.lower()) or "dankchristian" in str( text.lower()): subreddit_name = "dankchristianmemes" elif ("started" in str(text.lower()) or "get started" in str(text.lower())): data = to_json({ "recipient": { "id": recipient.get_id() }, "message": { "text": "Hi I'm MemeBot. I can send you memes, doggo pics and I can also help you look for shops etc. if you request." .encode("utf-8") } }) MessageHandler.messagerequestpost(token, data) else: print("Unknown Subreddit.") data = to_json({ "recipient": { "id": recipient }, "message": { "text": "Unknown Meme Source." } }) MessageHandler.messagerequestpost(token, data) if (subreddit_name != ""): for submission in reddit.subreddit(subreddit_name).hot(limit=None): if (submission.link_flair_css_class == 'image') or ((submission.is_self != True) and ((".jpg" in submission.url) or (".png" in submission.url))): user_posts = recipient.get_posts() if (user_posts is None): user_posts = [] if (next( (post for post in user_posts if post.get_id() == submission.id), None) is None): recipient.addposts(Post(submission.id, submission.url)) payload = submission.url break else: continue data = to_json({ "recipient": { "id": recipient.get_id() }, "message": { "attachment": { "type": "image", "payload": { "url": payload } }, "quick_replies": qr.quick_replies_list_reddit } }) MessageHandler.messagerequestpost(token, data)
class GameManager(object): def __init__(self, gametype, pgui): self.gui = pgui self.filesystem = FileSystem() self.iohandler = IOHandler(gametype, pgui) self.mapmanager = MapManager(self.filesystem.getData('map')) self.mapmanager.getVisibleObjects() self.messagehandler = MessageHandler( self.filesystem.getData("messages")) self.gamerun = False self.securitycamera = True self.talked = False def start(self): msghandler = self.messagehandler iohandler = self.iohandler if self.gui is None: # Tutorial p = self.mapmanager.getPlayer() iohandler.setOutput(msghandler.getMessage("introduction-welcome")) name = iohandler.getInput( msghandler.getMessage("introduction-name")) p.setName(name) iohandler.setOutput( msghandler.getMessage("introduction-personalwelcome").replace( "%name%", p.getName())) iohandler.setOutput(msghandler.getMessage("introduction-help")) res = iohandler.getInput( msghandler.getMessage("introduction-helpcommands")) while res != "help commands": res = iohandler.getInput( msghandler.getMessage( "general-invalidintroductionhelpcommand")) iohandler.setOutput(msghandler.getMessage("general-seperator")) iohandler.setOutput( msghandler.getMessage("commands-commands-info")) iohandler.setOutput(msghandler.getMessage("introduction-end")) # Game begin self.gamerun = True while self.gamerun: iohandler.setOutput(msghandler.getMessage("general-seperator")) input = self.iohandler.getInput( msghandler.getMessage("general-input")) self.__handleCommand(input) else: msg = msghandler.getMessage("introduction-welcome") msg = msg + "\n" + msghandler.getMessage("introduction-help") msg = msg + "\n" + msghandler.getMessage( "introduction-helpcommands") self.gui.write(msg) self.gui.start() def inputtrigger(self): input = self.iohandler.getInput( self.messagehandler.getMessage("general-input")) self.__handleCommand(input) # TODO: REMOVE L2-KARTE FROM DEFAULT INVENTORY def __handleCommand(self, input: str): msghandler = self.messagehandler iohandler = self.iohandler rawcommand = input.split(" ") command = rawcommand[0] args = rawcommand[1:] if command == "help" and len(args) == 1: iohandler.setOutput( msghandler.getMessage("commands-" + args[0] + "-info")) elif command == "quit": exit(0) elif command == "commands": iohandler.setOutput( msghandler.getMessage("commands-commands-info")) elif command == "left": self.mapmanager.rotatePlayer("left") direction = msghandler.getMessage("turn-left") facing = msghandler.getMessage( "turn-" + self.mapmanager.getPlayer().getFacing()) msg = msghandler.getMessage("turn-general").replace( "%direction%", direction).replace("%facing%", facing) iohandler.setOutput(msg) elif command == "right": self.mapmanager.rotatePlayer("right") direction = msghandler.getMessage("turn-right") facing = msghandler.getMessage( "turn-" + self.mapmanager.getPlayer().getFacing()) msg = msghandler.getMessage("turn-general").replace( "%direction%", direction).replace("%facing%", facing) iohandler.setOutput(msg) elif command == "lookaround": objects = self.mapmanager.getVisibleObjects() for o in objects: direction = o[2] objtype = o[0] msg = "" # left if direction == 0: if objtype == "wall": msg = msghandler.getMessage("lookaround-left").replace( "%object%", msghandler.getMessage("lookaround-wall")) elif objtype == "door": msg = msghandler.getMessage("lookaround-left").replace( "%object%", msghandler.getMessage("lookaround-door")) msg = msg + "\n" + msghandler.getMessage( "lookaround-doorname").replace( "%doorname%", o[1].getName()) msg = msg + "\n" + msghandler.getMessage( "lookaround-doorstatus").replace( "%status%", msghandler.getMessage("lookaround-" + o[1].getStatus())) elif objtype == "object": msg = msghandler.getMessage("lookaround-left").replace( "%object%", o[1].getName()) elif objtype == "narrator": msg = msghandler.getMessage("lookaround-left").replace( "%object%", o[1].getName()) # front elif direction == 1: if objtype == "wall": msg = msghandler.getMessage( "lookaround-front").replace( "%object%", msghandler.getMessage("lookaround-wall")) elif objtype == "door": msg = msghandler.getMessage( "lookaround-front").replace( "%object%", msghandler.getMessage("lookaround-door")) msg = msg + "\n" + msghandler.getMessage( "lookaround-doorname").replace( "%doorname%", o[1].getName()) msg = msg + "\n" + msghandler.getMessage( "lookaround-doorstatus").replace( "%status%", msghandler.getMessage("lookaround-" + o[1].getStatus())) elif objtype == "object": msg = msghandler.getMessage( "lookaround-front").replace( "%object%", o[1].getName()) elif objtype == "narrator": msg = msghandler.getMessage( "lookaround-front").replace( "%object%", o[1].getName()) # right elif direction == 2: if objtype == "wall": msg = msghandler.getMessage( "lookaround-right").replace( "%object%", msghandler.getMessage("lookaround-wall")) elif objtype == "door": msg = msghandler.getMessage( "lookaround-right").replace( "%object%", msghandler.getMessage("lookaround-door")) msg = msg + "\n" + msghandler.getMessage( "lookaround-doorname").replace( "%doorname%", o[1].getName()) msg = msg + "\n" + msghandler.getMessage( "lookaround-doorstatus").replace( "%status%", msghandler.getMessage("lookaround-" + o[1].getStatus())) elif objtype == "object": msg = msghandler.getMessage( "lookaround-right").replace( "%object%", o[1].getName()) elif objtype == "narrator": msg = msghandler.getMessage( "lookaround-right").replace( "%object%", o[1].getName()) if len(msg) > 0: iohandler.setOutput(msg) else: iohandler.setOutput( msghandler.getMessage("lookaround-nothing")) elif command == "move": objects = self.mapmanager.getVisibleObjects() obj = None msg = "" for o in objects: direction = o[2] objtype = o[0] if direction == 1: if objtype == "door": if o[1].getStatus() is not "open": msg = msghandler.getMessage( "lookaround-nomove") + " " obj = o break else: if o[1].getName() == "Portal": self.gamerun = False iohandler.setOutput( msghandler.getMessage("general-portalend")) return else: msg = msghandler.getMessage( "lookaround-nomove") + " " obj = o break if obj is not None: objtype = obj[0] if objtype == "wall": msg = msg + msghandler.getMessage( "lookaround-front").replace( "%object%", msghandler.getMessage("lookaround-wall")) elif objtype == "door": if obj[1].getStatus() is not "open": msg = msg + msghandler.getMessage( "lookaround-front").replace( "%object%", msghandler.getMessage("lookaround-door")) elif objtype == "object": msg = msg + msghandler.getMessage( "lookaround-front").replace("%object%", obj[1].getName()) elif objtype == "narrator": msg = msg + msghandler.getMessage( "lookaround-front").replace("%object%", obj[1].getName()) if len(msg) > 0: iohandler.setOutput(msg) else: p = self.mapmanager.getPlayer() pos = p.getPosition() facing = p.getFacing() if facing == "n": pos = [pos[0], pos[1] + 1] elif facing == "e": pos = [pos[0] + 1, pos[1]] elif facing == "s": pos = [pos[0], pos[1] - 1] elif facing == "w": pos = [pos[0] - 1, pos[1]] p.setPosition(pos) if pos == [6, 15] or pos == [7, 15]: if self.securitycamera: self.gamerun = False iohandler.setOutput( msghandler.getMessage("general-gamefailded")) return iohandler.setOutput(msghandler.getMessage("lookaround-move")) elif command == "goto" and len(args) >= 2: pos = [int(args[0]), int(args[1])] objatpos = self.mapmanager.objectAtPosition(pos) if objatpos is not None: iohandler.setOutput(msghandler.getMessage("goto-nomove")) else: p = self.mapmanager.getPlayer() p.setPosition(pos) iohandler.setOutput( msghandler.getMessage("goto-move").replace( "%x%", args[0]).replace("%y%", args[1])) pass elif command == "showinventory": p = self.mapmanager.getPlayer() inv = p.getInventory() if len(inv) == 0: iohandler.setOutput(msghandler.getMessage("inventory-noitems")) else: msg = msghandler.getMessage("inventory-show") for o in inv: msg = msg + "\n" + o.getName() iohandler.setOutput(msg) elif command == "door" and len(args) >= 1: if not (args[0] == "open" or args[0] == "close"): iohandler.setOutput( msghandler.getMessage("general-invalidcommand")) return objects = self.mapmanager.getVisibleObjects() obj = None for o in objects: direction = o[2] objtype = o[0] if direction == 1 and objtype == "door": obj = o[1] break if obj is None: iohandler.setOutput(msghandler.getMessage("door-nodoor")) return status = obj.getStatus() if status == "broken": iohandler.setOutput(msghandler.getMessage("door-broken")) return if args[0] == "open": if status == "open": iohandler.setOutput( msghandler.getMessage("door-alreadystatus").replace( "%status%", msghandler.getMessage("lookaround-open"))) return elif type(obj) == CardDoor: p = self.mapmanager.getPlayer() inv = p.getInventory() # Find the highest keycard in inventory keylevel = "" for o in inv: if "-Karte" in o.getName(): kl = o.getName().replace("-Karte", "") if len(kl) == 2: if len(keylevel) > 0: kllist = kl.split('') keylevellist = keylevel.split('') if kllist[1] > keylevellist[1]: keylevel = kl else: keylevel = kl # Test for exitdoor: if obj.getName() == "Ausgang": found = False for o in inv: if o.getName() == "USB-Stick": found = True if found: res = obj.open(keylevel) if not res: iohandler.setOutput( msghandler.getMessage("door-noperm")) return else: self.gamerun = False iohandler.setOutput( msghandler.getMessage( "general-gamefinished")) return else: iohandler.setOutput( msghandler.getMessage("door-noexit")) return res = obj.open(keylevel) if not res: iohandler.setOutput( msghandler.getMessage("door-noperm")) else: iohandler.setOutput( msghandler.getMessage("door-action").replace( "%action%", msghandler.getMessage("door-opened"))) # Find a matching door code in the inventory elif type(obj) == CodeDoor: p = self.mapmanager.getPlayer() inv = p.getInventory() res = False for o in inv: if "Pincodezettel-" in o.getName(): code = o.getName().replace("Pincodezettel-", "") res = obj.open(code) if res: iohandler.setOutput( msghandler.getMessage("door-action"). replace( "%action%", msghandler.getMessage("door-opened"))) return if not res: iohandler.setOutput( msghandler.getMessage("door-noperm")) else: obj.open() elif args[0] == "close": if status == "close": iohandler.setOutput( msghandler.getMessage("door-alreadystatus").replace( "%status%", msghandler.getMessage("lookaround-close"))) return else: obj.close() iohandler.setOutput( msghandler.getMessage("door-action").replace( "%action%", msghandler.getMessage("door-closed"))) elif command == "getposition": p = self.mapmanager.getPlayer() pos = p.getPosition() iohandler.setOutput( msghandler.getMessage("goto-position").replace( "%x%", str(pos[0])).replace("%y%", str(pos[1]))) elif command == "facing": p = self.mapmanager.getPlayer() facing = p.getFacing() facingmsg = msghandler.getMessage("turn-" + facing) iohandler.setOutput( msghandler.getMessage("turn-facing").replace( "%facing%", facingmsg)) elif command == "object" and len(args) >= 1: if not (args[0] == "showinventory" or args[0] == "getitem" or args[0] == "putitem" or args[0] == "move"): iohandler.setOutput( msghandler.getMessage("general-invalidcommand")) return objects = self.mapmanager.getVisibleObjects() obj = None for o in objects: direction = o[2] objtype = o[0] if direction == 1 and objtype == "object": obj = o[1] break if obj is None: iohandler.setOutput(msghandler.getMessage("object-noobject")) return if args[0] == "showinventory": inv = obj.getInventory() if len(inv) == 0: iohandler.setOutput( msghandler.getMessage("object-noitems").replace( "%objectname%", obj.getName())) return else: msg = msghandler.getMessage("object-show").replace( "%objectname%", obj.getName()) for o in inv: msg = msg + "\n" + o.getName() iohandler.setOutput(msg) elif args[0] == "getitem" and len(args) >= 2: inv = obj.getInventory() p = self.mapmanager.getPlayer() pinv = p.getInventory() for o in inv: if o.getName() == args[1]: inv.remove(o) obj.setInventory(inv) pinv.append(o) p.setInventory(pinv) iohandler.setOutput( msghandler.getMessage("object-get").replace( "%item%", o.getName()).replace("%objectname%", obj.getName())) return iohandler.setOutput( msghandler.getMessage("object-noget").replace( "%name%", args[1]).replace("%objectname%", obj.getName())) elif args[0] == "putitem" and len(args) >= 2: inv = obj.getInventory() p = self.mapmanager.getPlayer() pinv = p.getInventory() for o in pinv: if o.getName() == args[1]: pinv.remove(o) p.setInventory(pinv) inv.append(o) obj.setInventory(inv) iohandler.setOutput( msghandler.getMessage("object-put").replace( "%item%", o.getName()).replace("%objectname%", obj.getName())) return iohandler.setOutput( msghandler.getMessage("object-noput").replace( "%name%", args[1])) elif args[0] == "move" and len(args) >= 2: if not (args[1] == "left" or args[1] == "right" or args[1] == "forward"): iohandler.setOutput( msghandler.getMessage("general-invalidcommand")) return p = self.mapmanager.getPlayer() ppos = p.getPosition() pfacing = p.getFacing() if not obj.isMovable(): iohandler.setOutput( msghandler.getMessage("object-nomove").replace( "%objectname%", obj.getName())) return objpos = obj.getPosition() postomove = objpos if pfacing == "n": if args[1] == "left": postomove = [objpos[0] - 1, objpos[1]] elif args[1] == "right": postomove = [objpos[0] + 1, objpos[1]] elif args[1] == "forward": postomove = [objpos[0], objpos[1] + 1] elif pfacing == "e": if args[1] == "left": postomove = [objpos[0], objpos[1] + 1] elif args[1] == "right": postomove = [objpos[0], objpos[1] - 1] elif args[1] == "forward": postomove = [objpos[0] + 1, objpos[1]] elif pfacing == "s": if args[1] == "left": postomove = [objpos[0] + 1, objpos[1]] elif args[1] == "right": postomove = [objpos[0] - 1, objpos[1]] elif args[1] == "forward": postomove = [objpos[0], objpos[1] - 1] elif pfacing == "w": if args[1] == "left": postomove = [objpos[0], objpos[1] - 1] elif args[1] == "right": postomove = [objpos[0], objpos[1] + 1] elif args[1] == "forward": postomove = [objpos[0] - 1, objpos[1]] objatpos = self.mapmanager.objectAtPosition(postomove) if objatpos is not None: objname = "" if type(objatpos) == list: objname = msghandler.getMessage("lookaround-wall") elif type(objatpos) == Object: objname = objatpos.getName() else: objname = msghandler.getMessage("lookaround-door") iohandler.setOutput( msghandler.getMessage("object-nomoveblocked").replace( "%objectname%", objname)) return obj.setPosition(postomove) dir = msghandler.getMessage("turn-" + args[1]) iohandler.setOutput( msghandler.getMessage("object-moved").replace( "%direction%", dir)) elif command == "hackserver": objects = self.mapmanager.getVisibleObjects() obj = None msg = "" for o in objects: direction = o[2] objtype = o[0] if direction == 1: if type(o[1]) == Object: if o[1].getName() == "Server": obj = o[1] break if not obj: msg = msghandler.getMessage("server-noserver") else: if not self.securitycamera: msg = msghandler.getMessage("server-alreadyhacked") else: self.securitycamera = False msg = msghandler.getMessage("server-hacked") iohandler.setOutput(msg) elif command == "talk": objects = self.mapmanager.getVisibleObjects() obj = None msg = "" for o in objects: direction = o[2] objtype = o[0] if direction == 1: if objtype == "narrator": obj = o[1] if obj is None: msg = msghandler.getMessage("talk-notalk") else: if self.talked: msg = msghandler.getMessage("talk-talk") else: msg = msghandler.getMessage("talk-talk") self.talked = True p = self.mapmanager.getPlayer() inv = p.getInventory() key = Object("L2-Karte", 999, False, True, None, None) inv.append(key) p.setInventory(inv) msg = msg + "\n" + msghandler.getMessage("talk-keycard") iohandler.setOutput(msg) else: iohandler.setOutput( msghandler.getMessage("general-invalidcommand"))