This repository was archived by the owner on Mar 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path__init__.py
More file actions
626 lines (500 loc) · 19.4 KB
/
__init__.py
File metadata and controls
626 lines (500 loc) · 19.4 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
#! python3
# builtin
import os
import re
import inspect
import pickle
import threading
# pip
import emoji
import flask
# debug
from pprint import pprint
class VagueReply:
class VagueContainer:
def __init__(self, definitve, vagues):
self.definitve = definitve
self.vagues = vagues
def match(self, query):
for vagueType in self.vagues:
if vagueType == query:
if hasattr(vagueType, 'lastMatch'):
return vagueType.lastMatch
else:
return vagueType
return None
class TypeRegex:
def __init__(self, pattern, flags=0):
self.regex = re.compile(pattern, flags)
self.lastMatch = None
def match(self, s):
m = self.regex.match(s)
if not m:
self.lastMatch = None
return None
self.lastMatch = m.group(0)
return self.lastMatch
def __eq__(self, s):
if isinstance(s, str):
return self.match(s) is not None
print("%s.__eq__ expected a string" % str(self.__class__.__name__))
return False
class TypeContainsRegex(TypeRegex):
def match(self, s):
self.lastMatch = self.regex.search(s)
return self.lastMatch
@staticmethod
def regex(pattern, flags=0):
return VagueReply.TypeRegex(pattern, flags)
@staticmethod
def containsRegex(pattern, flags=0):
return VagueReply.TypeContainsRegex(pattern, flags)
@staticmethod
def string(s):
return s
def __init__(self):
self.data = []
def new(self, definitive, vagues=None):
if not vagues:
vagues = definitive
definitive = definitive[0]
c = VagueReply.VagueContainer(definitive, vagues)
self.data.append(c)
return c
class ServerHelper:
def __init__(self):
self.commands = {}
self.bot = None
self.vagueReply = VagueReply()
def _registerBot(self, bot):
self.bot = bot
def __registerCommand(self, func, condition_wrapper):
if func.__name__ in self.commands:
self.commands[func.__name__]["conditions"].append(
condition_wrapper)
else:
self.commands[func.__name__] = {
"conditions": [condition_wrapper], "function": func}
return func
@staticmethod
def _emojize(text):
return emoji.emojize(text, use_aliases=True)
@staticmethod
def _demojize(text):
return emoji.demojize(text)
@staticmethod
def _sendText(msg, text, buttons=None, is_question=False):
# Check length of message
if "maxMessageLength" in msg["_bot"].specifications and len(
text) > msg["_bot"].specifications["maxMessageLength"]:
N = msg["_bot"].specifications["maxMessageLength"]
re_newline = re.compile(r"\n|$", flags=re.MULTILINE)
re_whitespace = re.compile(r"\s+", flags=re.MULTILINE)
re_wordend = re.compile(r"\b\s*", flags=re.MULTILINE)
# Split long message up
while len(text) > N:
# Try to split at newline
m = re_newline.search(text, pos=N - 50)
if not m: # try to split at whitespace
m = re_whitespace.search(text, pos=N - 50)
if not m: # try to split at wordend
m = re_wordend.search(text, pos=N - 50)
if not m or m.end() == len(text):
# split anywhere
text, rest = text[0:N - 5] + \
"...", "..." + text[N - 5:].strip()
else:
# split at match
text, rest = text[0:m.start()], text[m.end():].strip()
if len(rest) == 0:
text = rest
break
else:
msg["_bot"].sendText(msg, text)
text = rest
if is_question and getattr(
msg["_bot"],
"sendQuestion",
None) is not None:
return msg["_bot"].sendQuestion(msg, text, buttons)
else:
return msg["_bot"].sendText(msg, text, buttons)
@staticmethod
def _sendLink(msg, url, buttons=None, text=""):
return msg["_bot"].sendLink(msg, url, buttons, text)
@staticmethod
def _sendPhoto(msg, url, buttons=None):
return msg["_bot"].sendPhoto(msg, url, buttons)
def _handleTextMessage(self, msg):
user = self.bot.user(msg)
msg["text_nice"] = self._demojize(msg["text"].strip())
msg["text_nice_lower"] = msg["text_nice"].lower()
# Match a vague answer
m = user.getResponse(msg["text_nice_lower"])
if m is not None:
function = m[0]
function(msg)
return True
# Fallback to question onOtherResponse
onOtherResponse = user.getOnOtherResponse()
if onOtherResponse is not None:
function, lastStage = onOtherResponse[1]
if len(inspect.signature(function).parameters) == 2:
function(msg, lastStage)
else:
function(msg)
return True
# Match any other
for commandName in self.commands:
for condition in self.commands[commandName]["conditions"]:
if condition(msg):
self.commands[commandName]["function"](self.bot, msg)
return True
# Fallback to generic onOther
if hasattr(self.bot, 'onOtherResponse'):
self.bot.onOtherResponse(msg)
return True
print("No handler found for text message: %s" %
msg["text_nice"].encode('unicode-escape').decode('ascii'))
return False
def _handleFriendPicker(self, msg):
if hasattr(self.bot, 'onFriendPicker'):
self.bot.onFriendPicker(msg)
return True
return False
def _handleLocation(self, msg):
if hasattr(self.bot, 'onLocation'):
self.bot.onLocation(msg)
return True
return False
def _handleButtonClick(self, msg):
user = self.bot.user(msg)
button = user.getButton(msg["text"])
if button is None:
return self._handleTextMessage(msg)
if isinstance(button[1], str):
msg["text"] = button[1]
msg["text_nice"] = self._demojize(msg["text"].strip())
msg["text_nice_lower"] = msg["text_nice"].lower()
return self._handleTextMessage(msg)
else:
msg["text_nice"] = self._demojize(msg["text"].strip())
msg["text_nice_lower"] = msg["text_nice"].lower()
function = button[1]
function(msg)
return True
def all(self, *args):
def wrapper(func):
org_func_name = func.__name__
func.__name__ = "fake_" + org_func_name
for arg in args:
arg(func)
conditions = self.commands.pop(func.__name__)["conditions"]
func.__name__ = org_func_name
def __condition(self, msg):
return all([condition(msg) for condition in conditions])
def condition_wrapper(msg):
return __condition(self, msg)
return self.__registerCommand(func, condition_wrapper)
return wrapper
def textLike(self, text):
def __condition(self, msg):
return text.strip().lower() == msg["text_nice_lower"]
def condition_wrapper(msg):
return __condition(self, msg)
def register_command(func):
return self.__registerCommand(func, condition_wrapper)
return register_command
def textStartsWith(self, text):
def __condition(self, msg):
return msg["text_nice_lower"].startswith(text.strip().lower())
def condition_wrapper(msg):
return __condition(self, msg)
def register_command(func):
return self.__registerCommand(func, condition_wrapper)
return register_command
def textRegexMatch(self, rawpattern, flags=re.IGNORECASE):
regex_pattern = re.compile(rawpattern, flags)
def __condition(self, msg):
return regex_pattern.match(msg["text_nice"])
def condition_wrapper(msg):
return __condition(self, msg)
def register_command(func):
return self.__registerCommand(func, condition_wrapper)
return register_command
def userIdEquals(self, userId):
def __condition(self, msg):
return userId == msg["_userId"]
def condition_wrapper(msg):
return __condition(self, msg)
def register_command(func):
return self.__registerCommand(func, condition_wrapper)
return register_command
class Bot:
def __init__(self, serverHelper, title="Bot", userFile=None):
self.serv = serverHelper
self.serv._registerBot(self)
self.title = title
self.__flaskServer = None
self.telegramBot = None
self.kikBot = None
self.facebookBot = None
self.bots = []
self.users = {}
self.userFile = userFile
self.userStorage = None
if self.userFile is not None and os.path.isfile(self.userFile):
with open(self.userFile, "rb") as fs:
self.users = pickle.load(fs)
def addPermanentStorage(self, storage):
self.userStorage = storage
def getPermanentStorage(self):
return self.userStorage
def getBotByName(self, name):
for bot in self.bots:
if type(bot).__name__ == name:
return bot
def getFlask(self):
if self.__flaskServer is None:
self.__flaskServer = flask.Flask(__name__)
return self.__flaskServer
def __runFlask(self, host, port):
return self.__flaskServer.run(
port=port, host=host, debug=False, threaded=True)
def addBot(self, bottype, *args, **kwargs):
bot = bottype(self.serv, *args, **kwargs)
self.bots.append(bot)
print("Added %s" % str(bot))
return bot
def addFlaskBot(self, bottype, *args, **kwargs):
bot = bottype(self.serv, self.getFlask(), *args, **kwargs)
self.bots.append(bot)
print("Added %s" % str(bot))
return bot
def run(self, runFlask=True, host='127.0.0.1', port=8080):
"""Starts all bots.
If runFlask is True, it will run Flask's server on standard host/port.
This call will block the current thread forever.
If False, it will just return the Flask and you may run it later.
You should not use Flask's server for production/deployment"""
print("Starting " + self.title + "...")
for bot in self.bots:
if hasattr(bot, "run"):
bot.run()
if self.__flaskServer is not None:
if runFlask:
print("Starting Flask...")
return self.__runFlask(host, port)
return self.__flaskServer
def user(self, msg):
userId = msg["_userId"]
if userId not in self.users:
self.users[userId] = User(
userId=userId,
lastMsg=msg,
storage=self.userStorage,
bot=msg["_bot"])
self.users[userId].msg(msg)
return self.users[userId]
def startConversation(self, msg, forceExitCommand="/cancel"):
user = self.user(msg)
user.startConversation(forceExitCommand)
def endConversation(self, msg):
self.user(msg).endConversation()
@staticmethod
def createEmptyMessage(fromMsg, toUserId):
return {
"_bot": fromMsg["_bot"],
"_responseMessages": [],
"_responseSent": True,
"_userId": toUserId
}
def sendText(self, msg, text, buttons=None):
"""
Send a text message with quick reply buttons (or commands depending on the bot type)
"""
if isinstance(msg, User):
msg = msg.msg()
return self.serv._sendText(msg, text, buttons)
def sendLink(self, msg, url, buttons=None, text=""):
"""
Sends link to a website and optionally a description text
"""
if isinstance(msg, User):
msg = msg.msg()
return self.serv._sendLink(msg, url, buttons, text)
def sendPhoto(self, msg, url, buttons=None):
"""
Sends a photo by its url
"""
if isinstance(msg, User):
msg = msg.msg()
return self.serv._sendPhoto(msg, url, buttons)
def sendQuestionWithReplies(
self,
msg,
text,
responses=None,
onOtherResponse=None,
onOtherResponseReturn=None):
"""
Sends a text message and expects a reply with predefined replies and actions.
"""
if isinstance(msg, User):
msg = msg.msg()
user = self.user(msg)
if responses is None:
responses = []
user.rememberResponses(
responses,
onOtherResponse,
onOtherResponseReturn)
return self.serv._sendText(
msg, text, buttons=responses, is_question=True)
def sendQuestion(self, msg, text, buttons=None):
"""
Sends a text message and expects a reply
"""
if isinstance(msg, User):
msg = msg.msg()
return self.serv._sendText(
msg, text, buttons=buttons, is_question=True)
def sendTextWithButtons(self, msg, text, buttons):
"""
Send a text message with quick reply buttons (or commands depending on the bot type)
Same as sendText()
"""
if isinstance(msg, User):
msg = msg.msg()
return self.serv._sendText(msg, text, buttons=buttons)
def saveUserFile(self):
if self.userFile is not None:
with open(self.userFile, "wb") as fs:
pickle.dump(self.users, fs)
@staticmethod
def runInThread(fun, *args, **kwargs):
try:
import asyncio
except ModuleNotFoundError:
pass
def runIt(loop, *args, **kwargs):
if loop:
asyncio.set_event_loop(loop)
fun(*args, **kwargs)
try:
loop = asyncio.get_event_loop()
except (RuntimeError, NameError):
loop = None
t = threading.Thread(target=runIt, args=(loop, *args), kwargs=kwargs)
t.daemon = True
t.start()
class User:
def __init__(self, userId, lastMsg=None, storage=None, bot=None):
self.__lastMsg = lastMsg
self.userId = userId
self.bot = bot
self.storage = storage
self.data = {}
self.userdata = {}
if self.storage is not None:
self.userdata = self.storage.retrieve(self.bot, userId)
self.conversation = None
self.onOtherResponseNAME = "__onOtherResponse__123"
def msg(self, msg=None):
if msg is None:
return self.__lastMsg
self.__lastMsg = msg
return msg
def startConversation(self, forceExitCommand):
self.conversation = {}
def endConversation(self):
self.conversation = None
def __clearResponses(self):
root = self.data if self.conversation is None else self.conversation
root["buttons"] = {}
def clearResponses(self):
self.__clearResponses()
def storeValue(self, key, value):
self.userdata[key] = value
if self.storage is not None:
self.storage.store(self.bot, self.userId, key, value)
def retrieveValue(self, key, default=None):
if key in self.userdata:
return self.userdata[key]
else:
return default
def clearValues(self):
self.userdata = {}
if self.storage is not None:
self.storage.clear(self.bot, self.userId)
def rememeberOnOtherResponse(
self,
onOtherResponse,
onOtherResponseReturn=None):
self.rememberResponse(
(self.onOtherResponseNAME, (onOtherResponse, onOtherResponseReturn)))
def rememberResponse(self, button):
root = self.data if self.conversation is None else self.conversation
if "buttons" not in root:
root["buttons"] = {}
root["buttons"][button[0]] = button
def rememberResponses(
self,
buttons,
onOtherResponse=None,
onOtherResponseReturn=None):
root = self.data if self.conversation is None else self.conversation
if "buttons" not in root:
root["buttons"] = {}
for button in buttons:
root["buttons"][button[0]] = button
if onOtherResponse is not None:
self.rememeberOnOtherResponse(
onOtherResponse, onOtherResponseReturn)
def getButton(self, key, clear=True):
root = self.data if self.conversation is None else self.conversation
if "buttons" not in root:
return None
if key not in root["buttons"]:
oldkey = key
for b in root["buttons"]:
if len(
root["buttons"][b]) > 1 and root["buttons"][b][1] == key:
key = b
break
if oldkey == key:
return None
ret = root["buttons"][key]
if clear:
self.__clearResponses()
return ret
def getOnOtherResponse(self):
return self.getButton(self.onOtherResponseNAME, clear=True)
def getResponse(self, query, clear=True):
root = self.data if self.conversation is None else self.conversation
if "buttons" not in root:
return None
query = query.lower()
def check():
for button in root["buttons"].values():
if button[0].lower() == query: # Compare strings
return button[1], button[0], button[0].lower()
if len(button) > 2:
if not isinstance(button[2], list):
vagueContainers = [button[2]]
else:
vagueContainers = button[2]
for vagueContainer in vagueContainers:
if isinstance(
vagueContainer,
VagueReply.VagueContainer):
m = vagueContainer.match(query)
if m is not None:
return button[1], vagueContainer.definitve, m
return None
ret = check()
if ret is None:
return None
if clear:
self.__clearResponses()
return ret