This repository has been archived by the owner on Jan 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.py
72 lines (60 loc) · 2.44 KB
/
server.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
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import zulip
import sys
import threading
import json
import requests
import secrets
import ssl
# !!! Please fill in all constants in secrets.py before operating !!!
# Make a post request to the groupme api to post to a chat.
def send_to_groupme(msg):
if(msg['sender_full_name'] != secrets.ZULIP_BOT_NAME and msg['subject'] == secrets.ZULIP_TOPIC):
requests.post("https://api.groupme.com/v3/bots/post",
data={'bot_id': secrets.GROUPME_BOT_ID,
'text': msg['sender_full_name'] + ": " + msg['content']})
# Use the python zulip functions to post to a stream
def send_to_zulip(msg):
if(msg['name'] != secrets.GROUPME_BOT_NAME):
message_text = msg['text']
# Check for image
for attachment in msg['attachments']:
# Add link to image to message text
if attachment['type'] == 'image':
caption = message_text if message_text else 'image'
message_text = '[%s](%s)\n' % (caption, attachment['url'])
break
client.send_message({
"type": "stream",
"to": secrets.ZULIP_STREAM,
"subject": secrets.ZULIP_TOPIC,
"content": "**" + msg['name'] + "**: " + message_text
})
# Handler for the groupme messages
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_POST(self):
content_length = int(self.headers['Content-Length'])
post_data = json.loads(self.rfile.read(content_length))
send_to_zulip(post_data)
self._set_headers()
# Actual server to handle the groupme messages
def run_groupme_listener():
server_address = ('', secrets.GROUPME_PORT)
httpd = HTTPServer(server_address, S)
print 'Starting httpd...'
httpd.socket = ssl.wrap_socket (httpd.socket, certfile=secrets.SSL_CERT_PATH, server_side=True)
httpd.serve_forever()
# Wrapper for the zulip listener for threading
def run_zulip_listener():
client.call_on_each_message(send_to_groupme)
# Start zulip listener in the background
client = zulip.Client(email=secrets.ZULIP_BOT_EMAIL, api_key=secrets.ZULIP_API_KEY, site=secrets.ZULIP_URL)
t = threading.Thread(target=run_zulip_listener)
t.setDaemon(True)
t.start()
#start the groupme listener as the main service
run_groupme_listener()