-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
80 lines (65 loc) · 2.14 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import os
import openai
from slack_sdk import WebClient
from slack_bolt import App
from slack_bolt.adapter.socket_mode import SocketModeHandler
import mysql.connector
from dotenv import load_dotenv
from langchain.chat_models import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.memory import ConversationBufferMemory
# Load environment variables
load_dotenv()
# Set up OpenAI API
openai.api_key = os.environ.get("OPENAI_API_KEY")
# Set up MySQL connection
db = mysql.connector.connect(
host=os.environ.get("MYSQL_HOST"),
user=os.environ.get("MYSQL_USER"),
password=os.environ.get("MYSQL_PASSWORD"),
database=os.environ.get("MYSQL_DATABASE")
)
# Set up Slack API
app = App(token=os.environ.get("SLACK_BOT_TOKEN"))
slack_client = WebClient(token=os.environ["SLACK_BOT_TOKEN"])
auth_response = slack_client.auth_test()
bot_user_id = auth_response["user_id"]
# Event handler for app mentions
# Event handler for app mentions
llm = ChatOpenAI(temperature=0.0)
memory = ConversationBufferMemory()
conversation = ConversationChain(
llm=llm,
memory=memory,
verbose=False
)
@app.event("app_mention")
def handle_app_mentions(body, say):
prompt = body["event"]["text"]
user_id = body["event"]["user"]
if user_id == bot_user_id:
return
# Remove @devexpert mention from the prompt
prompt = prompt.replace("<@{}>".format(bot_user_id), "").strip()
# Generate AI response using OpenAI API
response = openai.Completion.create(
engine="text-davinci-002",
prompt=prompt,
max_tokens=2000,
n=1,
stop=None,
temperature=0.7,
)
ai_response = response.choices[0].text.strip()
print(ai_response)
# Save conversation to MySQL database
cursor = db.cursor()
query = "INSERT INTO conversations (user_id, user_input, ai_response) VALUES (%s, %s, %s)"
values = (user_id, prompt, ai_response)
cursor.execute(query, values)
db.commit()
# Respond to the mention with the AI-generated response
say(ai_response)
if __name__ == "__main__":
handler = SocketModeHandler(app, os.environ.get("SLACK_APP_TOKEN"))
handler.start()