ChatGPTに「chatGPTに質問出来るslack botのtypescriptのコードを書いて下さい」とリクエストして書いてくれたコード
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
import { WebClient } from "@slack/web-api"; | |
import { RTMClient } from "@slack/rtm-api"; | |
import { Request, Response } from "express"; | |
import { createEventAdapter } from "@slack/events-api"; | |
// Slack Appのトークンを設定 | |
const slackWebClient = new WebClient(process.env.SLACK_TOKEN); | |
const slackRtmClient = new RTMClient(process.env.SLACK_TOKEN); | |
const slackEvents = createEventAdapter(process.env.SLACK_SIGNING_SECRET); | |
// Slack Botの名前を設定 | |
const botName = "ChatGPT"; | |
// Botが参加しているチャンネル一覧を取得 | |
const channels = await slackWebClient.conversations.list(); | |
const botChannels = channels.channels.filter( | |
(channel) => channel.is_member | |
); | |
// Slack Botがメッセージを受信したときの処理 | |
slackEvents.on("message", async (event) => { | |
if (event.text.includes(botName)) { | |
// Botに話しかけられた場合、ChatGPTに質問を送信 | |
const question = event.text.replace(botName, ""); | |
const response = await sendQuestionToChatGPT(question); | |
slackRtmClient.sendMessage(response, event.channel); | |
} | |
}); | |
// ChatGPTへの質問を送信する処理 | |
async function sendQuestionToChatGPT(question: string) { | |
// ChatGPT APIを呼び出して質問に対する回答を取得 | |
const response = await fetch("https://api.openai.com/v1/completions", { | |
method: "POST", | |
headers: { | |
"Content-Type": "application/json", | |
Authorization: `Bearer ${process.env.CHATGPT_SECRET}`, | |
}, | |
body: JSON.stringify({ | |
prompt: question, | |
model: "text-davinci-002", | |
max_tokens: 128, | |
temperature: 0.5, | |
}), | |
}); | |
const data = await response.json(); | |
return data.choices[0].text; | |
} | |
// Slack Event APIのエンドポイントを設定 | |
app.use("/events", slackEvents.requestListener()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment