Alan is very cultured
private async Task RandomWikiArticle()
{
try
{
var http = new HttpClient();
string rand_page_str, title, selected_page_str, content;
int unvalid_seq, idx1, idx2;
do
{
var rand_page = await http.GetAsync("http://en.wikipedia.org/wiki/Special:Random");
rand_page_str = await rand_page.Content.ReadAsStringAsync();
unvalid_seq = rand_page_str.IndexOf("\\u");
idx2 = rand_page_str.IndexOf(" - Wikipedia");
} while(idx2 == -1 || unvalid_seq != -1);
idx1 = rand_page_str.IndexOf("<title>") + "<title>".Length;
title = rand_page_str.Substring(idx1, idx2 - idx1).Replace(' ', '_');
var selected_page = await http.GetAsync("https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&exsentences=2&titles=" + title);
selected_page_str = await selected_page.Content.ReadAsStringAsync();
idx1 = selected_page_str.IndexOf("extract\":\"") + "extract\":\"".Length;
idx2 = selected_page_str.IndexOf("\"}}}}");
content = selected_page_str.Substring(idx1, idx2 - idx1);
while(content.IndexOf(" (") != -1)
{
idx1 = content.IndexOf(" (");
if(content.IndexOf("))") != -1)
{
idx2 = content.IndexOf("))") + 2;
content = content.Remove(idx1, idx2 - idx1);
}
else
{
idx2 = content.IndexOf(")") + 1;
content = content.Remove(idx1, idx2 - idx1);
}
}
while(content.IndexOf("\\n") != -1)
{
idx1 = content.IndexOf("\\n");
content = content.Remove(idx1, 2);
}
content = content.Replace(" ", " ");
content = content.Replace(" ", " ");
content = content.Replace("\\\"", "\"");
await GUIOutput(content, true);
}
catch
{
await GUIOutput("I'm sorry, I couldn't retrieve the informations from the web.", true);
}
state = AssistantState.BACKGROUND_DEFAULT;
}
This functionality also uses a web API but includes some filtering on the results to
avoid problems with unpronounceable characters such as Unicode values. Firstly the function
searches a random Wikipedia page that doesn't contain Unicode characters; once one is
found, it extracts the title of the page and sends it to the Wikipedia Web API in order to
obtain the content in a more structured form. It then gets the new content from this
structured string and eliminates all the brackets and special characters that might still
be there. Eventually the function passes the final string to GUIOutput
.