-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChatBot
583 lines (518 loc) · 12.8 KB
/
ChatBot
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
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import telegram
import numpy
import pandas as pd
import os
import psycopg2
import urllib.parse
import threading
import time
from datetime import datetime
from datetime import time as time_format
import logging
# Enable logging
logging.basicConfig(format='[ %(asctime)s ] %(name)s : %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
Token = "<token>"
db_username = '<user_name>'
db_password = '<your_pass>'
db_host = '<host>'
db_port = <port>
db_database = '<database>'
class Bot:
"""
Bot() is a center class of API.
__init__()
__del__()
getConn()
getChatList()
getMailler()
getSearch()
send(contactList, message)
getRemoveList()
"""
__removeList = []
def __init__(self):
"""
initilize the Bot Class
"""
print("Initilizing... Bot")
#token form bot father
self.__bot = telegram.Bot(token=Token)
self.__db_chatlist = 'chatlist'
self.__db_mailler = 'automailer'
self.__db_search = 'search'
self.__conn = 0
def open(self):
"""
Open new connection
"""
print("Database Connecting...")
self.__conn = psycopg2.connect(database=db_database,
user= db_username,
password=db_password,
host=db_host,
port=db_port
)
def close(self):
"""
Close the connection
"""
print("Connection closed.")
self.__conn.close()
def __del__(self):
"""
Close the connection
"""
print("Connection closed.")
if self.__conn:
self.__conn.close()
def getConn(self):
"""
@return : __conn
"""
return self.__conn
def getBot(self):
"""
@return : __bot
"""
return self.__bot
def getChatList(self):
"""
@return : __db_chatlist
"""
return self.__db_chatlist
def getMailler(self):
"""
@return : __db_mailler
"""
return self.__db_mailler
def getSearch(self):
"""
@return :
"""
return self.__db_search
def send(self, contactList, message):
"""
send the message to multiple contact list
@return : True
"""
self.__removeList = []
for contact in contactList:
while True:
try:
self.__bot.send_message(chat_id=contact, text=message)
print ("Send : "+ str(contact))
break
except Exception as e:
print(e)
print ("Error : "+ str(contact))
self.__removeList.append(contact)
return True
def getRemoveList(self):
"""
@return : list of last failed SMS ID
"""
return self.__removeList
class User(Bot):
"""
--User Class
"""
def __init__(self):
Bot.__init__()
print("Initilizing... User")
def remove(self, user_id):
"""
id (string)
Remove user form SQL database
@return : True|False
"""
try:
self.open()
conn = self.getConn()
cur = conn.cursor()
cur.execute("DELETE FROM chatlist WHERE id = %s;", (user_id,))
self.getConn().commit()
cur.close()
self.close()
return True
except psycopg2.DatabaseError as e:
if conn:
conn.rollback()
print ('Error : %s' % e)
self.close()
return False
def getAllUser(self):
"""
All user from SQL Database
"""
try:
self.open()
conn = self.getConn()
cur = conn.cursor()
cur.execute("SELECT * FROM chatlist")
tmp_list = []
while True:
row = cur.fetchone()
if row == None:
break
tmp_list.append(row)
except psycopg2.DatabaseError as e:
if conn:
conn.rollback()
print ('Error %s' % e)
df = pd.DataFrame(tmp_list, columns=['id', 'first_name', 'username', 'active', 'start', 'end', 'type'])
self.getConn().commit()
cur.close()
self.close()
return df
def save(self, id_row, first_name, username, active, start, end, type_row):
"""
Insert in database
@return : True|False
"""
try:
self.open()
conn = self.getConn()
cur = conn.cursor()
cur.execute("INSERT INTO chatlist (id, first_name, username, active, start_date, end_date, type) VALUES (%s, %s, %s, %s, %s, %s, %s);", (id_row, first_name, username, active, start, end, type_row))
self.getConn().commit()
cur.close()
self.close()
return True
except psycopg2.DatabaseError as e:
if conn:
conn.rollback()
print ('Error : %s' % e)
self.close()
return False
class Chat(User):
"""
--Chat Class
"""
def __init__(self):
User.__init__()
print("Initilizing... Chat")
def getAllGroup(self):
"""
get all group list
@return : pandas.DataFrame
"""
df = self.getAllUser()
return df.loc[df['type'] == 'group']
def getAllPrivate(self):
"""
get all private prople
@return : pandas.DataFrame
"""
df = self.getAllUser()
return df.loc[df['type'] == 'private']
def getAllPrivateID(self):
"""
get all private pep ids
@return : pandas.DataFrame
"""
r = self.getAllPrivate()
return r['id']
def refresh(self):
"""
refresh the database
@return : True
"""
try:
ids =[]
updates = self.getBot().get_updates()
for details in updates:
if not details.message.chat.username:
details.message.chat.username = details.message.chat.title
self.save(details.message.chat_id, details.message.chat.first_name, details.message.chat.username, 'Y', details.message.date, 'No', details.message.chat.type)
return True
except Exception as e:
return False
class AutoMailer(User):
"""
--Automailer Class
Time Formet : DD/MM/YYYY, HH:MM:SS
Example : 12/06/2018, 16:18:30
"""
def __init__(self):
User.__init__()
print("Initilizing... AutoMailer")
def getAllMailler(self):
"""
return all mailling shedule in database
@return pandas.DataFrame
"""
try:
self.open()
conn = self.getConn()
cur = conn.cursor()
cur.execute("SELECT * FROM automailer")
tmp_list = []
while True:
row = cur.fetchone()
if row == None:
break
tmp_list.append(row)
except psycopg2.DatabaseError as e:
if conn:
conn.rollback()
print ('Error %s' % e)
df = pd.DataFrame(tmp_list, columns=['time', 'message'])
self.getConn().commit()
cur.close()
self.close()
return df
def newMailler(self, msgTime, message):
"""
Add new entry in mailling shedule
@return : True| False
"""
try:
self.open()
conn = self.getConn()
cur = conn.cursor()
cur.execute("INSERT INTO automailer (time, message) VALUES (%s, %s);", (msgTime, message))
self.getConn().commit()
cur.close()
self.close()
return True
except psycopg2.DatabaseError as e:
if conn:
conn.rollback()
print ('Error : %s' % e)
self.close()
return False
def deleteMailler(self, mail_time, message):
"""
Delete a entry in mailling shedule
@return : True| False
"""
try:
self.open()
conn = self.getConn()
cur = conn.cursor()
cur.execute("DELETE FROM automailer WHERE time = %s AND message = %s;", (mail_time, message))
self.getConn().commit()
cur.close()
self.close()
return True
except psycopg2.DatabaseError as e:
if conn:
conn.rollback()
print ('Error : %s' % e)
self.close()
return False
def run(self):
"""
Run a thread for sending automatic mail
start a thread __sheduler()
"""
thread = threading.Thread(target = self.__sheduler, args=[])
thread.start()
print("To take effect of edit in database, AutoMailer have to restart.")
def __sheduler(self):
"""
takes data form getAllMailler()
Run in a loop and match time and send mail accordingly
"""
mails = self.getAllMailler()
timeList = list(mails['time'])
message = list(mails['message'])
user_list = self.getAllUser()
user_list = user_list.loc[user_list['active'].isin(["Y"])]
user_list = list(user_list["id"])
while True:
cu_time = time.strftime("%d/%m/%Y, %H:%M:%S")
if cu_time in timeList:
idx = timeList.index(cu_time)
self.send(user_list, message[idx])
print("Send to : " + str(user_list))
time.sleep(1)
class Regestration(Chat):
"""
--Regestration Class
"""
def __init__(self):
Chat.__init__()
print("Initilizing... Regestration")
def run(self):
"""
Run a thread getReg() to refresh the user database
@obsulute
"""
thread = threading.Thread(target = self.getReg, args=[])
thread.start()
print("Regestration Thread is running")
def __getSerchbyKey(self, key):
"""
Search on SQL database and return the match
@return : pandas.DataFrame
"""
try:
self.open()
conn = self.getConn()
cur = conn.cursor()
cur.execute("SELECT * FROM search WHERE key = '"+key+"'")
tmp_list = []
while True:
row = cur.fetchone()
if row == None:
break
tmp_list.append(row)
except psycopg2.DatabaseError as e:
if conn:
conn.rollback()
print ('Error %s' % e)
df = pd.DataFrame(tmp_list, columns=['key','message','timeForm','timeTo'])
self.getConn().commit()
cur.close()
self.close()
return df
def deleteSearch(self, key, message):
"""
Delete search keyword
@return : True|False
"""
try:
self.open()
conn = self.getConn()
cur = conn.cursor()
cur.execute("DELETE FROM search WHERE key= %s AND message= %s;", (key, message))
self.getConn().commit()
cur.close()
self.close()
return True
except psycopg2.DatabaseError as e:
if conn:
conn.rollback()
print ('Error : %s' % e)
self.close()
return False
def insertSerch(self, key, message, timeForm, timrTo):
"""
Insert new entry in search
@return : True|False
"""
try:
self.open()
conn = self.getConn()
cur = conn.cursor()
cur.execute("INSERT INTO search (key, message, timeform , timeto) VALUES (%s, %s, %s, %s);", (key.lower(), message, timeForm, timrTo))
self.getConn().commit()
cur.close()
self.close()
return True
except psycopg2.DatabaseError as e:
if conn:
conn.rollback()
print ('Error : %s' % e)
self.close()
return False
def getReg(self):
"""
Refresh in every seconds
@obsulute
"""
while True:
try:
self.refresh()
except Exception as e:
pass
time.sleep(1)
def __in_between(self, now, start, end):
"""
check if time lies in between two time
@return : True|False
"""
if start <= end:
return start <= now < end
else: # over midnight e.g., 23:30-04:15
return start <= now or now < end
def polling(self):
"""
Run a polling method that do all operaion like __search, __help, __start
"""
updater = Updater(token=Token)
dp = updater.dispatcher
dp.add_handler(CommandHandler("start", self.__start))
dp.add_handler(CommandHandler("help", self.__help))
dp.add_handler(CommandHandler("search", self.__search, pass_args=True))
dp.add_handler(MessageHandler(Filters.text, self.__echo))
updater.start_polling()
updater.idle()
def __echo(self, bot, update):
"""
Echo for non CommandHandler sms
"""
if update.message.chat_id in self.getAllPrivate:
update.message.reply_text("Invalid")
def __help(self, bot, update):
"""
reply List of available command to command issuer
"""
update.message.reply_text('/start : New Regestration\n /help : list of all command\n/search: Search ')
def __search(self, bot, update, args):
"""
Send search result to command issuer
"""
try:
# read the search file
data = self.__getSerchbyKey(args[0].lower())
# print(data)
res = "Search Result : \n"
for index, row in data.iterrows():
form_h, form_m = row["timeForm"].split(":")
to_h, to_m = row["timeTo"].split(":")
if self.__in_between(datetime.now().time(), time_format(int(form_h),int(form_m)), time_format(int(to_h), int(to_m))):
res = res + '\n' +row["message"]
update.message.reply_text(res)
except Exception as e:
print(e)
update.message.reply_text('Please enter the text.')
def __start(self, bot, update):
"""
Send a message when the command /start is issued.
regester the user
"""
if not update.message.chat.username:
update.message.chat.username = update.message.chat.title
self.save(update.message.chat_id, update.message.chat.first_name, update.message.chat.username, 'Y', update.message.date, 'No', update.message.chat.type)
self.save(update.message.from_user.id, update.message.from_user.first_name, update.message.from_user.username, 'Y', update.message.date, 'No', 'private')
print(str(update.message.chat.username)+"( "+str(update.message.chat_id)+" ) Added..")
print(str(update.message.chat.username)+"( "+str(update.message.from_user.id)+" ) Added..")
update.message.reply_text('Regestration Success...\nType /help to get the list of all command')
ti = time.strftime("%d/%m/%Y, %H:%M:%S")
"""
b = Bot()
b.open()
b.close()
del b
"""
"""
u = User()
print(u.getAllUser())
u.save(1, "first_name", "user", "Y", "25-12", "No", "group")
u.remove('1')
"""
"""
c = Chat()
print(c.getAllPrivate())
print(c.getAllGroup())
print(c.getAllPrivateID())
c.refresh()
"""
"""
a = AutoMailer()
print(a.getAllMailler())
print(a.newMailler(ti, 'This is sample Text genrated by AutoMailer'))
print(a.deleteMailler(ti, 'This is sample Text genrated by AutoMailer'))
a.run()
"""
"""
r = Regestration()
r.run()
print(r.deleteSearch("key2", "This is key2."))
print(r.insertSerch("key2", "This is key2.", "12:30", "23:30"))
r.polling()
"""