forked from mail-ru-im/bot-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbot.py
More file actions
487 lines (411 loc) · 16 KB
/
Copy pathbot.py
File metadata and controls
487 lines (411 loc) · 16 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
import cgi
import logging
import os
import re
from signal import signal, SIGINT, SIGTERM, SIGABRT
from threading import Thread, Lock
from time import sleep
import requests
from cached_property import cached_property
from expiringdict import ExpiringDict
from requests import Request
from requests.adapters import HTTPAdapter
import bot
from bot.dispatcher import Dispatcher, StopDispatching
from bot.event import Event, EventType
from bot.filter import Filter
from bot.handler import MessageHandler
from bot.util import signal_name_by_code
try:
from urllib import parse as urlparse
except ImportError:
# noinspection PyUnresolvedReferences
import urlparse
class Bot(object):
def __init__(self, token, api_url_base=None, name=None, version=None, timeout_s=20, poll_time_s=60):
super(Bot, self).__init__()
self.log = logging.getLogger(__name__)
self.token = token
self.api_base_url = "https://api.icq.net/bot/v1" if api_url_base is None else api_url_base
self.name = name
self.version = version
self.timeout_s = timeout_s
self.poll_time_s = poll_time_s
self.last_event_id = 0
self.dispatcher = Dispatcher(self)
self.running = False
self._uin = token.split(":")[-1]
self.__lock = Lock()
self.__polling_thread = None
self.__sent_im_cache = ExpiringDict(max_len=2 ** 10, max_age_seconds=60)
self.dispatcher.add_handler(SkipDuplicateMessageHandler(self.__sent_im_cache))
@property
def uin(self):
return self._uin
@cached_property
def user_agent(self):
return "{name}/{version} (uin={uin}) bot-python/{library_version}".format(
name=self.name,
version=self.version,
uin="" if self.uin is None else self.uin,
library_version=bot.__version__
)
@cached_property
def http_session(self):
session = requests.Session()
for scheme in ("http://", "https://"):
session.mount(scheme, BotLoggingHTTPAdapter(bot=self))
return session
def _start_polling(self):
while self.running:
# Exceptions should not stop polling thread.
# noinspection PyBroadException
try:
response = self.events_get()
for event in response.json()["events"]:
self.dispatcher.dispatch(Event(type_=EventType(event["type"]), data=event["payload"]))
except Exception:
self.log.exception("Exception while polling!")
def start_polling(self):
with self.__lock:
if not self.running:
self.log.info("Starting polling.")
self.running = True
self.__polling_thread = Thread(target=self._start_polling)
self.__polling_thread.start()
def stop(self):
with self.__lock:
if self.running:
self.log.info("Stopping bot.")
self.running = False
self.__polling_thread.join()
# noinspection PyUnusedLocal
def _signal_handler(self, sig, stack_frame):
if self.running:
self.log.debug("Stopping bot by signal '{name} ({code})'. Repeat for force exit.".format(
name=signal_name_by_code(sig), code=sig
))
self.stop()
else:
self.log.warning("Force exiting.")
# It's fine here, this is standard way to force exit.
# noinspection PyProtectedMember
os._exit(1)
def idle(self):
for sig in (SIGINT, SIGTERM, SIGABRT):
signal(sig, self._signal_handler)
while self.running:
sleep(1)
def events_get(self, poll_time_s=None, last_event_id=None):
poll_time_s = self.poll_time_s if poll_time_s is None else poll_time_s
last_event_id = self.last_event_id if last_event_id is None else last_event_id
response = self.http_session.get(
url="{}/events/get".format(self.api_base_url),
params={
"token": self.token,
"pollTime": poll_time_s,
"lastEventId": last_event_id
},
timeout=poll_time_s + self.timeout_s
)
if response.json()['events']:
self.last_event_id = max(response.json()['events'], key=lambda e: e['eventId'])['eventId']
return response
def self_get(self):
return self.http_session.get(
url="{}/self/get".format(self.api_base_url),
params={
"token": self.token
},
timeout=self.timeout_s
)
def send_text(self, chat_id, text, reply_msg_id=None, forward_chat_id=None, forward_msg_id=None,
inline_keyboard_markup=None):
return self.http_session.get(
url="{}/messages/sendText".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"text": text,
"replyMsgId": reply_msg_id,
"forwardChatId": forward_chat_id,
"forwardMsgId": forward_msg_id,
"inlineKeyboardMarkup": inline_keyboard_markup
},
timeout=self.timeout_s
)
def send_file(self, chat_id, file_id=None, file=None, caption=None, reply_msg_id=None, forward_chat_id=None,
forward_msg_id=None, inline_keyboard_markup=None):
request = Request(
method="GET",
url="{}/messages/sendFile".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"fileId": file_id,
"caption": caption,
"replyMsgId": reply_msg_id,
"forwardChatId": forward_chat_id,
"forwardMsgId": forward_msg_id,
"inlineKeyboardMarkup": inline_keyboard_markup
}
)
if file:
request.method = "POST"
request.files = {"file": file}
return self.http_session.send(request.prepare(), timeout=self.timeout_s)
def send_voice(self, chat_id, file_id=None, file=None, reply_msg_id=None, forward_chat_id=None,
forward_msg_id=None, inline_keyboard_markup=None):
request = Request(
method="GET",
url="{}/messages/sendVoice".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"fileId": file_id,
"replyMsgId": reply_msg_id,
"forwardChatId": forward_chat_id,
"forwardMsgId": forward_msg_id,
"inlineKeyboardMarkup": inline_keyboard_markup
}
)
if file:
request.method = "POST"
request.files = {"file": file}
return self.http_session.send(request.prepare(), timeout=self.timeout_s)
def edit_text(self, chat_id, msg_id, text, inline_keyboard_markup=None):
return self.http_session.get(
url="{}/messages/editText".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"msgId": msg_id,
"text": text,
"inlineKeyboardMarkup": inline_keyboard_markup
},
timeout=self.timeout_s
)
def delete_messages(self, chat_id, msg_id):
return self.http_session.get(
url="{}/messages/deleteMessages".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"msgId": msg_id
},
timeout=self.timeout_s
)
def answer_callback_query(self, query_id, text, show_alert=False, url=None):
return self.http_session.get(
url="{}/messages/answerCallbackQuery".format(self.api_base_url),
params={
"token": self.token,
"queryId": query_id,
"text": text,
"showAlert": 'true' if show_alert else 'false',
"url": url
}
)
def send_actions(self, chat_id, actions):
return self.http_session.get(
url="{}/chats/sendActions".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"actions": actions if len(actions) else ''
},
timeout=self.timeout_s
)
def get_chat_info(self, chat_id):
return self.http_session.get(
url="{}/chats/getInfo".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id
},
timeout=self.timeout_s
)
def get_chat_admins(self, chat_id):
return self.http_session.get(
url="{}/chats/getAdmins".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id
},
timeout=self.timeout_s
)
def get_chat_members(self, chat_id, cursor=None):
return self.http_session.get(
url="{}/chats/getMembers".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"cursor": cursor
},
timeout=self.timeout_s
)
def get_chat_blocked_users(self, chat_id):
return self.http_session.get(
url="{}/chats/getBlockedUsers".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id
},
timeout=self.timeout_s
)
def get_chat_pending_users(self, chat_id):
return self.http_session.get(
url="{}/chats/getPendingUsers".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id
},
timeout=self.timeout_s
)
def chat_block_user(self, chat_id, user_id, del_last_messages=False):
return self.http_session.get(
url="{}/chats/blockUser".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"userId": user_id,
"delLastMessages": str(del_last_messages).lower()
},
timeout=self.timeout_s
)
def chat_unblock_user(self, chat_id, user_id):
return self.http_session.get(
url="{}/chats/unblockUser".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"userId": user_id
},
timeout=self.timeout_s
)
def chat_resolve_pending(self, chat_id, approve=True, user_id="", everyone=False):
return self.http_session.get(
url="{}/chats/resolvePending".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"approve": str(approve).lower(),
"userId": user_id,
"everyone": str(everyone).lower()
},
timeout=self.timeout_s
)
def set_chat_title(self, chat_id, title):
return self.http_session.get(
url="{}/chats/setTitle".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"title": title
},
timeout=self.timeout_s
)
def set_chat_about(self, chat_id, about):
return self.http_session.get(
url="{}/chats/setAbout".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"about": about
},
timeout=self.timeout_s
)
def set_chat_rules(self, chat_id, rules):
return self.http_session.get(
url="{}/chats/setRules".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"rules": rules
},
timeout=self.timeout_s
)
def get_file_info(self, file_id):
return self.http_session.get(
url="{}/files/getInfo".format(self.api_base_url),
params={
"token": self.token,
"fileId": file_id
},
timeout=self.timeout_s
)
def pin_message(self, chat_id, msg_id):
return self.http_session.get(
url="{}/chats/pinMessage".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"msgId": msg_id
},
timeout=self.timeout_s
)
def unpin_message(self, chat_id, msg_id):
return self.http_session.get(
url="{}/chats/unpinMessage".format(self.api_base_url),
params={
"token": self.token,
"chatId": chat_id,
"msgId": msg_id
},
timeout=self.timeout_s
)
class LoggingHTTPAdapter(HTTPAdapter):
_LOG_MIME_TYPE_REGEXP = re.compile(
r"^(?:text(?:/.+)?|application/(?:json|javascript|xml|x-www-form-urlencoded))$", re.IGNORECASE
)
@staticmethod
def _is_loggable(headers):
return LoggingHTTPAdapter._LOG_MIME_TYPE_REGEXP.search(cgi.parse_header(headers.get("Content-Type", ""))[0])
@staticmethod
def _headers_to_string(headers):
return "\n".join((u"{key}: {value}".format(key=key, value=value) for (key, value) in headers.items()))
@staticmethod
def _body_to_string(body):
return body.decode("utf-8") if isinstance(body, bytes) else body
def __init__(self, *args, **kwargs):
super(LoggingHTTPAdapter, self).__init__(*args, **kwargs)
self.log = logging.getLogger(__name__)
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug(u"{method} {url}\n{headers}{body}".format(
method=request.method,
url=request.url,
headers=LoggingHTTPAdapter._headers_to_string(request.headers),
body="\n\n" + (
LoggingHTTPAdapter._body_to_string(request.body) if
LoggingHTTPAdapter._is_loggable(request.headers) else "[binary data]"
) if request.body is not None else ""
))
response = super(LoggingHTTPAdapter, self).send(request, stream, timeout, verify, cert, proxies)
if self.log.isEnabledFor(logging.DEBUG):
self.log.debug(u"{status_code} {reason}\n{headers}{body}".format(
status_code=response.status_code,
reason=response.reason,
headers=LoggingHTTPAdapter._headers_to_string(response.headers),
body="\n\n" + (
response.text if LoggingHTTPAdapter._is_loggable(response.headers) else "[binary data]"
) if response.content is not None else ""
))
return response
class BotLoggingHTTPAdapter(LoggingHTTPAdapter):
def __init__(self, bot, *args, **kwargs):
super(BotLoggingHTTPAdapter, self).__init__(*args, **kwargs)
self.bot = bot
def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
request.headers["User-Agent"] = self.bot.user_agent
return super(BotLoggingHTTPAdapter, self).send(request, stream, timeout, verify, cert, proxies)
class FileNotFoundException(Exception):
pass
class SkipDuplicateMessageHandler(MessageHandler):
def __init__(self, cache):
super(SkipDuplicateMessageHandler, self).__init__(filters=Filter.message)
self.cache = cache
def check(self, event, dispatcher):
if super(SkipDuplicateMessageHandler, self).check(event=event, dispatcher=dispatcher):
if self.cache.get(event.data["msgId"]) == event.data["text"]:
raise StopDispatching