def read_from_client(s, address): ''' 处理客户端传入的命令,将他们发送到命令解析器中解析后发送到命令处理器中处理 然后输出到客户端 Arguments: s {[type]} -- 客户端传入的命令 address {[type]} -- ''' while True: try: data = s.recvfrom(65536) # 从客户端读取socket套接字 if data is not None and data[0] is not None: try: command_arr = parse_command(data[0].decode('utf-8'), 0) # 解析客户端传入的命令 response = handle_command(command_arr) s.send(bytes(response, 'utf-8')) except socket.error: raise except Exception as e: s.send( bytes( resp_error( "An unspecified error occurred. {0}".format( str(e))), 'utf-8')) except socket.error: print(socket.error) break s.close()
def handle_message(): #return Response('suc') if request.get_json().get('callback_query'): ui.handle_message() return Response('success') print("got message" + " " + request.get_json()['message']['text']) chat_id = request.get_json()['message']['chat']['id'] message = request.get_json()['message']['text'] response = parse_command(message, chat_id) return Response("success")
def handle_message(): print("got message") message_text: str = request.get_json()['message']['text'] print(message_text) response = command_parser.parse_command(message_text, data) db_manipulator.DataBase.write_data() chat_id = request.get_json()['message']['chat']['id'] res = requests.get( "https://api.telegram.org/bot{}/sendMessage?chat_id={}&text={}'". format(TOKEN, chat_id, response)) return Response("success")
async def _accept_client(self, reader: StreamReader, writer: StreamWriter) -> None: addr: str = writer.get_extra_info('peername') print(f'Accepted client from {addr}') try: while True: data = await reader.readuntil(SEPARATOR_BINARY) log_received_message(data, writer) response: Union[str, bytes] = '' try: message = data.decode() if len(message.strip()) == 0: # ignore empty messages continue command_or_error = parse_command(message) if command_or_error.error: response = command_or_error.error else: command = command_or_error.command if isinstance(command, CommandSet): await process_set_command(command, reader, writer) response = execute_command(command, self._cache) except ValueError: print(f'Failed to decode message from {addr}') response = build_error_message('failed to decode message', fatal=False) await send_message(response, writer) except (MalformedMessageException, asyncio.LimitOverrunError): await send_message( build_error_message( 'unexpected message length or termination marker.', fatal=True), writer) except (asyncio.IncompleteReadError, ConnectionResetError): # client disconnected pass await close_connection(writer)
def run(socket, channels, cmds, nick): # buffer for some command received buff = "" num_workers = sum(len(v) for k, v in cmds.iteritems()) # TODO: what happens if I use all the workers? # TODO: don't let commands to run for more than one minute with futures.ProcessPoolExecutor(max_workers=num_workers) as executor: while len(channels): receive = socket.recv(4096) buff = buff + receive response = "" if receive: logging.debug(receive + ("" if "\n" == receive[len(receive) - 1] else "\n")) if -1 != buff.find("\n"): # get a full command from the buffer command = buff[0 : buff.find("\n")] buff = buff[buff.find("\n") + 1 :] # command's components after parsing components = command_parser.parse_command(command) to = send_to(command) if "PING" == components["action"]: response = [] response.append("PONG") response.append(":" + components["arguments"]) elif "PRIVMSG" == components["action"]: if "." == components["arguments"][0] or "!" == components["arguments"][0]: # a command from a user only makes sense if it starts # with an exclamation mark pos = components["arguments"].find(" ") if -1 == pos: pos = len(components["arguments"]) # get the command issued to the bot without the "!" cmd = components["arguments"][1:pos] callable_cmd = get_cmd(cmd, cmds["user"]) if callable_cmd: run_cmd(socket, executor, to, callable_cmd, components) else: callable_cmd = get_cmd(cmd, cmds["core"]) if callable_cmd: try: response = callable_cmd(socket, components) except Exception as e: response = err.C_EXCEPTION.format(callable_cmd.__name__) logging.error(str(e)) # run auto commands for cmd in config.cmds["auto"]: callable_cmd = get_cmd(cmd, cmds["auto"]) if callable_cmd: run_cmd(socket, executor, to, callable_cmd, components) elif "KICK" == components["action"] and nick == components["action_args"][1]: channels.remove(components["action_args"][0]) elif ( "QUIT" == components["action"] and -1 != components["arguments"].find("ERROR :Closing Link") and -1 != components["arguments"].find("Ping timeout: ") ): channels[:] = [] # this call is still necessary in case that a PONG response or a # core command response should be sent, every other response is # sent when the futures finish working from their respective # thread send_response(response, to, socket) buff = ""
{'ID': 'i', 'name': 'interpolate', 'type': StringType, 'default': '3', 'constraint': 'interpolate in "234lLqQcCbBsS"'}, {'ID': 's', 'name': 'sampling', 'type': FloatType, 'constraint': 'sampling>0.0', 'default': 5.0}, {'ID': 'w', 'name': 'wingExt', 'type': FloatType, 'constraint': 'wingExt>0.0', 'default': 5.0}, {'ID': 'x', 'name': 'xLimits', 'type': Interval, 'constraint': 'xLimits.lower>=0.0'}, {'ID': 'n', 'name': 'nGrids', 'type': IntType, 'default': 3, 'constraint': 'nGrids>0'}, {'ID': 'g', 'name': 'gridRatio', 'type': IntType, 'default': 8, 'constraint': 'gridRatio in [4,8]'}, {'ID': 'q', 'name': 'quad', 'type': StringType, 'default': 'T', 'constraint': 'quad.upper() in ["T","S","H"]'}, {'ID': 'W', 'name': 'nWidths', 'type': FloatType, 'default': 25.0,'constraint': 'nWidths>2.0'}, {'ID': 'r', 'name': 'flipUpDown'}, {'ID': 'y', 'name': 'yOnly'}, {'ID': 'plot'}, {'ID': 'nm', 'name': 'nanometer'}, {'ID': 'v', 'name': 'verbose'} ] inFiles, options, commentChar, outFile = parse_command (opts,(2,99)) if options.has_key('h'): print __doc__%globals(); raise SystemExit, " end of lbl2od help" # translate some options to boolean flags for key in ['yOnly', 'nanometer', 'plot', 'flipUpDown', 'verbose']: options[key] = options.has_key(key) if commonExtension(inFiles): print '\nWARNING: all input files have the same extension, first file probably NOT an atmospheric data file!!!\n' # unpack list of input files atmFile, lineFiles = inFiles[0], inFiles[1:] # optionally already import module used at very end (check availablity of netcdf before starting a lengthy job) if outFile and os.path.splitext(outFile)[1].lower() in ('.nc', '.ncdf', '.netcdf'): try:
#################################################################################################################################### if (__name__ == "__main__"): from IO import open_outFile from command_parser import parse_command, standardOptions from pairTypes import Interval opts = standardOptions + [ # h=help, c=commentChar, o=outFile {'ID': 'ToA', 'name': 'zToA', 'type': FloatType, 'constraint': 'zToA>0.0'}, {'ID': 'f', 'name': 'format', 'type': StringType}, {'ID': 'p', 'name': 'pRatio', 'type': FloatType, 'constraint': 'pRatio>1.0'}, {'ID': 'x', 'name': 'extract', 'type': StringType, 'default': '*'}, {'ID': 'z', 'name': 'zGrid', 'type': StringType}, {'ID': 'where', 'type': StringType}, {'ID': 'v', 'name': 'verbose'}, {'ID': 'saveVMR'}, {'ID': 'pT'} ] atmFiles, options, commentChar, outFile = parse_command (opts,[1,99]) if options.has_key('h'): print __doc__%globals(); raise SystemExit, "end of atmos help" else: options['verbose'] = options.has_key('verbose') options['saveVMR'] = options.has_key('saveVMR') options['pT'] = options.has_key('pT') _atmos_ (atmFiles, outFile, commentChar, **options)
dict(ID='m', name='molecule', type=str), # option called "atlas" to avoid conflict with matplotlib function "plot" dict(ID='plot', name='lineAtlas', type=str, default='S', constraint='lineAtlas in "STEansdL"'), dict(ID='p', name='pressure', type=float, constraint='pressure>0.0'), dict(ID='T', name='temperature', type=float, constraint='temperature>0.0'), dict(ID='x', name='xLimits', type=Interval, constraint='xLimits.lower>=0.0'), dict(ID='v', name='verbose') ] lineFiles, options, commentChar, outFile = parse_command(opts, (1, 99)) if 'h' in options: raise SystemExit(__doc__ + "\n end of lines help") if 'about' in options: raise SystemExit(_LICENSE_) options['verbose'] = 'verbose' in options if 'lineAtlas' in options: figure() _lines_(lineFiles, outFile, commentChar, **options)
}, {"ID": "d", "name": "outDir", "type": StringType}, {"ID": "i", "name": "isotope", "type": IntType, "constraint": "isotope>=0", "default": 0}, {"ID": "m", "name": "molecule", "type": StringType, "constraint": 'len(re.split("[,;\s]",molecule))==1'}, {"ID": "S", "name": "strMin", "type": FloatType, "constraint": "strMin>=0.0", "default": 0.0}, {"ID": "x", "name": "xLimits", "type": Interval, "constraint": "xLimits.lower>=0.0"}, { "ID": "X", "name": "xUnit", "type": StringType, "default": "cm-1", "constraint": "xUnit in ['cm-1', 'mue', 'nm', 'Hz', 'kHz', 'MHz', 'GHz', 'THz']", }, ] files, options, commentChar, outFile = parse_command(opts, 1) if options.has_key("h"): print __doc__ raise SystemExit if options.has_key("help"): print __doc__[:-42] + more_help raise SystemExit, " end of extract help" outDir = options.pop("outDir", None) format = options.pop("format", None) # replace format shortcut with 'full' name if format == "vSEb": format = "vSEasni" lines = extract_lines(files, **options)