I'm creating a simple chatbot through the Messenger Platform API and I'm pretty much stuck on how to effectively recognise a set of commands that the bot can react to. I'm currently using a switch statement to detect commands that begin with an exclamation mark (e.g. !showlist; !additem <single/set of parameter(s)>
).
Here is what I currently have:
switch(true){
case stristr($receivedMsg,'!additem'):
....
}
At any matching stage the code, either execute a set of statements or extrapolate the eventual parameters first and then executes some statements with them.
The issues I'm having with the above setup are the following:
- in case of no parameters commands it is possible to get the related code to execute even if the command is misspelled. E.g. !additem#$%% will still invoke the actual command's code in the switch statement.
in case of commands that take parameters, when retrieving those parameters with say this statement:
$item=str_replace('!additem', '', $receivedMsg);
it is very easy to include unwanted text in the parameters; you may deal with spaces with
trim()
or imply there will always be a space and edit the above statement to include it in the function. E.g.$item=str_replace('!additem ', '', $receivedMsg);
but this makes other problem arise when trying to separate the command from the params.
I'm aware that a solution could be hardcoding with systematic string manipulation functions but that doesn't seem correct to me. What do people do in this situation? Isn't there a specific way to exactly match commands and securely spot eventual users' typos?