Alexaでライブドア天気APIを叩く際に注意すること
AlexaでAPIを叩く練習にライブドア天気APIを使いました。
その際に結構ハマったので書き残しておきます。
ハマったこと
Alexaがライブドアの天気情報を喋ってくれない!
きちんとログには出ているのに!
なんで????
async handle(handlerInput) { const url = "http://weather.livedoor.com/forecast/webservice/json/v1?city=400040"; const res = await axios.get(url); const items = res.data; const speechText = items.description.text; console.log("speechText: " + speechText);
解決策
知り合いのエンジニアの方に助けていただきました。ありがとうございますm(__)m
どうやら、改行と「<」「>」が邪魔をしていたそうです!
たしかにある!!
そこで、教えていただいたとおりに改行と「<」「>」を削除すると、、、
async handle(handlerInput) { const url = "http://weather.livedoor.com/forecast/webservice/json/v1?city=400040"; const res = await axios.get(url); const items = res.data; var speechText = items.description.text.replace(/\r?\n/g, ''); speechText = speechText.replace(/</g, ''); speechText = speechText.replace(/>/g, ''); console.log("speechText: " + speechText);
おおおお!感動!!!!!
ログもこのように!!
いやあ、よかった。これにて解決。
ありがとうございました。
結論(注意すること)
Alexaに喋らせる文字列は、改行・「<」・「>」を消す必要あり
リファクタリング(?)
その後、正規表現を少し学び、、、
以下のようにリファクタリングしてみました。
同じ動作をします。ただ、短くなった代わりに若干読みづらくなった気が・・・(焦)
ご意見いただければ幸いです。
async handle(handlerInput) { const url = "http://weather.livedoor.com/forecast/webservice/json/v1?city=400040"; const res = await axios.get(url); const items = res.data; const speechText = items.description.text.replace(/[\r?\n<>]/g, ''); console.log("speechText: " + speechText);
いつか書こう書こうと思ってたら1カ月が過ぎてた・・・・