エンジニアの卵の成長日記

https://blog.toru-takagi.dev/profile/

Slack Botを利用した鍵管理システム

今日は第20回のゼミがあり大学に行っていた

ゼミの内容はPythonで書くCompositeパターンとFlyweightパターンの発表だ

それ関連の記事を貼っておくので良かったら見てください

qiita.com

その後、研究室の課題であるSlackを利用した鍵管理システムの作成をチームで行っていた




課題の概要はWeb班とAndroid班に分かれ、僕はAndroid
1週間でAndroidの仕様書を作成し、作成した仕様書をWeb班に渡す
2週間でWeb班からもらったWebの仕様書を頼りにシステムの作成
2週間でWeb班が作成したAndroidアプリを修正するというもの

現在はWeb班からもらったWebアプリの仕様書を頼りにシステムを作成している最中だ
13時~15時の予定でしたが、結局19時までシステムの作成を行っていた...

久しぶりにCentOS6.5を触ったのと大学のプロキシサーバに苦戦した
環境構築の内容については後日Qiitaに投稿する予定だ

今回はサーバ側をPHPで書いたので、それを載せようと思う
バイトでPHPフレームワークを触ることはあるが、モダンなPHP?なコードを書いて開発するのは初めてだったので、ksコードだと思うが許してほしい

time.php

<?php
    //DBに値を登録
    $db_info = 'mysql:host=localhost;dbname=keybot;charset=utf8';

    try {
        $db = new PDO($db_info, 'db', 'hogehoge');
    } catch (PDOException $e) {
        exit('データベース接続失敗。'.$e->getMessage());
    }

    $sql = $db->prepare('select * from time');
    $sql->execute();

    //DBの値を取得
    $sql = $db->prepare('select * from time');
    $sql->execute();

    $data = $sql->fetch();

    //Slack APIの情報
    $slackApiKey = 'token code';
    $message = "返却予定時間は『";

    if ($data['hour'] < 10) {
        $message = $message."0".$data['hour'].":";
    } else {
        $message = $message.$data['hour'].":";
    } 

    if ($data['minute'] < 10) {
        $message = $message."0".$data['minute'];
        $message = $message."";
    } else {
        $message = $message.$data['minute'];
        $message = $message."";
    }

    $message = urlencode($message);
    $url = "https://slack.com/api/chat.postMessage?token=${slackApiKey}&channel=%23seminar_team_android&text=${message}&as_user=true";
    file_get_contents($url);

    //リダイレクト
    header('location: index.html');
    exit();
?>


keylocation.php

<?php
    //DBから値をとってくる
    $db_info = 'mysql:host=localhost;dbname=keybot;charset=utf8';

    try {
        $db = new PDO($db_info, 'db', 'hogehoge');
    } catch (PDOException $e) {
        exit('データベース接続失敗。'.$e->getMessage());
    }

    $sql = $db->prepare('select * from keylocation');
    $sql->execute();

    $data = $sql->fetch();

    //Slack APIの情報
    $slackApiKey = 'token code';
    $message = '';

    if ($data['keylocation'] == 0) {
        $message = '鍵の所在は『守衛室』です。';
    } else if ($data['keylocation'] == 1) {
        $message = '鍵の所在は『研究室』です。';
    } else {
        $message = '鍵の所在は『不明』です。';
    }

    $message = urlencode($message);
    $url = "https://slack.com/api/chat.postMessage?token=${slackApiKey}&channel=%23seminar_team_android&text=${message}&as_user=true";
    file_get_contents($url);

    //DBに値を登録
    if ($data['keylocation'] == 0) {
        $sql = $db->prepare('update keylocation set keylocation = 1');
        $sql->execute();
    } else if ($data['keylocation'] == 1) {
        $sql = $db->prepare('update keylocation set keylocation = 0');
        $sql->execute();
    }

    //リダイレクト
    header('location: index.html');
    exit();
?>