1

I'm creating some kind of a "personal assistant" application which is basically a web service that receives a message and then does something according to it.

For example I send "what time is it?" and I get the current time as answer. Other examples:

  • "tell me a joke" -> queries and sends some joke from an public api
  • "I have to [X] -> sets [X] to todo list
  • "What do I have to do?" -> sends todo list
  • "Start my pc" -> Starts PC via Wake On Lan

or what ever else comes to my mind.

My first prototype just uses an if else statment which looks something like

if message.contains("foo"):
  # do foo stuff
elif message.contains("bar"):
  # do bar stuff

Of course this will be a total mess after adding several commands so I'm thinking about what would be a good concept to structure such a huge conditional statement.

(I'm using Python with the web.py framework)

One idea is to use some list / map to create a mapping between key words and associated functions and split functionality in different classes (like a todo list module and so on).

There are applications like WolframAlpha or Siri which have just a single input method but several hundred or thousand different functions in the brackground. Of course those are on a totally different level but in general, how do you create a nice and clean branching from a single input to a big number of different functions?

das Keks
  • 213
  • 1
  • 4
  • 7

1 Answers1

1

The usual approach to mapping strings to functions is to use a dictionary or hashtable. Here is what it would look like in C#:

var commands = new Dictionary<string, Action<string>>();

This creates a hash table with a string key and a method delegate taking one parameter (in this case a string. You can use the parameter however you want).

You can create the commands at compile time:

var commands = new Dictionary<string, Action<string>>
{
    { "Tell me a joke", TellJoke }, 
    { "I have to",  IHaveTo }
};

or at runtime:

commands.add("Tell me a joke", TellJoke);

Where TellJoke is some method that takes one parameter and returns nothing. After a bit of pre-processing of the search string, the mapped function would then be called thusly:

Commands[searchKey](searchString);

or more robustly:

bool ExecuteCommand(string key, string search)
{
    if (commands.Contains(key))
    {
        Commands[searchKey](search);
        return true;
    }
    return false;
}

Of course, a real personal assistant wouldn't work this way. You would have some sort of engine that can be modified at runtime, not compile time, so that it can learn.

Robert Harvey
  • 200,592