LineMessageAPIを使用して、送信された内容で検索を行うBOTを作成する際に検索するためにGoogleCustomSearchEngineを使用する。
LineBotの設定等はコチラ
RailsでGoogleCustomSearchEngineを使用するためにGemをinstallためGemfileに下記を追加
gem 'google_custom_search_api'
API_KEYなどの必要な情報の取得についてはGitHubのgoogle_custom_search_apiを参照
渡されたパラメータを検索条件として検索を行う
今回はLineMessageAPIを使用した際の返信時に実行する
def reply(replyToken, text)
query = text.gsub(","," ")
results = GoogleCustomSearchApi.search(query)
columns = []
results["items"].first(3).each do | item |
if item["cse_thumbnail"]
thumbnail = item["cse_thumbnail"]["src"] || "https://example.com/bot/images/item1.jpg"
else
thumbnail = "https://example.com/bot/images/item1.jpg"
end
columns << {
"thumbnailImageUrl": thumbnail,
"title": item["title"],
"text": item["snippet"][0..30],
"actions": [
{
"type": "uri",
"label": "ブラウザで表示",
"uri": item["link"]
}
]
}
end
messages = [
{
"type": "template",
"altText": "this is a carousel template",
"template": {
"type": "carousel",
"columns": columns
}
}
]
body = {
"replyToken" => replyToken ,
"messages" => messages
}
post('/v2/bot/message/reply', body.to_json)
end
resultからtitleとlinkの取得は下記でも可能だが、cse_thumbnail
などはitem["cse_thumbnail"]
としないと取得できず、ちょっとはまった。
results.items.each do |item|
puts item.title, item.link
end
他は試していないけれど、title
とlink
以外は["xxx"]
としないと取得できなさそう。。。
後はAPIを直接ブラウザから実行しJSONから必要なものを取得してくれば、他にも色々と情報を取得できそうである。