Skip to content

Instantly share code, notes, and snippets.

@yoshihiko-k
Created December 5, 2022 16:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoshihiko-k/239233d23409efdacca6c0ece5b20cc2 to your computer and use it in GitHub Desktop.
Save yoshihiko-k/239233d23409efdacca6c0ece5b20cc2 to your computer and use it in GitHub Desktop.
ChatGPTに「chatGPTに質問出来るslack botのtypescriptのコードを書いて下さい」とリクエストして書いてくれたコード
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