Help us understand the problem. What is going on with this article?

RailsでGoogleCustomSearchEngine(CSE)を使ってみる

More than 1 year has passed since last update.

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

他は試していないけれど、titlelink以外は["xxx"]としないと取得できなさそう。。。

後はAPIを直接ブラウザから実行しJSONから必要なものを取得してくれば、他にも色々と情報を取得できそうである。

Why do not you register as a user and use Qiita more conveniently?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away