Skip to content

Instantly share code, notes, and snippets.

@ina111
Last active March 11, 2023 11:57
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 ina111/f50f3c5aeb2511bada85fd15477d1943 to your computer and use it in GitHub Desktop.
Save ina111/f50f3c5aeb2511bada85fd15477d1943 to your computer and use it in GitHub Desktop.
Slack上でアプリにメンションを飛ばすとChatGPTのAPIからの返信が返ってくるコード。SlackのBoltフレームワークとOpenAIのAPIを使用。app.pyと同じフォルダ.envというAPIのTOKENやAPI Keyを入れるファイルも必要。importに使っているdotenv-python, slack_bolt, openaiはpipなどでインストールすること。
import os
from dotenv import load_dotenv
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
import openai
load_dotenv()
app = App(token=os.environ["SLACK_BOT_TOKEN"])
openai.api_key = os.environ["OPENAI_API_KEY"]
# メンションされたら動作
@app.event("app_mention")
def chatgpt_reply(event, say):
input_message = event["text"]
thread_ts = event.get("thread_ts") or None
channel = event["channel"]
input_message = input_message.replace("<@hogehoge>", "") # ChatbotのアカウントIDの@を削除, hogehogeをアプリのIDに変換
print("prompt: " + input_message)
# 先生かSenseiが入力文字にあれば、そう演じる。それ以外は生のChatGPT
if "先生" in input_message or "Sensei" in input_message:
system_message = """
You play a space expert. Your name is ChatGPT Sensei.
You are very knowledgeable about rockets and satellites. You are also well versed in astronomy.
Please explain my question in as much detail as possible, using technical terms.
Also, when generating sentences, write in a style for business or science.
You try to provide accurate information as much as possible, but there are times when we have no choice but to lie.
You cannot hold continuous conversations and it resets after each one.
You are an MIT aerospace graduate with a Ph.D. in space engineering.
You also worked for NASA for 10 years and was involved in engineering, project manager, management and management positions.
You are a good AI assistant for our team.
"""
else:
system_message = "You are ChatGPT, a large language model trained by OpenAI. Answer as concisely as possible."
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[
{"role": "system", "content": system_message},
{"role": "user", "content": input_message}
]
)
text = response["choices"][0]["message"]["content"]
print("ChatGPT: " + text)
if thread_ts is not None:
parent_thread_ts = event["thread_ts"]
say(text=text, thread_ts=parent_thread_ts, channel=channel)
else:
say(text=text, channel=channel)
# else: # スレッドじゃないときもスレッドに返すときはこれ
# response = app.client.conversations_replies(channel=channel, ts=event["ts"])
# thread_ts = response["messages"][0]["ts"]
# say(text=text, thread_ts=thread_ts, channel=channel)
if __name__ == "__main__":
handler = SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"])
handler.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment