2
1

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 1 year has passed since last update.

Google Apps ScriptとGemini Proを活用してサーバーレスなLINE Botを構築する

Posted at

はじめに

Google Apps Script(GAS)とGemini Proを使うことで、サーバーを必要とせずに機能豊かなLINE Botを簡単に構築できます。この記事では、具体的なコード例を用いて、その構築方法を解説します。

こちらのオウム返しできる環境が必要です。

Gemini Pro APIとの統合

まず、Gemini Pro APIを使った応答生成機能をGASに統合します。以下のgetGeminiApiResponse関数は、ユーザーからのメッセージ(プロンプト)に基づいて、Gemini Pro APIを通じて応答を生成します。

function getGeminiApiResponse(prompt = 'あなたができることは何ですか?') {
  const apiKey = PropertiesService.getScriptProperties().getProperty('APIKEY');
  const apiUrl = `https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent?key=${apiKey}`;
  const payload = {
    "contents": [
      {"role": "user","parts": { "text": prompt }}
    ],
  };
  const options = {
    'payload': JSON.stringify(payload),
    'method' : 'POST',
    'muteHttpExceptions': true,
    'contentType': 'application/json'
  };

  try {
    const responseText = UrlFetchApp.fetch(apiUrl, options).getContentText();
    const response = JSON.parse(responseText);
    const { content: { parts: [{ text }] } } = response.candidates[0];
    console.log(text);
    return text;
  } catch (error) {
    console.error('APIリクエストでエラーが発生しました: ', error);
    return '少々お待ちください。';
  }
}

この関数は、Gemini Pro APIから得られた応答を返します。エラーが発生した場合には、「少々お待ちください。」というメッセージを返します。

LINE Botの設定と応答の送信

次に、LINE Botの設定とユーザーからのメッセージに対する応答の送信方法を確認します。以下のdoPost関数は、LINEからのメッセージを受け取り、Gemini Proを通じて生成された応答をLINEに返信します。

const LINE_TOKEN = PropertiesService.getScriptProperties().getProperty("LINE_TOKEN");
const LINE_URL = 'https://api.line.me/v2/bot/message/reply';

function doPost(e) {
  const json = JSON.parse(e.postData.contents);
  const replyToken = json.events[0].replyToken;
  const messageText = json.events[0].message.text;

  if (typeof replyToken === 'undefined') {
    return;
  }

  const geminiResponse = getGeminiApiResponse(messageText);

  const option = {
    'headers': {
      'Content-Type': 'application/json; charset=UTF-8',
      'Authorization': 'Bearer ' + LINE_TOKEN,
    },
    'method': 'post',
    'payload': JSON.stringify({
      'replyToken': replyToken,
      'messages': [{
        'type': 'text',
        'text': geminiResponse || '申し訳ありません、応答を生成できませんでした。',
      }],
    }),
  };

  UrlFetchApp.fetch(LINE_URL, option);

  return;
}

この関数では、LINEのMessaging APIを使用して、ユーザーからのメッセージに対する応答を送信します。Gemini Pro APIを利用することで、単なるオウム返しではなく、より高度で自然な対話が可能になります。

まとめ

このように、GASとGemini Proを組み合わせることで、サーバー不要で高機能なLINE Botを簡単に構築できます。このアプローチは、開発の敷居を下げ、迅速かつ効率的なBot開発を可能にします。サーバーの設定や維持に関する心配がないため、開発者はBotの機能とユーザー体験の向上に集中できます。

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?