-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.py
150 lines (109 loc) · 4.31 KB
/
bot.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
150
import websocket
import _thread
import time
import rel
import json
import requests
wsAPIBaseURL = "wss://api.graspity.com:8001"
restAPIBaseURL = "https://api.graspity.com:8000"
token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXUyJ9.eyJpc3MiOiJncmFzcGl0eS5zdmMuYXV0aCIsInN1YiI6IlNvTzFoZ0FGLnBjZWc5T29fWnRDZ3cifQ.Gg2CBWm8Xkuh_csTygpr_dni_4SuYS_O-1tWhJ2CS2o"
userId = "SoO1hgAF.pceg9Oo_ZtCgw" # MY userId
communityId = "S9qGDgAF.oCXxEAKWPh1Ug"
def authAndSubscribe():
auth = {"t": 3, "p": token, "ocid": "auth"}
ws.send(json.dumps(auth))
subs = {"t": 200, "p": {"communityId": communityId}, "ocid": "subscribe"}
ws.send(json.dumps(subs))
def getLastMessages(channelId, offset, limit, filter):
page = requests.get(
restAPIBaseURL +
"/communities/" + communityId +
"/channels/" + channelId +
"/messages/offset/" + str(offset) +
"/limit/" + str(limit) +
"/direction/1/?" + filter,
headers = {"Authorization":"Bearer " + token}).json()
return page
def sendReply(ws, channelId, originalMessage, replyText):
msg = {
"type": "TEXT",
"authorDisplayName": "Hello Bot",
"data": replyText,
"tags": [],
"mentions": [originalMessage["author"]]
}
requests.post(
restAPIBaseURL +
"/communities/" + communityId +
"/channels/" + channelId +
"/messages/" + str(originalMessage["index"]) +
"/replies",
data=json.dumps(msg),
headers = {"Authorization":"Bearer " + token}
)
def processPageAndReply(ws, channelId, originalMessage, page):
if page["type"] != "CHANNEL_MESSAGE_PAGE":
print("Error - can't obtain messages page")
return
messages = page["payload"]["items"]
print("items-count=" + str(len(messages)))
plainText = "";
for item in messages:
msg = item["object"]
# Exclude bot's messages
if msg["author"] != userId:
plainText = msg["authorDisplayName"] + ": " + msg["data"] + "\n\n" + plainText
# TODO - put you logic here
replyText = "Hello [@" + originalMessage["authorDisplayName"] + "](mn:" + originalMessage["author"] + ")" + "\n\n"
replyText += "Here the text I've processed: \n\n" \
"```\n" + \
plainText + \
"```\n\n" + \
"Regards,\nHello Bot"
sendReply(ws, channelId, originalMessage, replyText)
def onBotMentioned(ws, channelId, message):
# do not process own messages
if message["author"] == userId:
print("Oh it was me...")
return
print("BOT WAS MENTIONED IN CHANNEL " + channelId)
if message["threadIndex"] is None:
print("in public")
page = getLastMessages(channelId, message["index"], 10, "")
processPageAndReply(ws, channelId, message, page)
else:
print("in thread " + str(message["threadIndex"]))
page = getLastMessages(channelId, message["index"], 10, "td=" + str(message["threadIndex"]))
processPageAndReply(ws, channelId, message, page)
def on_message(ws, message):
print(message)
msg = json.loads(message)
if msg["t"] == 1:
pong = {"t": 2, "p": msg["p"]}
ws.send(json.dumps(pong))
elif msg["t"] == 100:
channelId = msg["p"]["channelId"]
# 0 - new message
if msg["p"]["payload"]["type"] == 0:
mentions = msg["p"]["payload"]["payload"]["mentions"]
print("mentions=" + json.dumps(mentions));
if userId in mentions:
onBotMentioned(ws, channelId, msg["p"]["payload"]["payload"])
def on_error(ws, error):
print(error)
def on_close(ws, close_status_code, close_msg):
print("### closed ###")
def on_open(ws):
print("Opened connection")
print("Auth and subscribe...")
authAndSubscribe()
if __name__ == "__main__":
#websocket.enableTrace(True)
ws = websocket.WebSocketApp(wsAPIBaseURL + "/ws",
on_open=on_open,
on_message=on_message,
on_error=on_error,
on_close=on_close)
ws.run_forever(dispatcher=rel, reconnect=5) # Set dispatcher to automatic reconnection, 5 second reconnect delay if connection closed unexpectedly
rel.signal(2, rel.abort) # Keyboard Interrupt
rel.dispatch()