LoginSignup
8
4

草食系男子がAPIとLINE Notifyを使ってチャラ男に変身することはできるのか!?

Last updated at Posted at 2023-11-14

1. 意中のあの子をレストランに誘いたいけど、どうやって誘ったらいいかわからない!

ChatGPTにどうすればいいか聞けって?というわけで聞いてみたところ
スクリーンショット 2023-11-14 003059.png
丁寧に教えてもらった。ありがたい時代ですね。
とにかく「レストランに誘え」と言いたいみたい。
ふむふむ、いけそうな気がしてきたぞ。

まだPCのモニターとしか向き合っていません。

2. デートの場所としてレストランのリストを作る!

スマートに誘うためにLINEにあらかじめ候補となるレストランのリストを送りたい。
名古屋駅から500m圏内の個室のあるお店をリストアップしてLINE Notifyで送るようにコードを作成した。

作成したコード
const fetch = require('node-fetch');

// ホットペッパーAPIのエンドポイント
const hotpepperEndpoint = 'https://webservice.recruit.co.jp/hotpepper/gourmet/v1/';

// 名古屋駅の緯度経度
const nagoyaStationLocation = {
  latitude: 35.170694,
  longitude: 136.881637,
};

// ホットペッパーAPIのアクセストークン(例:実際のものを使用してください)
const hotpepperApiKey = '*********';

// ホットペッパーAPIを使用してレストラン情報を取得する関数
const getRestaurantData = async () => {
  const url = new URL(hotpepperEndpoint);
  url.searchParams.append('key', hotpepperApiKey);
  url.searchParams.append('lat', nagoyaStationLocation.latitude);
  url.searchParams.append('lng', nagoyaStationLocation.longitude);
  url.searchParams.append('range', '2'); // 500メートル以内
  url.searchParams.append('private_room', '1'); // 個室あり
  url.searchParams.append('format', 'json');

  const response = await fetch(url);
  const data = await response.json();
  return data.results.shop;
};

// LINE Notifyに通知を送信する関数
const sendNotify = async (message, access_token) => {
  const url = 'https://notify-api.line.me/api/notify';
  const headers = {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Authorization': `Bearer ${access_token}`,
  };
  const encodedMessage = `message=${encodeURIComponent(message)}`;
  
  await fetch(url, {
    method: 'POST',
    headers: headers,
    body: encodedMessage,
  });
};

// メインの処理
const main = async () => {
  try {
    // レストラン情報を取得
    const restaurantData = await getRestaurantData();

    // レストラン情報から店名だけを抽出
    const shopNames = restaurantData.map(restaurant => restaurant.name);

    // LINE Notifyにメッセージを送信(コメントアウトされた部分)
    const access_token = '*********';
    const message = `名駅から500メートル以内の個室のあるレストラン一覧:\n${shopNames.join('\n')}`;
    await sendNotify(message, access_token);

    console.log('通知が送信されました。');
  } catch (error) {
    console.error('エラーが発生しました:', error.message);
  }
};

// メイン処理を実行
main();

届いたLINE
LINE_capture_721583806.922010.jpg
すごい!!このリストがあればデートに誘えるぞ!!
こういうお店のリストを持っているのはもはやチャラ男!草食系男子卒業か!?

まだPCのモニターとしか向き合っていません。

・・・
あれ??
お店の数が思ったより少ない。
デートっぽいお店も少ない。これではデートに誘っても断られてしまう。
仕方がないからデートに誘うのはもう少しデートスポットのリストが揃ってからにするしかないかな。
意中のあの子をデートに誘うのはまだ先になりそう。

結局まだPCのモニターとしか向き合っていません。

3. 今回のコード作成の手順

  • LINE Notifyのトークンを発行する
  • ホットペッパーのAPIキーを入手する
  • ChatGPTにコードを書いてもらう

3-1. LINE Notifyのトークンを発行する

まずLINE NOTIFYにアクセスする。

スクリーンショット 2023-11-14 110741.png
右上からログインをする。スクリーンショット 2023-11-14 112032.png
マイページを開いてスクリーンショット 2023-11-14 111710.png
トークンを発行するをクリックし
トークン名を適当に入力し

1:1でLINE Notifyから通知を受け取る

をチェックして発行するとトークンが受け取れる。
大事にメモしておく。

3-2. ホットペッパーのAPIキーを入手する

リクルートのユーザー登録を行うと登録したメールアドレス宛にAPIキーが送られてくる。

3-3. chatGPTにコードを書いてもらう

ここまで準備が整ったらコードを作成する。
スクリーンショット 2023-11-14 142625.png
と聞いてみると

const fetch = require('node-fetch'); // Node.js環境ではnode-fetchを使用

const hotpepperApiKey = 'YOUR_HOTPEPPER_API_KEY';
const lineNotifyToken = 'YOUR_LINE_NOTIFY_TOKEN';
const nagoyaStationLat = 35.170694;
const nagoyaStationLng = 136.881637;

const getRestaurants = async () => {
    try {
        const url = `https://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=${hotpepperApiKey}&format=json&lat=${nagoyaStationLat}&lng=${nagoyaStationLng}&range=5&keyword=個室`;

        const response = await fetch(url);
        if (!response.ok) {
            throw new Error(`Failed to fetch restaurant information. Status: ${response.status}`);
        }

        const data = await response.json();
        return data.results.shop;
    } catch (error) {
        console.error(error.message);
        return [];
    }
};

const sendLineNotify = async (message) => {
    try {
        const url = 'https://notify-api.line.me/api/notify';
        const headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'Authorization': `Bearer ${lineNotifyToken}`,
        };

        const body = new URLSearchParams({ message });

        const response = await fetch(url, {
            method: 'POST',
            headers,
            body,
        });

        if (!response.ok) {
            throw new Error(`Failed to send LINE Notify. Status: ${response.status}`);
        }

        console.log('Notification sent successfully.');
    } catch (error) {
        console.error(error.message);
    }
};

const main = async () => {
    const restaurants = await getRestaurants();
    const filteredRestaurants = restaurants.filter(restaurant => restaurant.private_room === 'あり');

    if (filteredRestaurants.length > 0) {
        const message = '名古屋駅から500メートル以内の個室のあるレストランのリスト:\n' +
            filteredRestaurants.map(restaurant => `${restaurant.name} - ${restaurant.address}`).join('\n');

        await sendLineNotify(message);
    } else {
        console.log('個室のあるレストランは見つかりませんでした。');
    }
};

main();

というものを作ってくれた。
少し間違っているところがあったのでリクルートのAPIリファレンスを参照しながらいくつか修正して、もともと手に入れていたAPIキーとトークンを入力し、完成となる。
エラーメッセージを入力することで訂正をかなり細かく教えてくれるが、GPT3.5ではネット上のデータを完全に利用することは難しいようで、自力での学習や精通した専門家の意見が結局必要ということがわかった。

4. まとめ

LINEは多くの人が使っているためLINE Notifyで欲しい情報をリストにしておくのは非常に便利なことがわかった。
飲食店の情報は無料のAPIが少なく、ホットペッパーは無料であったため今回利用させてもらった。
ChatGPTはプログラミング分野はかなり得意であるが、使いこなすにはベースの知識が必須になる。
これからベースの知識のアップデートをして、もっと有効なリストを作り、意中のあの子をデートに誘っていきたい。
最後まで読んでいただきありがとうございます。

最後までPCのモニターとしか向き合いませんでした。

8
4
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
8
4