チャットGPTをslackで使えるようにする
賢すぎるチャットbotとして、チャットGPTが話題になっています。気軽に業務に活かせるように、slackで実装する方法をご紹介します。
slackで相談できればチームの業務も捗ること間違い無しですね。
・OpenAIのAPIキーの取得方法
・Google Apps Script(GAS)のスクリプト
・Slackのappを作る
OpenAIのAPIキーの取得方法
OpenAIのAPIキーを取得して、サーバ側のスクリプト作成の準備をしましょう。
以下でSign upしてログインします。Google Accountでも登録できます。
ログインして、Create New Seacret Keyをクリックし、API用のキーを取得します。
これでスクリプト作成の準備完了です。

Google Apps Script(GAS)のスクリプト
Google Apps Scriptで、サーバレス環境にてサーバを準備します。
以下のURLにてプロジェクトを作成してスクリプトを作成します。
スクリプトの中の[自身のOpenAIのAPIキー]と[自身のSlack IncommingのURL]には、控えた文字列を記載しましょう。SlackのURLは次のセクションで取得方法を説明します。
function doPost(e)
{
// slack appsのEvent Subscriptionsのchallenge。同期する時に利用。
var params = JSON.parse(e.postData.getDataAsString());
if('challenge' in params)
{
return ContentService.createTextOutput(params.challenge);
}
// ユーザ名とtextを取得
var userName = params.event.user;
var textSlack = params.event.text.substr(0, params.event.text.length);
// chatGPTに問い合わせ
var resultStr = getChatGptMessage(textSlack);
var contents = `<@${userName}> ${resultStr}`;
var options =
{
"method" : "post",
"contentType" : "application/json",
"payload" : JSON.stringify(
{
"text" : contents,
link_names: 1
}
)
};
// slack連携
UrlFetchApp.fetch("https://hooks.slack.com/services/[自身のSlack IncommingのURL]", options);
}
// ChatGPTのAPIを呼び出し応答を取得する
function getChatGptMessage(message) {
var uri = 'https://api.openai.com/v1/completions';
var headers = {
'Authorization': 'Bearer [自身のOpenAIのAPIキー]',
'Content-type': 'application/json',
'X-Slack-No-Retry': 1
};
var options = {
'muteHttpExceptions' : true,
'headers': headers,
'method': 'POST',
'payload': JSON.stringify({
"model": "text-davinci-003",
"max_tokens" : 2500,
"prompt": message})
};
try {
const response = UrlFetchApp.fetch(uri, options);
var json=JSON.parse(response.getContentText());
return json["choices"][0]["text"];
} catch(e) {
console.log('error');
}
}
スクリプトを作成しましたら、New Deployをクリックして、歯車をクリックしてWeb appを選択しましょう。Who hasではanyoneを選択して、Deployをクリックします。Authorized accessでログインして承認します。
DeployをクリックするとWeb URLができますのでコピーします。

Slackのappを作る
slackにログインして、slack app Directoryへ移動します。
右上のビルドを選択します。

Create an appを選択し、Appを作成していきましょう。

From scratchを選択し、scratchで作っていきます。

App Nameを任意の文字列で記載し、作成したAppを追加するチャンネルを選択します。
Create Appをクリックします。

Incoming Webhooksを選択し、Google Apps Scriptから受け取るためのURLを取得得します。

Activate Incoming Webhooksを「On」にします。

WebhookURLをCopyして、前のセクションで作成したGoogle App Scriptのスクリプトに貼り付けます。

左側のサイドバーよりEvent Subscriptionsを選択します。

SlackからGoogle Apps Script側のサーバへ送信するためのURLを記載します。
challengeを含むparameterで、Google Apps ScriptのPost関数に送信され、チェックが入ります。

Google Apps ScriptとSlackのEvent Subscriptionsの双方で正しく接続できるようになりましたら、slackでチャットGPTが使えます。
終わりに
チャットGPTをslackでさわれるようにする方法をご紹介しました。
slackを業務で使っている方は、相談役としてチャットGPTを使えるようになり仕事が捗りそうですね。それだけではなく雑談も活発になり、組織力も上がるかも知れません。使ってみてください。
LINEでチャットGPTを使う方法も記事にしています。
興味がある方は併せて読んでくださいね。