def handleMessage(self, message: psclient.Message): """Handles incoming messages from the server Args: message (psclient.Message): the Message object to handle """ if message.type in prefs.getPref('blacklistedTypes'): return formatted: Union[str, HTML] = message.raw if message.type == 'chat' and message.senderName and message.body and message.room: time: str = f"[{str(datetime.utcfromtimestamp(int(message.time)).time())}] " if message.time else "" toPrint = [ f"({message.room.id}) {time}{message.senderName.strip()}: {message.body}" ] if '|raw|' in message.body: split = message.body.split('|raw|') toPrint[0] = toPrint[0].replace(message.body, split[0]) for item in split[1:]: toPrint.append(formatHTML(item)) return [printf(item) for item in toPrint] if message.type == 'pm' and message.senderName: if message.sender and message.sender.id != message.connection.this.id: formatted = f"(PM from {message.senderName.strip()}) {message.body}" if message.type in ['join', 'leave' ] and message.room and message.senderName: if prefs.getPref("showjoins"): formatted = f"{message.senderName.strip()} {'joined' if message.type == 'join' else 'left'} {message.room.id}" if message.type in ['raw', 'html', 'uhtml'] and message.raw: index = 3 if message.type == 'uhtml' else 2 split = message.raw.split('|', index) formatted = formatHTML( f"{(split[index - 1] + ': ') if message.type == 'uhtml' else ''}{split[index]}" ) printf(formatted)
def mainLoop(*args: psclient.PSConnection) -> None: """Gets run when we connect to PS! """ if not args: return conn: psclient.PSConnection = args[0] hasAutojoined: bool = False while True: if conn.isLoggedIn and not hasAutojoined: autojoins = prefs.getPref("autojoins") if autojoins: for room in autojoins: conn.roomList.add(psclient.Room(room, conn)) hasAutojoined = True printf("Logged in!") command: Union[str, None] = None try: interface.handleMessage(messageQueue.get(block=False)) except queue.Empty: pass try: command = inputQueue.get(block=False) except queue.Empty: interface.isBusy = False if not command: continue if command[:len(interface.commandChar)] == interface.commandChar: split = command[len(interface.commandChar):].split(' ', 1) if split[0].lower() in interface.commands.keys(): interface.commands[split[0].lower()]( split[1] if len(split) > 1 else '') # invoke the command continue printf(f"Unknown command '{interface.commandChar}{split[0]}'") continue interface.send(command) interface.isBusy = False
async def process(): printf( HTML(f"<ansiwhite>connecting to <b>{host}:{port}</b></ansiwhite>\n")) client_stream = await trio.open_tcp_stream(host, port) async with client_stream: async with trio.open_nursery() as nursery: nursery.start_soon(sender, client_stream) nursery.start_soon(receiver, client_stream)
def eval(self, code: str) -> None: """Evaluates code and prints the result Args: code (str): the code """ try: printf(eval(code)) # pylint: disable=eval-used except Exception as err: logError(err)
def inputListener() -> None: """Listens for keyboard input """ while True: if not interface.isBusy: try: x = interface.prompt.prompt() except KeyboardInterrupt: printf(f"Use {interface.commandChar}exit to exit.") continue inputQueue.put(x) interface.isBusy = True
async def receiver(client_stream): while True: packet = await client_stream.receive_some(BUFSIZE) # data = msgpack.unpackb(packet, use_list=False, raw=False) status, message, as_json = parse_packet(packet) color = "ansigreen" if status == "OK" else "ansired" printf(HTML(f"\n>>\t<{color}><b>{status}</b></{color}>")) if as_json: message = highlight(message, JsonLexer(), TerminalFormatter()) printf(ANSI('\t' + message.replace("\n", "\n\t"))) await trio.sleep(0.1)
def unloadPlugin(self, plugin: str) -> None: """Unloads a plugin Args: plugin (str): the name of the plugin to unload """ plugin = plugin.lower().replace(' ', '') if not plugin: return logError("You must specify a plugin.") if plugin not in self.loadedPlugins: return logError("That plugin isn't loaded!") try: commands = importlib.import_module(plugin).commands # type: ignore for command in commands: if command in self.commands: del self.commands[command] self.loadedPlugins.remove(plugin) except ModuleNotFoundError: return logError(f"No plugin named {plugin} was found.") except Exception as err: return logError(err) pluginSettings: list = prefs.getPref("plugins") if pluginSettings and plugin in pluginSettings: pluginSettings.remove(plugin) prefs.setPref("plugins", pluginSettings) return printf(f"Plugin {plugin} unloaded!")
def loadPlugin(self, plugin: str) -> None: """Loads a plugin Args: plugin (str): the name of the plugin to load """ plugin = plugin.lower().replace(' ', '') if not plugin: return logError("You must specify a plugin.") if plugin in self.loadedPlugins: return logError("That plugin is already loaded.") pluginsPath: str = str(pathlib.Path('plugins').resolve()) if pluginsPath not in sys.path: sys.path.append(pluginsPath) try: self.commands.update( importlib.import_module(plugin).commands) # type: ignore self.loadedPlugins.add(plugin) except ModuleNotFoundError: return logError(f"No plugin named {plugin} was found.") except AttributeError: return logError("The plugin file is invalid." + \ f"Check that you have the latest version and that the file 'plugins/{plugin}.py' is correctly formatted") except Exception as err: return logError(err) pluginSettings: list = prefs.getPref("plugins") if not pluginSettings: pluginSettings = [] if plugin not in pluginSettings: pluginSettings.append(plugin) prefs.setPref("plugins", pluginSettings) return printf(f"Plugin {plugin} loaded!")
def logError(error: Union[str, Exception]) -> None: """Handles error logging Args: error (Union[str, Exception]): the error """ if isinstance(error, Exception): error = f"Error: {str(error)}" return printf(HTML(f"<ansired>{html.escape(error)}</ansired>"))
def dadJoke(arguments: str) -> None: """A command function Args: arguments (str): the arguments (for example, if a command is "%eval self.connection.this.id == 'Annika'", arguments would be "self.connection.this.id == 'Annika'") """ splits = ["I'm", "im", "i'm"] response = HTML( f"<ansired>You must include {', '.join(splits[:-1])}, or {splits[-1]} in your message.</ansired>" ) for split in splits: if split in arguments: thing = arguments.split(split, 1)[1] if not thing: continue if thing[0] != ' ': thing = ' ' + thing response = HTML(f"<ansigreen>Hi{thing}, I'm pokétext!</ansigreen>") printf(response)
def execute_entry(path): if not path: print('Unknown entry') return printf(HTML(f'<gray>> {path}</gray>')) is_file = not os.path.isdir(path) dir_name = os.path.dirname(path) try: if is_file: cwd = os.getcwd() os.chdir(dir_name) # TODO Handle paths with spaces prefix = 'start ' if os.name == 'nt' else 'open ' retcode = subprocess.run(prefix + str(path), shell=True) if is_file: os.chdir(cwd) except OSError as e: print(f'Execution failed: {e}')
break_dance='' def clear(): # from https://repl.it/talk/share/pyIDE/24797?order=new (examples/clrScrnEx.py) if os.name == 'nt': os.system("cls") else: os.system("clear") clear() print(os.getcwd()) if command_line: filename=sys.argv[1] else: printf(HTML('<pink><b>Choose a filename/filepath to create/edit</b></pink>')) filename=input('') if filename.startswith('/'): filename=os.getcwd()+filename else: filaname=os.getcwd()+'/'+filename clear() quit_it=False current='' if os.path.isfile(filename): fp=open(filename) current=fp.read()
def main(): if len(sys.argv) < 2: print('I need a path to the project\'s root') return 1 project_path = Path(sys.argv[1]) if not os.path.isdir(project_path): print('Invalid path') return 1 project_file = project_path / 'project.plik' if os.path.isfile(project_file): printf(HTML(f'<gray>Found project file at {project_file}</gray>')) # Init graphics imgui.create_context() window = _glfw_init(500, 1000) renderer = GlfwRenderer(window) __main_locals_marker = None def on_glfw_key(window, key, scancode, action, mods): renderer.keyboard_callback(window, key, scancode, action, mods) if action == glfw.RELEASE: if key in (glfw.KEY_PAUSE, glfw.KEY_SCROLL_LOCK): # Pretty slow I assume, but reliable frame = inspect.currentframe() while frame: if '__main_locals_marker' in frame.f_locals: break frame = frame.f_back ipshell(local_ns=frame.f_locals) # Need to set this after creating the renderer because by default it does its own hooks glfw.set_key_callback(window, on_glfw_key) # TODO state = State() state.project_path = project_path state.project_file = project_file app.prompt.start(state) running = True while not glfw.window_should_close(window) and running: glfw.poll_events() renderer.process_inputs() # TODO Render only when any events are detected to lower CPU usage imgui.new_frame() imgui.show_test_window() # state.window_width, state.window_height = glfw.get_window_size(window) # TODO Just set the font at the beginning! # with imgui.font(font): running = app.prompt.process_next_entry(state) gl.glClearColor(.1, .1, .1, .1) gl.glClear(gl.GL_COLOR_BUFFER_BIT) imgui.render() renderer.render(imgui.get_draw_data()) glfw.swap_buffers(window) renderer.shutdown() glfw.terminate()