-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathmessenger.py
144 lines (119 loc) · 4.19 KB
/
messenger.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
#!/usr/bin/env python3
########################################
# is_ieee_open.py
# [email protected], April 2022
#
# This component of the program handles sending
# alert messages, over discord and email
########################################
import requests
import smtplib, ssl # for sending email
import os
import time
import logging
import _creds_
port = 465 # For SMTP SSL
def main():
# used for testing all relevant alerting systems
print("The main of messenger.py should NOT be called in normal operation. ")
print("Testing messenger functionality: ")
print("trying to send discord testing message")
if send_room_alert("test"):
print("send test message alert succeeded!")
print("testing send_room_open")
if send_room_alert("open"):
print("send room open succeeded!")
print("testing send_room_closed")
if send_room_alert("closed"):
print("send room closed succeeded!")
print("sending poweroff test")
send_room_alert("poweroff")
print("testing sending email")
if send_email(1, "SCRIPT TEST; DISREGARD"):
print("sending email succeeded!")
def send_room_alert(alert_code):
# set alert_code = whatever json packet we're going to use
if alert_code == "open":
json_data = open_data
elif alert_code == "closed":
json_data = closed_data
elif alert_code == "test":
json_data = test_message
elif alert_code == "poweron":
json_data = poweron_data
elif alert_code == "poweroff":
json_data = poweroff_data
else:
json_data = interp_error_data
try:
result = requests.post(_creds_.WEBHOOK_URL, json = json_data)
except ConnectionError as err:
logging.info("ConnectionError: " + str(err))
time.sleep(1) # prevent overloading server with requests
return False, err
except Exception as err:
logging.info("Generic Exception: " + str(err))
time.sleep(1) # prevent overloading server with requests
return False, err
try:
result.raise_for_status()
except requests.exceptions.HTTPError as err:
logging.info(err)
time.sleep(1) # prevent overloading server with requests
return False, err
except Exception as err:
logging.info("Generic Exception: " + str(err))
time.sleep(1) # prevent overloading server with requests
return False, err
else:
logging.info(f'Success, HTTP code {result.status_code}.')
return True, "none"
# send error email
def send_email(fail_count, error_desc):
message = """\
Subject: IEEE Room Alert Bot Notice
Number of failed send attempts: {}
Error description: {}
Uptime: {}
This message was sent by an automated system.""".format(fail_count, error_desc, os.popen('uptime -p').read()[:-1])
try:
# try sending email
context = ssl.create_default_context()
with smtplib.SMTP_SSL(_creds_.smtp_server, port, context=context) as server:
server.login(_creds_.sender_email, _creds_.password)
result = server.sendmail(_creds_.sender_email, _creds_.receiver_email, message)
logging.info("Server sendmail result: ", end="")
logging.info(result)
except Exception as err:
logging.info("Error sending email! We received: " + str(err))
return False
else:
logging.info("Email sent successfully")
return True
# JSON data packets for the discord message webhooks
open_data = {
"content" : "Looks like the IEEE Room is open! :sunglasses:",
"username" : "IEEE Room Alert"
}
closed_data = {
"content" : "Looks like the IEEE Room is no longer open :disappointed:",
"username" : "IEEE Room Alert"
}
poweron_data = {
"content" : "Powering on!",
"username" : "IEEE Room Alert"
}
poweroff_data = {
"content" : "Time for a graceful shutdown :(",
"username" : "IEEE Room Alert"
}
interp_error_data = {
"content" : "Looks like we ran into an error and I'm not sure what to send out :(",
"username" : "IEEE Room Alert"
}
test_message = {
"content" : "Results of testing the messaging functionality on discord: ",
"username" : "IEEE Room Alert"
}
if __name__=="__main__":
main()