Skip to content

Instantly share code, notes, and snippets.

@fukuiretu
Forked from kmizu/ChatGPT.js
Created March 4, 2023 04:56
Show Gist options
  • Save fukuiretu/cdcd7e17dc47829f0f88e24f759715b7 to your computer and use it in GitHub Desktop.
Save fukuiretu/cdcd7e17dc47829f0f88e24f759715b7 to your computer and use it in GitHub Desktop.
Google Apps Script to use ChatGPT API
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(YOUR_SLACK_WEBHOOK_URL, options);
}
// ChatGPTのAPIを呼び出し応答を取得する
function getChatGptMessage(message) {
var uri = 'https://api.openai.com/v1/chat/completions';
var headers = {
'Authorization': `Bearer ${ScriptProperties.getProperty("OPENAI_API_KEY")}`,
'Content-type': 'application/json',
'X-Slack-No-Retry': 1
};
var options = {
'muteHttpExceptions' : true,
'headers': headers,
'method': 'POST',
'payload': JSON.stringify({
model: "gpt-3.5-turbo",
messages: [
{role: "user", content: message}
]
})
};
console.log(options)
try {
const response = UrlFetchApp.fetch(uri, options);
var json = JSON.parse(response.getContentText());
let generatedText = json["choices"][0]['message']['content'];
console.log(generatedText);
return generatedText;
} catch(e) {
console.log('error');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment