-
-
Save fukuiretu/cdcd7e17dc47829f0f88e24f759715b7 to your computer and use it in GitHub Desktop.
Google Apps Script to use ChatGPT API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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