def test_parse_01_response(self): """Test 0x01 command parsing. Values from https://github.com/openaps/openomni/wiki/Response-01 """ fmt1, _ = commands.parse_command( "011b13881008340a5002070002070002030000a3770003ab371f00ee87". decode("hex")) fmt2a, _ = commands.parse_command( "011502070002070002020000a3770003ab379f1f00ee87".decode("hex")) fmt2b, _ = commands.parse_command( "011502070002070002020000a64000097c279c1f08ced2".decode("hex")) for m in (fmt1, fmt2a, fmt2b): self.assertTrue(isinstance(m, commands.Message01Response)) self.assertEqual(fmt1.hardcode_bytes, "13881008340a5002070002070002") self.assertEqual(fmt1.state_byte, "03") self.assertEqual(fmt1.lot, "0000a377") self.assertEqual(fmt1.tid, "0003ab37") self.assertEqual(fmt1.pod_address, "1f00ee87") self.assertEqual(fmt2a.hardcode_bytes, "02070002070002") self.assertEqual(fmt2a.state_byte, "02") self.assertEqual(fmt2a.lot, "0000a377") self.assertEqual(fmt2a.tid, "0003ab37") self.assertEqual(fmt2a.pod_address, "1f00ee87") self.assertEqual(fmt2b.hardcode_bytes, "02070002070002") self.assertEqual(fmt2b.state_byte, "02") self.assertEqual(fmt2b.lot, "0000a640") self.assertEqual(fmt2b.tid, "00097c27") self.assertEqual(fmt2b.pod_address, "1f08ced2")
def play(): pc = Player_Character('player', 'start', 10, 6, 6, 7) room = get_room(pc.location) while pc.is_alive and not pc.victory: user_input = input("> ").lower().split() if not cmd.valid_command(user_input, pc): continue else: cmd.parse_command(user_input, pc)
def test_parsing_command(self): cmd = "/start with other args" self.assertEqual('/start', parse_command(cmd)) cmd = "/start@DnDCompanionBot" self.assertEqual('/start', parse_command(cmd)) cmd = "/start " self.assertEqual('/start', parse_command(cmd))
def commands(self): body = copy.copy(self.body) cmds = [] while body: cmd, body = parse_command(body) cmds.append(cmd) return cmds
def make_suggestions_and_shortcuts(self, env, obs, num_suggestions=None, num_shortcuts=None): if num_suggestions is None: num_suggestions = self.num_suggestions if num_shortcuts is None: num_shortcuts = self.num_shortcuts cache = self.cache shortcuts = [] def add_shortcut(m): h = m.format_with(["#"] * m.size) if useful_shortcut(h) and len( shortcuts) < num_shortcuts and h not in shortcuts: shortcuts.append(h) def useful_shortcut(h): return len(h) > 8 for register in env.registers: for m in register.contents: for h in messages.submessages(messages.strip_prefix(m), include_root=True): add_shortcut(h) def useful_suggestion(h): c = commands.parse_command(h) m = commands.parse_message(h) try: if c is not None: for m in c.messages(): m.instantiate(env.args) elif m is not None: m.instantiate(env.args) return True except messages.BadInstantiation: return False suggestions = best_dict_values(obs, cache, filter=useful_suggestion, n=num_suggestions) for h in suggestions: c = commands.parse_command(h) m = commands.parse_message(h) if c is not None: for m in c.messages(): for sub_m in messages.submessages(m, include_root=True): add_shortcut(sub_m) elif m is not None: for sub_m in messages.submessages(m, include_root=True): add_shortcut(sub_m) return suggestions, shortcuts
def handler(bot, update): command = parse_command(update.message.text) txt_args = ' '.join(update.message.text.split(' ')[1:]) try: command_handler(command)(bot, update, command, txt_args) except CommandNotFound: default_handler(bot, update, f'Command {command} not found') except CharacterNotFound: default_handler(bot, update, f'Character not found. Cannot execute {update.message.text}') except CampaignNotFound: default_handler(bot, update, f'Campaign not found. Theres must be an active campaign')
def useful_suggestion(h): c = commands.parse_command(h) m = commands.parse_message(h) try: if c is not None: for m in c.messages(): m.instantiate(env.args) elif m is not None: m.instantiate(env.args) return True except messages.BadInstantiation: return False
def webhook(event, context): """ Runs the Telegram webhook. """ bot = configure_telegram() logger.info(json.loads(event.get('body'))) if event.get('httpMethod') == 'POST' and event.get('body'): update = telegram.Update.de_json(json.loads(event.get('body')), bot) if not is_command(update): return OK_RESPONSE db = Database() chat_id = update.message.chat.id username = update.message.from_user.username if update.message.from_user.username else update.message.from_user.first_name command = parse_command(update.message.text) txt_args = ' '.join(update.message.text.split(' ')[1:]) try: command_handler(command)(bot, update, command, txt_args, username, chat_id, db) except (CommandNotFound, InvalidCommand): default_handler(bot, update, 'Invalid command or command not supported') except CharacterNotFound: default_handler(bot, update, 'Character not found. Cannot execute command') except CampaignNotFound: default_handler( bot, update, 'Campaign not found. There must be an active campaign') except json.JSONDecodeError: default_handler(bot, update, 'Error parsing JSON') except NotADM: default_handler( bot, update, f'Only the Dungeon Master can execute {command} command') #except Exception: # logger.error(sys.exc_info()[2]) # default_handler(bot, update, 'Unhandled error. Check server logs for more details') return OK_RESPONSE
def handler(bot, update): command = parse_command(update.message.text) txt_args = ' '.join(update.message.text.split(' ')[1:]) try: command_handler(command)(bot, update, command, txt_args) except (CommandNotFound, InvalidCommand): default_handler(bot, update, 'Invalid command') except CharacterNotFound: default_handler(bot, update, 'Character not found. Cannot execute command') except CampaignNotFound: default_handler( bot, update, f'Campaign not found. Theres must be an active campaign') except NotADM: default_handler( bot, update, f'Only the Dungeon Master can execute {command} command')
def test_parse_unknown_command(self): # Parse a 0x99 command with length 0x01 cmd, _ = commands.parse_command("990100".decode("hex")) self.assertTrue(isinstance(cmd, commands.UnknownCommand))
def test_parse_1d_response(self): resp, _ = commands.parse_command("1d18003e980000421fff".decode("hex")) self.assertTrue(isinstance(resp, commands.PodStatusResponse)) self.assertEqual(resp.minutes_active, 135) self.assertEqual(resp.reservoir_level, 50.0)
def test_parse_cancel(self): # Parse cancel temp basal from PDM cmd, _ = commands.parse_command("1f05156b93e8620028".decode("hex")) self.assertTrue(isinstance(cmd, commands.CancelCommand))
def on_privmsg(self, from_, message): if message.startswith('+'): message = message[1:] commands.parse_command(self, config, from_, from_[0], message)
def run_machine(state): command = None retval = None error = None error_cmd = None fixing_cmd = None while True: if state.budget_consumed >= state.budget and retval is None: budget_consumed = state.budget_consumed exhausted = budget_consumed >= state.nominal_budget command = commands.Interrupted(exhausted, command, budget_consumed=budget_consumed, state=state) retval = command.make_message() if retval is not None: if state.parent_cmd is None: return retval, state, command retval, state, command = state.parent_cmd.finish( retval, command, state.budget_consumed) else: def make_pre_suggestions(): pre_suggestions = state.pre_suggestions() if error_cmd is not None: pre_suggestions.append(error_cmd.string) return pre_suggestions if error is None: error_message = None else: if error_cmd is None: error_message = error else: error_message = "{}: {}".format(error, error_cmd.string) s = get_response(state, error_message=error_message, use_cache=state.use_cache, prompt=state.prompt, kind=state.kind, make_pre_suggestions=make_pre_suggestions) command = commands.parse_command(s) command = command.copy(string=s, state=state) if fixing_cmd is not None and s == error_cmd.string: error = "nothing was fixed" error_cmd = fixing_cmd state = fixing_cmd.state fixing_cmd = None elif s == "help": error = help_message error_cmd = None elif isinstance(command, commands.Malformed): error = "syntax error (type 'help' for help)" error_cmd = command elif isinstance(command, commands.Fix): error_cmd = state.registers[command.n].cmd.command_for_fix() error = "previously" fixing_cmd = command state = error_cmd.state else: try: fixing_cmd = None retval, state, command = command.execute() error = None error_cmd = None except commands.BadCommand as e: error = str(e) error_cmd = command except UnwindRecursion as e: if e.unwound( ): #reraise unless we've unwound all n steps of recursion error = "Recursion error" error_cmd = command except RecursionError: raise UnwindRecursion(30)
from models import ParkedVehicles from base import Session, engine, Base from commands import parse_command # Create table if it was not created Base.metadata.create_all(engine) # read input file with open('input.txt', 'r') as ip: lines = ip.readlines() # read all commands in one go # if the number of commands is going to be huge, process each line/command while file is open # Parse and execute each command for line in lines: if line and line != '\n': parse_command(line)
def on_chanmsg(self, from_, channel, message): if message.startswith('+'): message = message[1:] commands.parse_command(self, config, from_, channel, message)