9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Slackで昼飯をレコメンド

Last updated at Posted at 2016-05-18

昼飯を考えるのが面倒なのでslackにレコメンしてくれるよう通知
*対象店舗のデータはyelpを利用

##1.構成

サーバー : CentOS6.7
Ruby : 2.2.1

Slack API

tokenはあらかじめ取得
使用できるか確認

$curl -XPOST -d "token=<取得token>" -d "pretty=1" "https://slack.com/api/auth.test"

falseにならなければOK!

通知はWebhookを利用
slack-incoming-webhooks をインストール

#gem install slack-incoming-webhooks

Webhook URLの発行

Webhook URL

yelpのdevelopersから必要な情報を取得

yelp

Manage API access より取得できる

Consumer Key
Consumer Secret
Token
Token Secret

##2. 準備

緯度(ll)と半径(radius_filter)は適時変更
半径はメートル単位

yelp.rb
#!/usr/bin/ruby
# coding: utf-8

require 'rubygems'
require 'oauth'
require 'json'
require 'slack/incoming/webhooks'

## send slack
def send_slack(url,mesg)
     slack = Slack::Incoming::Webhooks.new url
     slack.post mesg
end

## post channel
wurl = "https://hooks.slack.com/services/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"

#credit
consumer_key = "XXXXXXXXXXXXXXXXXX"
consumer_secret = "XXXXXXXXXXXXXXXXXX"
token = "XXXXXXXXXXXXXXXXXX"
token_secret = "XXXXXXXXXXXXXXXXXX"
api_host = 'http://api.yelp.com'

consumer = OAuth::Consumer.new(consumer_key, consumer_secret, {:site => api_host})
access_token = OAuth::AccessToken.new(consumer, token, token_secret)


def call_yelp(access_token, off_set)

   shop_name = []
   set = off_set
   path = "/v2/search?term=food&radius_filter=850&sort=1&offset=#{set}&ll=XX.XXXXXXX,XX.XXXXXX&lang=ja"
   jresp = JSON.parse(access_token.get(path).body)
   jresp['businesses'].each do | business |
     if business['is_closed'] == false
        shop_name << business['name']
     end
   end

   return  shop_name.sample

end

def search_yelp(access_token, url, off_set, name)

   wurl, rname, set = url, name, off_set
   path = "/v2/search?term=food&radius_filter=850&sort=1&offset=#{set}&ll=XX.XXXXXXX,XX.XXXXXX&lang=ja"
   jresp = JSON.parse(access_token.get(path).body)
   jresp['businesses'].each do | business |
     if business['name'] == rname
       send_slack(wurl,"#{business['name']}\s#{business['rating']}\n#{business['url']}\n")
     end
   end

end


# recommend1
restaurant1 = call_yelp(access_token, 0)
search_yelp(access_token, wurl, 0, restaurant1)

# recommend2
restaurant2 = call_yelp(access_token, 21)
search_yelp(access_token, wurl, 21, restaurant2)

あとはこれをcronなどで動かせばOK!

##3.残作業

なんか一度にデータを取得できないからまどろっこしいやり方に。
limitとかで渡せばいっきにデータを取得できると思ったが、なぜかデフォルトの20件に絞られる。
他にもっといいやり方があるだろう・・。

参考

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?