-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtelebot.py
executable file
·307 lines (194 loc) · 8.75 KB
/
telebot.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
306
307
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import ConfigParser
import time
import sys
import os
import random
import string
reload(sys)
sys.setdefaultencoding('utf-8')
class api_req: # Класс для get/post из telegram api
def __init__(self, interval, admin_id, api_url, secret, offset, text, chat_id, chat_name):
self.interval = interval
self.admin_id = admin_id
self.api_url = api_url
self.secret = secret
self.offset = offset
self.text = text
self.chat_id = chat_id
self.chat_name = chat_name
def request_executor(self):
self.options = {'offset': self.offset + 1, 'limit': 5, 'timeout': 0}
try:
self.request = requests.get(self.api_url + self.secret + '/getUpdates', data=self.options)
except:
print('Error getting updates')
return False
if not self.request.status_code == 200:
return False
if not self.request.json()['ok']:
return False
if self.request.json()['result']:
return self.request.json()['result']
else:
return False
def post_executor(self):
log_event('Sending to %s: %s' % (self.chat_name, self.text), self.chat_name)
self.options = {'chat_id': self.chat_id, 'text': self.text}
self.request = requests.post(self.api_url + self.secret + '/sendMessage', self.options)
if not self.request.status_code == 200:
return False
return self.request.json()['ok']
def message_extraction(message_body): # Выковыриваем из ответа сообщение
if type(message_body) == str or int: # Иногда приезжает булевый тип данных, ломая итерацию. Избавляемся.
global offset
for update in message_body:
offset = update['update_id']
if not 'message' in update or not 'text' in update['message']:
log_event('Unknown update: %s' % (update), "error")
continue
from_id = update['message']['chat']['id']
chat_number = update['message']['chat']['id']
chat_type = update['message']['chat']['type']
if not 'first_name' in update['message']['from']: # Проверка наличия имени и фамилии пользователя, они не всегда бывают.
name = update['message']['from']['last_name']
print(name)
if not 'last_name' in update['message']['from']:
name = update['message']['from']['first_name']
else:
name = update['message']['from']['first_name'] + ' ' + update['message']['from']['last_name']
if chat_type == "group": # Определяем имя чата для последующей записи в лог.
chat_name = update['message']['chat']['title']
elif chat_type == "private":
chat_name = name
message = update['message']['text'] # Вытаскиваем текст сообщения.
log_event('Message from %s: %s' % (name, message), chat_name)
return (message, from_id, chat_name, chat_number) # Возвращаем сообщение и идентификаторы чата
def log_event(text, logname):
filename = 'chatlogs/'+logname+'_log.txt'
event = '%s >> %s' % (time.ctime(), text)
filework = open(filename, 'a+')
filework.write(event)
filework.write("\n")
filework.close()
def learner(message_text, chat_number):
chat_number = str(chat_number)
chat_number = chat_number.replace('+', '').replace('-', '')
message_text = message_text.replace('/learn', '').strip()
filework = open('dict/' + chat_number + '_words.dat', 'a')
filework.write(message_text)
filework.write("\n")
filework.close()
def longestSubstringFinder(string1, string2):
"""
string1 is for word in dictionary
string2 is for word in message
"""
answer = ""
len1, len2 = len(string1), len(string2)
for i in range(len1):
match = ""
for j in range(len2):
if (i + j < len1 and string1[i + j] == string2[j]):
match += string2[j]
else:
if (len(match) > len(answer)): answer = match
match = ""
return len(answer) >= 0.8 * len(string1)
def compare_words_lists(filelist, message):
"""
filelist is for words in file
message list is for message words
"""
matched = []
for f in filelist:
for w in message:
if longestSubstringFinder(f, w):
matched.append(f)
return matched
def messager_test(message_word,chat_name,chat_number):
message_word_command = message_word.split(" ")
if message_word_command[0] == '/help':
return "Telebot - Simple Telegram bot"
elif message_word_command[0] == '/stop':
return "Hui tebe!"
elif message_word_command[0] == '/start':
return "OK"
elif message_word_command[0] == '/learn':
learner(message_word, chat_number)
return "Записал!"
try:
chat_number = str(chat_number)
chat_number = chat_number.replace('+', '').replace('-', '')
words_file = open('dict/' + chat_number + '_words.dat', 'r')
except:
return False
message_word = message_word.encode('utf-8', 'ignore') # Извлекаем слово, убираем пунктуацию, переводим в нижний регистр и загоняем в список по пробелам
message_word_truncated = message_word.translate(string.maketrans("",""), string.punctuation).decode('utf-8').lower().split(" ")
string_with_words = []
if message_word_truncated[0] == '':
return False
for strings in words_file:
counter = 0
list_original = strings.split(" || ")
list_spl = strings.decode('utf-8').lower().split(" || ") # Получаем строку из файла, делим ее по разделителю и переводим в нижний регистр
list_spl_truncated = list_spl[:]
for elements in list_spl:
list_spl_truncated[counter] = list_spl[counter].encode('utf-8', 'ignore').translate(string.maketrans("", ""), string.punctuation).decode('utf-8') # Удаляем пунктуацию, получаем чистый список
counter += 1
list_diff = compare_words_lists(list_spl_truncated, message_word_truncated) # получаем точки пресечения списков
if list_diff:
string_with_words = string_with_words + list_original # Собираем значения, совпавшие со строками списков в один список.
if string_with_words:
rnd = random.randint(1, len(string_with_words)-1) # Из образовавшегося набора рандомно выбираем фразу или слово, как повезет.
words_file.close()
return string_with_words[rnd]
else:
return False
# Парсим конфигурацию
config = ConfigParser.RawConfigParser()
config.read('telebot.cfg')
try:
interval = config.getfloat('SectionBot', 'interval')
admin_id = config.getint('SectionBot', 'admin_id')
api_url = config.get('SectionBot', 'api_url')
secret = config.get('SectionBot', 'secret')
offset = config.getint('SectionBot', 'offset')
lock_file = 'tmp/telebot.lock'
text = 'Hello'
chat_id = 0
except:
print("Can't parse config file!")
exit(0)
if __name__ == "__main__":
if os.path.exists(lock_file):
print('Lock file exists!')
#exit(0)
else:
try:
open(lock_file, 'a+')
lock_file.close()
except:
exit(0)
while True:
try:
chat_name = 0
answ_data = False
message_data = False
test = api_req(interval, admin_id, api_url, secret, offset, text, chat_id, chat_name)
data_test = test.request_executor()
if data_test:
message_data = message_extraction(data_test)
if message_data:
message, from_id, chat_name, chat_number = message_data
answ = messager_test(message, chat_name, chat_number)
if answ:
runn = api_req(interval, admin_id, api_url, secret, offset, answ, from_id, chat_name)
runn.post_executor()
time.sleep(interval)
except KeyboardInterrupt:
print('Прервано пользователем..')
os.remove(lock_file)
break