LoginSignup
0
0

More than 3 years have passed since last update.

Slackで星占いbotを作る

Posted at

1.「占い」というSlackへのチャット送信に反応して12星座のボタンを返信
2. 12星座のうちどれかボタンを押すと今日の運勢が返ってくる
というSlack botを作ります。
uranai.jpg

いきあたりばったりで作ってるので部品の共通化など細かいとこはやっておりません。
Slack API
https://api.slack.com/
使用した星占いAPI
http://jugemkey.jp/api/waf/api_free.php

1. Slack bot appの作成

Appの作成、OAuth Tokenの取得などは他に詳しいページたくさんございますのでお探しいただければ。

Pemission Scopes

以下の2つをPermission Scopesに追加してSave。
- Access user's public channels
- Send messages as bot
scope.jpg
permission.jpg

Event subscription

  • SlackからのEventを受け取るURLを設定
  • 初回は所有者確認用の儀式があるのでそれは他の詳しい解説お読みください events.jpg

Interactive components

  • ボタンを使用してEventを受け取りたいのでInteractive componentsを設定
  • Interactive componentsからのEvent受信用URLを設定 interactive.jpg

2. プログラムをかく

  • Webhookに設定したSlackからのイベント受信用
bot.php
    $base_url="https://slack.com/api/chat.postMessage";
    $channel="チャネルID";
    $token="OAuth Token";

    $json_string = file_get_contents('php://input'); 
    $json_string = mb_convert_encoding($json_string, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');

    $type = $arr['event']['type'];
    $text = $arr['event']['text'];
    $event_channel = $arr['event']['channel'];
    $url="";

    if($event_channel==$channel and $text=="占い"){
    $headers = [
    'Authorization: Bearer OAuth Token', 
    'Content-Type: application/json;charset=utf-8'
    ];

    //ボタン作成
    $data = [
    "channel" => $channel,
    "text"=> "今日の運勢を占います。星座のボタンを押してください。",
    "attachments" => [
        [
        'callback_id'=> 'button',
        'text'=> '',
        'actions'=> [
            [
            "name"=> "牡羊座",
            "text"=> ":ram:",
            "type"=> "button",
            "value"=> 0
            ],
            [
            "name"=> "牡牛座",
            "text"=> ":cow2:",
            "type"=> "button",
            "value"=> 1
            ],
            [
            "name"=> "双子座",
            "text"=> ":woman-with-bunny-ears-partying:",
            "type"=> "button",
            "value"=> 2
            ],
            [
            "name"=> "蟹座",
            "text"=> ":crab:",
            "type"=> "button",
            "value"=> 3
            ],
            [
            "name"=> "獅子座",
            "text"=> ":lion_face:",
            "type"=> "button",
            "value"=> 4
            ]]],
        [
        'callback_id'=> 'button',
        'text'=> '',
        'actions'=> [
            [
            "name"=> "乙女座",
            "text"=> ":woman:",
            "type"=> "button",
            "value"=> 5
            ],
            [
            "name"=> "天秤座",
            "text"=> ":scales:",
            "type"=> "button",
            "value"=> 6
            ],
            [
            "name"=> "蠍座",
            "text"=> ":scorpion:",
            "type"=> "button",
            "value"=> 7
            ],
            [
            "name"=> "射手座",
            "text"=> ":bow_and_arrow:",
            "type"=> "button",
            "value"=> 8
            ],
            [
            "name"=> "山羊座",
            "text"=> ":goat:",
            "type"=> "button",
            "value"=> 9
            ]]
        ],
        [
        'callback_id'=> 'button',
        'text'=> '',
        'actions'=> [
            [
            "name"=> "水瓶座",
            "text"=> ":droplet:",
            "type"=> "button",
            "value"=> 10
            ],
            [
            "name"=> "魚座",
            "text"=> ":fish:",
            "type"=> "button",
            "value"=> 11
            ]]
        ]
        ],

    "as_user" => false
    ];

    $options = [
    CURLOPT_URL => $base_url,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POST => true,
    CURLOPT_POSTFIELDS => json_encode($data) 
    ];

    $ch = curl_init();
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch); 
    curl_close($ch);

    }else{
        return;
    }
  • Interactive componentsで設定したイベント受信用
interactive_receive.php
    date_default_timezone_set('Asia/Tokyo');
    $date=date("Y/m/d");
    $horo_base_url="http://api.jugemkey.jp/api/horoscope/free/";

    $channel="チャネルID";
    $base_url="https://slack.com/api/chat.postMessage";


    $json_string = file_get_contents('php://input'); 
    $json_string = mb_convert_encoding($json_string, 'UTF8', 'ASCII,JIS,UTF-8,EUC-JP,SJIS-WIN');
    $json_string = urldecode($json_string);
    $json_string = str_replace('payload=', '', $json_string);
    $arr = json_decode($json_string,true);
    $value = $arr['actions'][0]['value'];

    //占いAPIの利用
    $options = [
    CURLOPT_URL => $horo_base_url.$date,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true
    ];

    $ch = curl_init();
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch); 
    curl_close($ch);
    $arr = json_decode($result,true);
    $content=$arr['horoscope'][$date][$value]['content'];
    $rank=$arr['horoscope'][$date][$value]['rank'];
    $item=$arr['horoscope'][$date][$value]['item'];
    $money=get_star($arr['horoscope'][$date][$value]['money'],$val="money");
    $job=get_star($arr['horoscope'][$date][$value]['job'],$val="job");
    $love=get_star($arr['horoscope'][$date][$value]['love'],$val="love");
    $color=$arr['horoscope'][$date][$value]['color'];
    $sign=$arr['horoscope'][$date][$value]['sign'];
    $content_date=date("n月d日");

    $headers = [
        'Authorization: Bearer xoxp-657953111670-714389541459-767572323317-3792f4abf0e2081f3dd6baf4d6757340', 
        'Content-Type: application/json;charset=utf-8'
        ];
    $data = [
        "channel" => $channel,
        "text"=> $content_date."の".$sign."の運勢は第".$rank."位です。\n".$content."ラッキーアイテムは".$item."。\n仕事運:".$job."\n金運:".$money."\nラブ運:".$love,
        "as_user" => false
    ];

    //同じコマンドを再度記述してます(未整理)
    $options = [
        CURLOPT_URL => $base_url,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POST => true,
        CURLOPT_POSTFIELDS => json_encode($data) 
        ];

    $ch = curl_init();
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch); 
    curl_close($ch);

    //APIから戻ってくるスコアを絵文字で表現
    function get_star($score,$val){
        for($i=0;$i<$score;$i++){
            switch ($val) {
                case 'job':
                    $star.=":ok_hand:";
                    break;
                case 'money':
                    $star.=":moneybag:";
                    break;
                case 'love':
                    $star.=":heart_eyes:";
                    break;
                default:
                    $star.="★";
                    break;
            }

        }
        return $star;
    }
0
0
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
0
0