WLA: Random answers loaded from an XML file

One of the nice features of developing a messenger robot/agent is that you can easily load data from XML files. Combining this with few lines of code, you can make your agent more rich by giving a different response each time. Here is an example:

We'll use this XML file to store answers for specific topics:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<answers>
<topicGeek>
<text>Yeah, of course I am!</text>
<text>Indeed, my friend</text>
<text>You are a geek too!</text>
</topicGeek>
</answers>

The first step is to define how to load our desired topic answers into a datasource:

datasource AnswersXMLFileLoader() => text
file
answers.xml
simple xml
answers
topicGeek
text {loop=content}

Then, we create a datatable to load those answers, and keep the desired fiels (in this example, just the text field)

datatable AnswersGeekTopicTable {expire=never}
load text {index=exact} from datasource
AnswersXMLFileLoader()

With this simple code, we count the number of elements of a datatable, randomly choose one, find it and return its text field:

function RandText(TABLE)
COUNT = get count in TABLE
ITEM = Rand(COUNT)
VAR = 0
TEXT = get text in TABLE
if VAR == ITEM
return TEXT
VAR = VAR + 1
return TEXT

Now we setup the procedure that will call our RandText() function and output to the user the answer:

procedure RandomAnswerGeekTopic()
ANSWER = RandText(AnswersGeekTopicTable)
- ANSWER

And finally, we create the pattern which will be answered (notice that "You are a" it's optional):

+ [You are a] geek
call RandomAnswerGeekTopic()

And that's all!

Posted by Kartones on 2007-09-20

Comments?

Share via: Twitter Linkedin Google+ Facebook