BotHeavenで作ってみたスクリプト

実験しながら幾つか作ってみた。

天気予報

「天気予報」を入力するとLivedoorから引っ張ってくる。サンプルで掲載されていたやつ。
http://weather.livedoor.com/weather_hacks/

cityのコードを変更することで地域を変更できる。cityコードは少ないのが難点。

function onTalk(name, text) {
if (text == "天気予報") {
api.http.get("http://weather.livedoor.com/forecast/webservice/json/v1", { "city": 140010 }, "onReceive");
}
}

function onReceive(result) {
var weather = JSON.parse(result);
api.slack.talk(weather["description"]["text"]);
}

日の出

日の出日の入りが気になるのがエージェント
http://openweathermap.org/

地域はとても多い。他にも情報が取れる。

function onTalk(name, text) {
if (text == "日の出") {
api.http.get("http://api.openweathermap.org/data/2.5/weather", { "q": "Sagamihara", "units": "metric"}, "onReceive");
}
}

function onReceive(result) {
var jdata = JSON.parse(result);
var br = "\n";
var TZ = +9;
var note = "平均気温 "+jdata.main.temp + br +
"最低気温 "+jdata.main.temp_min + br +
"最高気温 "+jdata.main.temp_max + br +
"日の出 " + parseTime(unixtimeToDate(jdata.sys.sunrise, TZ)) + br +
"日の入り " + parseTime(unixtimeToDate(jdata.sys.sunset, TZ)) ;

api.slack.talk(note);
}

function parseTime(datetime){
return datetime.getHours() + ":" + datetime.getMinutes();
}

// unixtimeをTimeZoneも使ってDate型に変換
function unixtimeToDate(ut, TZ) {
var tD = new Date( ut * 1000 );
tD.setTime( tD.getTime() + (60*60*1000 * TZ) );
return tD;
}

モジュールを使ったボット

複数人でボットを作ることを想定したときに、データとスクリプトを分離したくなった。
スクリプト

function initialize() {
}

function onTalk(name, text) {
if(text in BotWords){
api.slack.talk(BotWords[text]);
}else if(text in kenmituoBot){
api.slack.talk(kenmituoBot[text]);
}
}

モジュール
bot_words

var BotWords={};
BotWords["dog"]="わんわん";
BotWords["cat"]="にゃー";
BotWords["kuma"]="そんな餌に釣られないクマー";
BotWords["google"]="http://www.google.co.jp";
BotWords["Hello!"]="Bot Heaven!だよーん";

kenmituo_bot

var kenmituoBot={};
kenmituoBot["ようかんマン"] = "\
殺伐としたスレに救世主が!\n\
.    __\n\
    ヽ|・∀・|ノ ようかんマン\n\
    |__|\n\
     | |";

wikipedia

wikipediaから調べます

function initialize() {
}

function onTalk(name, text) {
var nani = text.indexOf("って何");
if(nani>0){
var searchWord = text.substr(0, nani);
//api.slack.talk(searchWord);
api.http.get("http://wikipedia.simpleapi.net/api",
{"output": "json", "keyword": searchWord }, "onReceive");
}
}

function onReceive(result) {
var wikipedia = JSON.parse(result);
if(wikipedia){
var resHtml = wikipedia[0].body;
var rep = resHtml.replace(//g, "\n");
api.slack.talk(rep);
}else{
api.slack.talk("(´・ω・`)知らんがな");
}
}

使えないコード

jQuery、$、xmlHttpRequestが使えない。
Googleスプレッドシートから読み込むとか、docomoの雑談対話とか使えなかった。ざんねん。