-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtelegrambot.py
257 lines (207 loc) · 10.4 KB
/
telegrambot.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
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
import telegram
import json
from io import BytesIO
import requests
from requests.auth import HTTPDigestAuth
class Bot(object):
"""docstring for Bot."""
chat_ids = []
valid_chat_ids = []
def __init__(self, token, alarm, config):
super(Bot, self).__init__()
self.token = token
self.alarm = alarm
self.config = config
self.chat_ids = config.get('telegram.chat_ids', [])
self.valid_chat_ids = config.get('telegram.valid_chat_ids', [])
self.updater = Updater(self.token, use_context=False)
self.updater.dispatcher.add_handler(CommandHandler('start', self.handleStart))
self.updater.dispatcher.add_handler(CommandHandler('help', self.handleHelp))
self.updater.dispatcher.add_handler(CommandHandler('settings', self.handleSettings))
self.updater.dispatcher.add_handler(CommandHandler('on', self.handleOn))
self.updater.dispatcher.add_handler(CommandHandler('off', self.handleOff))
self.updater.dispatcher.add_handler(CommandHandler('home', self.handleHome))
self.updater.dispatcher.add_handler(CommandHandler('status', self.handleStatus))
self.updater.dispatcher.add_handler(CommandHandler('siren', self.handleSiren, pass_args=True))
self.updater.dispatcher.add_handler(CommandHandler('custom', self.handleCustom, pass_args=True))
self.updater.dispatcher.add_handler(CallbackQueryHandler(self.inlineCallbackQuery))
self.updater.dispatcher.add_handler(CommandHandler('grant', self.handleGrant, pass_args=True))
self.updater.dispatcher.add_handler(CommandHandler('config', self.handleConfig, pass_args=True))
self.updater.dispatcher.add_handler(CommandHandler('images', self.handleImages))
self.updater.start_polling()
def start(self):
self.updater.start_polling()
def stop(self):
self.updater.stop()
def notifyStatus(self, status):
self.broadcastMessage("Alarm is now *{}*".format(status), parse_mode=telegram.ParseMode.MARKDOWN)
def notifyWarning(self, msg):
self.broadcastMessage("{}".format(msg), parse_mode=telegram.ParseMode.MARKDOWN, include_images=True)
def validateChat(self, bot, update):
print("= message in {}".format(update.message.chat_id))
# collect all chat_ids engaging, so we can validate /grant calls later
self.addChatId(update.message.chat_id)
if update.message.chat_id not in self.valid_chat_ids:
print("=> Rejected chat {}".format(update.message.chat_id))
update.message.reply_text("Sorry, you don't have access.")
self.broadcastMessage(
"Rejected chat {} ({})".format(update.message.chat_id, update.message.from_user.first_name),
reply_markup = telegram.InlineKeyboardMarkup([[telegram.InlineKeyboardButton("Grant access", callback_data='/grant {}'.format(update.message.chat_id))]]))
return False
return True
def broadcastMessage(self, msg, parse_mode=None, reply_markup=None, include_images=False):
for chat_id in self.valid_chat_ids:
self.updater.bot.send_message(chat_id=chat_id, text=msg, parse_mode=parse_mode, reply_markup=reply_markup)
if include_images:
cameras = self.config.get('cameras', [])
print("= Send warning images for {} cameras".format(len(cameras)))
media = []
for camera in cameras:
try:
r = requests.get(
camera['url'],
auth=HTTPDigestAuth(camera['auth'][0], camera['auth'][1])
)
fp = BytesIO(r.content)
media.append(telegram.InputMediaPhoto(fp))
except Exception as e:
print("error fetching for camera: {}".format(camera['url']))
print(e)
if len(media) > 1:
for chat_id in self.valid_chat_ids:
self.updater.bot.send_media_group(chat_id=chat_id, media=media, parse_mode=parse_mode)
def inlineCallbackQuery(self, bot, update):
query = update.callback_query
print(update, query)
if query.data.split(" ")[0] == "/grant":
chat_id = int(query.data.split(" ")[1])
msg = self.grant(chat_id, query.message.chat.first_name)
else:
msg = "unknown action"
bot.edit_message_text(text=msg,
chat_id=query.message.chat_id,
message_id=query.message.message_id)
def handleStart(self, bot, update):
if not self.validateChat(bot, update):
return False
keyboard = telegram.ReplyKeyboardMarkup([["/off","/home","/on", "/images"]], resize_keyboard=True)
update.message.reply_text("Control the alarm", reply_markup=keyboard)
def handleHelp(self, bot, update):
if not self.validateChat(bot, update):
return False
keyboard = telegram.ReplyKeyboardMarkup([["/off","/home","/on", "/images"]], resize_keyboard=True)
update.message.reply_text("Send command /on or /off to change alarm status.", reply_markup=keyboard)
def handleSettings(self, bot, update):
if not self.validateChat(bot, update):
return False
update.message.reply_text("Not really used, sorry!")
def hello(self, bot, update):
if not self.validateChat(bot, update):
return False
update.message.reply_text(
'Hello {}'.format(update.message.from_user.first_name))
def handleOn(self, bot, update):
if not self.validateChat(bot, update):
return False
print("= Command On in {}".format(update.message.chat_id))
self.alarm.queueRequest(self.alarm.requestStatusChange(1), name=update.message.from_user.first_name)
def handleOff(self, bot, update):
if not self.validateChat(bot, update):
return False
print("= Command Off in {}".format(update.message.chat_id))
self.alarm.queueRequest(self.alarm.requestStatusChange(0), name=update.message.from_user.first_name)
def handleHome(self, bot, update):
if not self.validateChat(bot, update):
return False
print("= Command Home in {}".format(update.message.chat_id))
self.alarm.queueRequest(self.alarm.requestStatusChange(2), name=update.message.from_user.first_name)
def handleStatus(self, bot, update):
if not self.validateChat(bot, update):
return False
print("= Command Status in {}".format(update.message.chat_id))
update.message.reply_text("Alarm is {}".format(self.alarm.statusName))
def handleImages(self, bot, update):
if not self.validateChat(bot, update):
return False
cameras = self.config.get('cameras', [])
print("= Command Images in {} for {} cameras".format(update.message.chat_id, len(cameras)))
msg = update.message.reply_text("fetching images....")
media = []
for camera in cameras:
try:
r = requests.get(
camera['url'],
auth=HTTPDigestAuth(camera['auth'][0], camera['auth'][1])
)
fp = BytesIO(r.content)
media.append(telegram.InputMediaPhoto(fp))
except Exception as e:
print("error fetching for camera: {}".format(camera['url']))
print(e)
if len(media):
update.message.reply_media_group(media)
msg.delete()
def handleSiren(self,bot,update, args):
if not self.validateChat(bot, update):
return False
print("= Command Siren in {}".format(update.message.chat_id))
if len(args) < 1:
try:
value = "on" if self.alarm._svle > 0 else "off"
except AttributeError as e:
value = "unknown"
update.message.reply_text(
"Siren currently **{}**\n\n/siren on - Enable siren\n/siren off - Disable siren".format(value),
parse_mode=telegram.ParseMode.MARKDOWN
)
else:
arg = args[0].lower()
if arg == "off":
value = 0
elif arg == "on":
value = 1
elif int(arg) == 0:
value = 0
else:
value = 1
req = "{{\"sg_svle\":\"{}\"}}".format(value)
update.message.reply_text("Send: {}".format(req))
self.alarm.queueRequest(req, name=update.message.from_user.first_name)
def handleCustom(self, bot, update, args):
if not self.validateChat(bot, update):
return False
print("= Command CUSTOM in {}".format(update.message.chat_id))
print(args)
if len(args) < 1:
update.message.reply_text("Requires some code")
cmd = " ".join(args)
update.message.reply_text("Send to Box: {}".format(cmd))
self.alarm.queueRequest(cmd, name=update.message.from_user.first_name)
def addChatId(self, chat_id):
if chat_id not in self.chat_ids:
self.chat_ids.append(chat_id)
self.config.set('telegram.chat_ids', self.chat_ids)
def addValidChatId(self, chat_id):
if chat_id not in self.valid_chat_ids:
self.valid_chat_ids.append(chat_id)
self.config.set('telegram.valid_chat_ids', self.valid_chat_ids)
def grant(self, chat_id, from_name=""):
chat_id = int(chat_id)
if chat_id in self.valid_chat_ids:
return "Already added {}".format(chat_id)
elif chat_id not in self.chat_ids:
return "Unknown chat id '{}'".format(chat_id)
else:
self.addValidChatId(chat_id)
self.updater.bot.send_message(chat_id=chat_id, text="{} granted you control over the alarm".format(from_name))
return "Granted '{}' control over alarm".format(chat_id)
def handleGrant(self, bot, update, args):
if not self.validateChat(bot, update):
return False
for arg in args:
msg = self.grant(chat_id, update.message.from_user.first_name)
def handleConfig(self, bot, update, args):
if not self.validateChat(bot, update):
return False
update.message.reply_text(json.dumps(self.alarm.__dict__, indent=2))