-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.py
305 lines (258 loc) · 9.63 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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
#!/usr/bin/env python3
from telegram import Update
from telegram.ext import (
Updater,
CommandHandler,
CallbackContext,
MessageHandler,
Filters,
CallbackQueryHandler,
)
import telegram
import sys
from datetime import datetime
import pytz
# Us
from scraper import get_bloodstocks
from strings import HELLO_MSG, ABOUT_MSG, DONATE_MSG
from subscribe import subscribe_c, subscribe_cb, unsubscribe_c
from firebase_persistence import FirebasePersistence
from stocks import (
format_stocks,
get_stock_diffs,
diffs_to_str,
diffs_with_bloodtype_to_str,
)
from storage import *
# 30 min
UPDATE_INTERVAL_SECS = 20 * 60
# Already formatted string to pass to /check
STOCKS_STR = None
# Stocks retrieved from previous pass
OLD_STOCKS = None
# Current stocks
CURRENT_STOCKS = None
# Test: first message from bot should be an auto update if we are subscribed appropriately
"""
Original
{'A+': {'fill_level': '100', 'status': 'Healthy'},
'A-': {'fill_level': '69', 'status': 'Healthy'},
'AB+': {'fill_level': '100', 'status': 'Healthy'},
'AB-': {'fill_level': '40', 'status': 'Low'},
'B+': {'fill_level': '100', 'status': 'Healthy'},
'B-': {'fill_level': '66', 'status': 'Healthy'},
'O+': {'fill_level': '100', 'status': 'Healthy'},
'O-': {'fill_level': '51', 'status': 'Moderate'}}
"""
# CURRENT_STOCKS_TEST = {
# "A+": {"fill_level": "90", "status": "Healthy"}, # Lower fill, same state
# "A-": {"fill_level": "69", "status": "Healthy"},
# "AB+": {"fill_level": "100", "status": "Healthy"},
# "AB-": {"fill_level": "20", "status": "Critical"}, # Lower fill, different state
# "B+": {"fill_level": "100", "status": "Healthy"},
# "B-": {"fill_level": "67", "status": "Healthy"}, # Higher fill, same state
# "O+": {"fill_level": "100", "status": "Healthy"},
# "O-": {"fill_level": "70", "status": "Healthy"}, # Higher fill, different state
# }
# CURRENT_STOCKS = CURRENT_STOCKS_TEST
# Last updated time
LAST_BOT_UPDATE_TIME = None
LAST_REDCROSS_UPDATE_TIME = None
# Diffs
CURRENT_DIFF = None
CURRENT_DIFF_STR = None
# Datetime
TIMEZONE = pytz.timezone("Asia/Singapore")
def update_stocks(context: CallbackContext):
global STOCKS_STR
global OLD_STOCKS
global CURRENT_STOCKS
global LAST_BOT_UPDATE_TIME
global LAST_REDCROSS_UPDATE_TIME
global CURRENT_DIFF
global CURRENT_DIFF_STR
# Replace old stocks
OLD_STOCKS = CURRENT_STOCKS
# Update new stocks
new_stocks = get_bloodstocks()
# If we have an error, new_stocks will return {}. Kill this run if so.
if not new_stocks:
print(f"Failed to get blood stocks! Check error log.")
return
CURRENT_STOCKS = new_stocks
# Update our last update time
current_time = pytz.utc.localize(datetime.utcnow()).astimezone(TIMEZONE)
LAST_BOT_UPDATE_TIME = current_time
print(f"Current time is: {str(current_time)}")
# Format /check string
stock_str = format_stocks(new_stocks, current_time)
STOCKS_STR = stock_str
# Check diffs between old and current stocks
if OLD_STOCKS is not None and CURRENT_STOCKS is not None:
diffs = get_stock_diffs(CURRENT_STOCKS, OLD_STOCKS)
print(diffs)
if diffs:
# Update globals
# CURRENT_DIFF = diffs
# LAST_REDCROSS_UPDATE_TIME = current_time
# Get a generic diffs string to send to all the alldiffs subscribers
diffs_str = diffs_to_str(diffs, current_time)
# CURRENT_DIFF_STR = diffs_str
print(diffs_str)
update_current_diff(context, diffs, diffs_str)
# Update all "any"-blood stock subscribers
update_any_subscribers(context, diffs_str)
# Update type-by-type
for key in diffs:
update_subscribers_for_bloodtype(context, diffs, key, current_time)
def update_any_subscribers(context: CallbackContext, diffs_str):
"""
For subscribers that want the "any" subscription, send them the diff string
"""
users = get_all_users(context)
for user in users:
if is_user_any_blood_subscription(context, user):
try:
context.bot.send_message(
chat_id=int(user),
text=diffs_str,
parse_mode=telegram.constants.PARSEMODE_MARKDOWN,
)
except Exception as e:
print("Exception during send!")
print(e.__doc__)
print(e.message)
def update_subscribers_for_bloodtype(
context: CallbackContext, diffs, bloodtype: str, current_time
):
"""
For specific updates on specific bloodtypes.
Don't send them this update if they are already subscribed to "any"
"""
diffs_str = diffs_with_bloodtype_to_str(diffs, bloodtype, current_time)
users = get_all_users(context)
for user in users:
if is_user_blood_subscription(
context, user, bloodtype
) and not is_user_any_blood_subscription(context, user):
try:
context.bot.send_message(
chat_id=int(user),
text=diffs_str,
parse_mode=telegram.constants.PARSEMODE_MARKDOWN,
)
except Exception as e:
print("Exception during send!")
print(e.__doc__)
print(e.message)
def update_stocks_interval(context: CallbackContext):
print("Updating stocks at interval")
update_stocks(context)
def hello(update: Update, context: CallbackContext) -> None:
"""
/start command, send hello message and then the check string
"""
print(
f"Received message: /start from chat id {update.message.chat_id} ({update.message.chat.first_name} {update.message.chat.last_name})"
)
update.message.reply_text(HELLO_MSG)
check(update, context)
def help_c(update: Update, context: CallbackContext) -> None:
"""
/help command, /start without the blood bank info
"""
print(
f"Received message: /help from chat id {update.message.chat_id} ({update.message.chat.first_name} {update.message.chat.last_name})"
)
update.message.reply_text(HELLO_MSG)
def check(update: Update, context: CallbackContext) -> None:
"""
/check command, send blood stock string
"""
print(
f"Received or processing code for: /check from chat id {update.message.chat_id} ({update.message.chat.first_name} {update.message.chat.last_name})"
)
update.message.reply_text(
STOCKS_STR, parse_mode=telegram.constants.PARSEMODE_MARKDOWN
)
def change(update: Update, context: CallbackContext) -> None:
"""
/change command, send the latest change in all blood stocks
"""
print(
f"Received or processing code for: /change from chat id {update.message.chat_id} ({update.message.chat.first_name} {update.message.chat.last_name})"
)
diffstr = get_current_diff_str(context)
if diffstr:
update.message.reply_text(
diffstr, parse_mode=telegram.constants.PARSEMODE_MARKDOWN
)
else:
update.message.reply_text(
"No stock changes observed recently.",
parse_mode=telegram.constants.PARSEMODE_MARKDOWN,
)
def about(update: Update, context: CallbackContext) -> None:
"""
/about command, send info message
"""
print(
f"Received message: /about from chat id {update.message.chat_id} ({update.message.chat.first_name} {update.message.chat.last_name})"
)
update.message.reply_text(
ABOUT_MSG, parse_mode=telegram.constants.PARSEMODE_MARKDOWN
)
def donate(update: Update, context: CallbackContext) -> None:
"""
/donate command, send info message
"""
print(
f"Received message: /donate from chat id {update.message.chat_id} ({update.message.chat.first_name} {update.message.chat.last_name})"
)
update.message.reply_text(
DONATE_MSG, parse_mode=telegram.constants.PARSEMODE_MARKDOWN
)
def unknown(update, context):
print(
f"Received unknown command: {update.message.text} from chat id {update.message.chat_id}"
)
context.bot.send_message(
chat_id=update.effective_chat.id,
text="Sorry, I didn't understand that command.",
)
def error_callback(update, context):
print(
f"\n!!!!!!!! Update caused error: [[ {context.error} ]] \nFrom Update: {update}\n"
)
def setup(token):
my_persistence = FirebasePersistence.from_environment(
store_user_data=False,
store_chat_data=False,
store_bot_data=True,
)
updater = Updater(
token,
persistence=my_persistence,
use_context=True,
)
# update_stocks()
j = updater.job_queue
job_minute = j.run_repeating(
update_stocks_interval, interval=UPDATE_INTERVAL_SECS, first=1
)
# Handle initial start message
updater.dispatcher.add_handler(CommandHandler("start", hello))
updater.dispatcher.add_handler(CommandHandler("check", check))
updater.dispatcher.add_handler(CommandHandler("changes", change))
updater.dispatcher.add_handler(CommandHandler("about", about))
updater.dispatcher.add_handler(CommandHandler("help", help_c))
updater.dispatcher.add_handler(CommandHandler("donate", donate))
updater.dispatcher.add_handler(CommandHandler("subscribe", subscribe_c))
updater.dispatcher.add_handler(CommandHandler("unsubscribe", unsubscribe_c))
updater.dispatcher.add_handler(CallbackQueryHandler(subscribe_cb))
# Handle unknown commands
unknown_handler = MessageHandler(Filters.command, unknown)
updater.dispatcher.add_handler(unknown_handler)
# Error handling
updater.dispatcher.add_error_handler(error_callback)
return updater