forked from DidierRLopes/slackGPT
-
Notifications
You must be signed in to change notification settings - Fork 0
/
slackgpt.py
149 lines (109 loc) · 5.52 KB
/
slackgpt.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
import os
import json
from openai import OpenAI
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from dotenv import load_dotenv
from datetime import datetime
from slack_sdk import WebClient
from slack_sdk.errors import SlackApiError
# Load environment variables
load_dotenv()
# OpenAI API
OPENAI_API_KEY = os.getenv('OPENAI_API_KEY') or "REPLACE-ME"
# Slack API
SLACK_WEBHOOK_URL = os.getenv('SLACK_WEBHOOK_URL') or "REPLACE-ME"
SLACK_TOKEN = os.getenv('SLACK_TOKEN') or "REPLACE-ME"
# Slack channels ids separated by commas (no spaces), e.g. ABC123,DEF456,GHI789
SLACK_CHANNEL_IDS = os.getenv('SLACK_CHANNEL_IDS') or "REPLACE-ME"
def main():
client = WebClient(token=SLACK_TOKEN)
for channel_id in SLACK_CHANNEL_IDS.split(","):
# Store conversation history
conversation_history = []
try:
# --- Get conversation history ---
# Get the current date and time in UTC
current_datetime_utc = datetime.utcnow()
# Set the time to the beginning of today
start_of_today_utc = datetime(current_datetime_utc.year, current_datetime_utc.month, current_datetime_utc.day, 0, 0, 0)
# Get the data from the beginning of today in UTC
result = client.conversations_history(channel=channel_id, oldest=str(int(start_of_today_utc.timestamp())))
conversation_history = result["messages"]
# --- Parse conversation history ---
convo = ""
# Parse this conversation history
for message in conversation_history:
# Check if this is a user message
if ("type" in message and message["type"] == "message" and "subtype" not in message):
# Check if there's a user associated with the message
if "user" in message:
# Get the user's real name from the users.info API method
real_name = client.users_info(user=message['user']).get("user").get("real_name")
# The 28_000 is to convert from UTC to PST (8*60*60)
text = f"At {datetime.utcfromtimestamp(float(message['ts'])-28_800).strftime('%H:%M')} {real_name} "
if "text" in message and message['text']:
text += f"said '{message['text']}' "
# Provide a link to the files uploaded by the user
if "files" in message:
text += "shared the following files: "
for file in message["files"]:
text += file['url_private'] + ","
# Remove the last comma
text = text[:-1]
# Create the conversation from a channel
convo += text + "\n"
# --- Get channel name ---
# Call the conversations.info method with the channel ID
conversation_info = client.conversations_info(channel=channel_id)
# Extract the channel name from the result
channel_name = conversation_info["channel"]["name"]
# Print results
if convo:
# --- OpenAI Summarization ---
client = OpenAI(api_key=OPENAI_API_KEY)
response = client.chat.completions.create(
model="gpt-4",
messages=[
{
"role": "system",
"content": "You are an executive assistant that analyzes messages on Slack and performs a summary."
},
{
"role": "user",
"content": f"In the channel {channel_name}, summarize the following conversation that has unfolded:\n{convo}"
},
]
)
summary = response.choices[0].message.content
# --- Send Slack message with summary ---
payload = {
'text': summary,
}
req = Request(SLACK_WEBHOOK_URL, json.dumps(payload).encode('utf-8'))
try:
response = urlopen(req)
response.read()
print("SUCCESS: Message with insights sent to slack\n")
except HTTPError as e:
print(f"Request failed: {e.code} {e.reason}\n")
except URLError as e:
print(f"Server connection failed: {e.reason}\n")
else:
# --- Send Slack message saying no messages were found ---
payload = {
'text': f"No messages were found in channel {channel_name}.",
}
req = Request(SLACK_WEBHOOK_URL, json.dumps(payload).encode('utf-8'))
try:
response = urlopen(req)
response.read()
print("SUCCESS: Message with insights sent to slack\n")
except HTTPError as e:
print(f"Request failed: {e.code} {e.reason}\n")
except URLError as e:
print(f"Server connection failed: {e.reason}\n")
except SlackApiError as e:
print(f"Error creating conversation: {e}")
if __name__ == '__main__':
main()