T.H/ 2023年 1月 31日/ 技術

はじめに

こんにちは。T.H.です。
今回は、話題のChatGPTを試してみました。
おやつ感覚の軽い記事です。

試した内容

以前に載せたDiscordのリマインダーbotをChatGPTで生成できるかを試してみました。
ChatGPTの利用方法に関しては様々な記事があふれていますのでここでは割愛いたします。
記事執筆時点ではアカウント登録のみで無料で利用できます。

比較元コード

まずは比較対象となるコード全文を載せます。以前の記事そのままです。

function remindAttendance() {

  // googleカレンダーを取得
  // 対象のカレンダーID
  const calendarId = 'xxxxxxxxxxx@import.calendar.google.com';
  // カレンダーオブジェクト取得
  const calendar = CalendarApp.getCalendarById(calendarId);

  // 対象日時を取得
  const target_date = new Date();
  target_date.setDate(target_date.getDate() + 7);

  // 指定日(当日)の予定オブジェクトの配列を取得
  const events = calendar.getEventsForDay(target_date);

  // 予定が0件の場合
  if (events.length === 0) {
    console.log("No events found at" + target_date);
  }
  // 予定が1件以上の場合
  else {
    // console.log("Events:");
    // 予定の件数だけ実行
    for (event in events) {

      // 予定のタイトルを取得
      let title = events[event].getTitle();
      // タイトルに'予定'が入っているか
      result = title.indexOf('予定')
      if(result !== -1){
        // 予定の開始時刻・終了時刻を取得
        let startHour = toDoubleDigits(events[event].getStartTime().getHours());
        let startMinute = toDoubleDigits(events[event].getStartTime().getMinutes());
        let endHour = toDoubleDigits(events[event].getEndTime().getHours());
        let endMinute = toDoubleDigits(events[event].getEndTime().getMinutes());

        msg_schedule = title + '(' + startHour + '時' + startMinute + '分~' + endHour + '時' + endMinute + '分)';
        message = '1週間後の予定です!\n' + msg_schedule
        postMessage(message)

      }
    }
  }
}

// メッセージ投稿
function postMessage(message){

  // discord側で作成したボットのウェブフックURL
  const discordWebHookURL = "https://discord.com/api/webhooks/yyyyyyyyyyyy";

  // 投稿するチャット内容と設定
  const messageContents = {
    "content": message, // チャット本文
    "tts": false  // ロボットによる読み上げ機能を無効化
  }

  const param = {
    "method": "POST",
    "headers": { 'Content-type': "application/json" },
    "payload": JSON.stringify(messageContents)
  }

  UrlFetchApp.fetch(discordWebHookURL, param);

}

// 時刻の0埋め用
function toDoubleDigits(num) {
  num += "";
  if (num.length === 1) {
    num = "0" + num;
  }
 return num;     
}

質問内容と回答コード

ChatGPTに以下の質問をしてみました。

Google App Scriptを使用してgoogleカレンダーの情報から特定の文字列を含む予定を取得し、1週間前にDiscordの特定のチャンネルにリマインドするDiscord botを作成するためのjava scriptコードを教えてください。

すると下記の内容が回答として返ってきました。

Here's an example of how to retrieve events from Google Calendar that contain a specific string, and remind about them one week before the event date in a specific Discord channel using Google App Script and JavaScript:

// Import the required libraries
const { google } = require('googleapis');
const Discord = require('discord.js');

// Authenticate with Google and initialize the Google Calendar API
async function authorize(credentials) {
  const client = await google.auth.getClient({
    credentials,
    scopes: ['https://www.googleapis.com/auth/calendar.readonly'],
  });
  return google.calendar({ version: 'v3', auth: client });
}

// Get events from a specified calendar that contain a specific string
async function getEventsWithString(calendarId, searchString) {
  const calendar = await authorize();
  const now = new Date();
  const nextWeek = new Date(now.getTime() + 7 * 24 * 60 * 60 * 1000);
  const events = await calendar.events.list({
    calendarId,
    timeMin: now.toISOString(),
    timeMax: nextWeek.toISOString(),
    singleEvents: true,
    orderBy: 'startTime',
  });
  return events.data.items.filter(event => event.summary.includes(searchString));
}

// Initialize the Discord client
const client = new Discord.Client();

// Respond to messages containing the "!remind" command
client.on('message', async message => {
  if (message.content.startsWith('!remind')) {
    const searchString = message.content.split(' ').slice(1).join(' ');
    const events = await getEventsWithString('primary', searchString);
    if (events.length > 0) {
      events.forEach(async event => {
        const reminder = new Date(event.start.dateTime || event.start.date);
        reminder.setDate(reminder.getDate() - 7);
        setTimeout(() => {
          const channel = client.channels.cache.get('YOUR_DISCORD_CHANNEL_ID');
          if (channel) {
            channel.send(`Reminder: "${event.summary}" is happening on ` +
              `${event.start.dateTime || event.start.date}.`);
          }
        }, reminder.getTime() - now.getTime());
      });
      message.reply(`Reminders set for ${events.length} events containing "${searchString}"`);
    } else {
      message.reply(`No events found containing "${searchString}"`);
    }
  }
});

// Login to Discord with a bot token
client.login('YOUR_DISCORD_BOT_TOKEN');

This code assumes that you have already set up a Google API project with the Google Calendar API enabled and have downloaded the API credentials in JSON format. Replace 'YOUR_DISCORD_BOT_TOKEN' with the bot token for your Discord bot, and replace 'YOUR_DISCORD_CHANNEL_ID' with the ID of the Discord channel where the reminders should be posted.

一見それっぽいですが、元々のコードと比較すると質問意図とは少し違うコードが返ってきたようです。常駐型のDiscord botからのメッセージで起動しようとしているのでしょうか。私の知識が足り無いこともあり、ちょっと読み取りきれていません。
質問文で仕様を一文に詰めすぎたことによりあいまいになってしまったかもしれません。

質問を少しシンプルに

以下のように、仕様を少し単純にしてみました。
さらになんとなく英語で質問しています。英文作成はDeepLを利用しました。ここら辺のスムーズさは本当に隔世の感がありますね。

What is the javascript code to create a discord bot that retrieves google calendar information using Google App Script?
(Google App Scriptを使ってgoogleカレンダー情報を取得するdiscord botを作成するためのjavascriptコードを教えてください。)

以下回答

Creating a Discord bot that retrieves information from a Google Calendar using JavaScript and Google App Script would involve several steps, including:
Setting up a new bot in the Discord Developer Portal and obtaining the bot's token.
Creating a new Google App Script project and linking it to your Google Calendar
Use the UrlFetchApp to make calls to the Discord API and the CalendarApp to access the events in the Google Calendar.
Here is an example of code that retrieves upcoming events from a specific calendar using the UrlFetchApp and CalendarApp:

function getUpcomingEvents() {
  // Get the calendar
  var calendar = CalendarApp.getCalendarById("YOUR_CALENDAR_ID");

  // Get the upcoming events
  var events = calendar.getEventsForDay(new Date());
  var eventText = "Upcoming events: \n";

  // Loop through the events and create a message
  for (var i = 0; i < events.length; i++) {
    var event = events[i];
    eventText += event.getTitle() + ": " + event.getStartTime() + "\n";
  }

  // Send the message to Discord
  var url = "https://discordapp.com/api/webhooks/YOUR_WEBHOOK_ID/YOUR_WEBHOOK_TOKEN";
  var options = {
    "method": "post",
    "payload": JSON.stringify({ "content": eventText })
  };
  UrlFetchApp.fetch(url, options);
}

This is just an example, you will need to customize the code to fit your needs. Make sure to replace the placeholders with your own information like YOUR_CALENDAR_ID, YOUR_WEBHOOK_ID and YOUR_WEBHOOK_TOKEN.
Please note that you will have to have knowledge of javascript and the libraries used, and have set up a project in Google App Script, linking it to your Google Calendar, and created a webhook in your discord server.
Also, you need to keep in mind that, you need to check the Calendar API's quota limits to check how many requests you can make, and also you need to be authorized to access the Calendar API.

細かく見ていくと説明文の中に気になる記述(YOUR_WEBHOOK_ID and YOUR_WEBHOOK_TOKEN?)などはありますが、コードは比較対象と近い構造となっており、かなりそれっぽいです。

実際に動くか

実際に上記のコードをGASに張り付けて実行できるかを試してみました。
結論としては以下の点を修正することで実際に動作し、Discordに指定日付の予定タイトルをメッセージとしておくりこむことが出来ました。
"headers"に関しては明確な不具合ですが、それ以外に関してはきちんと動作するコードが生成されていたといって良いと思います。

  • "YOUR_CALENDAR_ID"を使用するGoogleカレンダーのIDと置き換える
  • calendar.getEventsForDay(new Date())に指定の日付、Date(2023,1,30)などを入れる
  • "https://discordapp.com/api/webhooks/YOUR_WEBHOOK_ID/YOUR_WEBHOOK_TOKEN"をDiscordのwebhook URLに差し替える
  • optionsに "headers": { 'Content-type': "application/json" },を追加する

最後に

すでに各所でさんざん言われていることですが、
単なる会話にとどまらずコード生成に関してもかなりのレベルまで来ていることは実感できました。
ただし、しれっと嘘の説明や不具合を混ぜてくるので、使いどころを限定する必要はありそうです。

例えば、やりたいことははっきりとしているが単に実装が面倒な場合や、特定のAPIの使用サンプル作成、別の実装方法の壁打ちなど、本人が正誤判定できる状況であれば本当に強力なツールになりそうです。

しばらく色々試してみたいと思います。

About T.H

North Torch株式会社 プログラマ 技術的な経歴は.NETアプリケーションが一番長い。 その他はまだまだ勉強中。