pyrobale 0.2.1__py3-none-any.whl → 0.2.3__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {pyrobale-0.2.1.dist-info → pyrobale-0.2.3.dist-info}/METADATA +39 -29
- pyrobale-0.2.3.dist-info/RECORD +5 -0
- {pyrobale-0.2.1.dist-info → pyrobale-0.2.3.dist-info}/licenses/LICENSE +678 -674
- pyrobale.py +1394 -1422
- pyrobale-0.2.1.dist-info/RECORD +0 -5
- {pyrobale-0.2.1.dist-info → pyrobale-0.2.3.dist-info}/WHEEL +0 -0
pyrobale.py
CHANGED
@@ -1,1422 +1,1394 @@
|
|
1
|
-
import requests, json, time, threading
|
2
|
-
from typing import Optional, Dict, Any, List, Union
|
3
|
-
import traceback
|
4
|
-
import sqlite3
|
5
|
-
import inspect
|
6
|
-
import asyncio
|
7
|
-
|
8
|
-
__version__ = '0.2.
|
9
|
-
|
10
|
-
class DataBase:
|
11
|
-
def __init__(self, name):
|
12
|
-
self.name = name
|
13
|
-
self.conn = None
|
14
|
-
self.cursor = None
|
15
|
-
self._initialize_db()
|
16
|
-
|
17
|
-
def _initialize_db(self):
|
18
|
-
self.conn = sqlite3.connect(self.name)
|
19
|
-
self.cursor = self.conn.cursor()
|
20
|
-
self.cursor.execute('''CREATE TABLE IF NOT EXISTS key_value_store
|
21
|
-
(key TEXT PRIMARY KEY, value TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
22
|
-
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
|
23
|
-
self.conn.commit()
|
24
|
-
|
25
|
-
def __enter__(self):
|
26
|
-
return self
|
27
|
-
|
28
|
-
def __exit__(self, exc_type, exc_val, exc_tb):
|
29
|
-
self.close()
|
30
|
-
|
31
|
-
def close(self):
|
32
|
-
if self.conn:
|
33
|
-
self.conn.close()
|
34
|
-
self.conn = None
|
35
|
-
self.cursor = None
|
36
|
-
|
37
|
-
def read_database(self, include_timestamps=False):
|
38
|
-
if not self.conn:
|
39
|
-
self._initialize_db()
|
40
|
-
if include_timestamps:
|
41
|
-
self.cursor.execute("SELECT key, value, created_at, updated_at FROM key_value_store")
|
42
|
-
rows = self.cursor.fetchall()
|
43
|
-
return {key: {'value': json.loads(value), 'created_at': created, 'updated_at': updated}
|
44
|
-
for key, value, created, updated in rows}
|
45
|
-
else:
|
46
|
-
self.cursor.execute("SELECT key, value FROM key_value_store")
|
47
|
-
rows = self.cursor.fetchall()
|
48
|
-
return {key: json.loads(value) for key, value in rows}
|
49
|
-
|
50
|
-
def write_database(self, data_dict):
|
51
|
-
if not self.conn:
|
52
|
-
self._initialize_db()
|
53
|
-
for key, value in data_dict.items():
|
54
|
-
self.cursor.execute("""
|
55
|
-
INSERT INTO key_value_store (key, value, updated_at)
|
56
|
-
VALUES (?, ?, CURRENT_TIMESTAMP)
|
57
|
-
ON CONFLICT(key) DO UPDATE SET
|
58
|
-
value=excluded.value, updated_at=CURRENT_TIMESTAMP""",
|
59
|
-
(key, json.dumps(value, default=str)))
|
60
|
-
self.conn.commit()
|
61
|
-
|
62
|
-
def read_key(self, key: str, default=None):
|
63
|
-
if not self.conn:
|
64
|
-
self._initialize_db()
|
65
|
-
self.cursor.execute("SELECT value FROM key_value_store WHERE key = ?", (key,))
|
66
|
-
result = self.cursor.fetchone()
|
67
|
-
return json.loads(result[0]) if result else default
|
68
|
-
|
69
|
-
def write_key(self, key: str, value):
|
70
|
-
if not self.conn:
|
71
|
-
self._initialize_db()
|
72
|
-
self.cursor.execute("""
|
73
|
-
INSERT INTO key_value_store (key, value, updated_at)
|
74
|
-
VALUES (?, ?, CURRENT_TIMESTAMP)
|
75
|
-
ON CONFLICT(key) DO UPDATE SET
|
76
|
-
value=excluded.value, updated_at=CURRENT_TIMESTAMP""",
|
77
|
-
(key, json.dumps(value, default=str)))
|
78
|
-
self.conn.commit()
|
79
|
-
|
80
|
-
def delete_key(self, key: str):
|
81
|
-
if not self.conn:
|
82
|
-
self._initialize_db()
|
83
|
-
self.cursor.execute("DELETE FROM key_value_store WHERE key = ?", (key,))
|
84
|
-
self.conn.commit()
|
85
|
-
|
86
|
-
def keys(self):
|
87
|
-
if not self.conn:
|
88
|
-
self._initialize_db()
|
89
|
-
self.cursor.execute("SELECT key FROM key_value_store")
|
90
|
-
return [row[0] for row in self.cursor.fetchall()]
|
91
|
-
|
92
|
-
def clear(self):
|
93
|
-
if not self.conn:
|
94
|
-
self._initialize_db()
|
95
|
-
self.cursor.execute("DELETE FROM key_value_store")
|
96
|
-
self.conn.commit()
|
97
|
-
|
98
|
-
def get_metadata(self, key: str):
|
99
|
-
if not self.conn:
|
100
|
-
self._initialize_db()
|
101
|
-
self.cursor.execute("""
|
102
|
-
SELECT created_at, updated_at
|
103
|
-
FROM key_value_store
|
104
|
-
WHERE key = ?""", (key,))
|
105
|
-
result = self.cursor.fetchone()
|
106
|
-
return {'created_at': result[0], 'updated_at': result[1]} if result else None
|
107
|
-
|
108
|
-
def exists(self, key: str) -> bool:
|
109
|
-
if not self.conn:
|
110
|
-
self._initialize_db()
|
111
|
-
self.cursor.execute("SELECT 1 FROM key_value_store WHERE key = ?", (key,))
|
112
|
-
return bool(self.cursor.fetchone())
|
113
|
-
|
114
|
-
|
115
|
-
class ChatMember:
|
116
|
-
def __init__(self, client: 'Client', data: Dict[str, Any]):
|
117
|
-
if data:
|
118
|
-
self.status = data.get('status')
|
119
|
-
self.user = User(client, {'ok': True, 'result': data.get('user', {})})
|
120
|
-
self.is_anonymous = data.get('is_anonymous')
|
121
|
-
self.can_be_edited = data.get('can_be_edited')
|
122
|
-
self.can_manage_chat = data.get('can_manage_chat')
|
123
|
-
self.can_delete_messages = data.get('can_delete_messages')
|
124
|
-
self.can_manage_video_chats = data.get('can_manage_video_chats')
|
125
|
-
self.can_restrict_members = data.get('can_restrict_members')
|
126
|
-
self.can_promote_members = data.get('can_promote_members')
|
127
|
-
self.can_change_info = data.get('can_change_info')
|
128
|
-
self.can_invite_users = data.get('can_invite_users')
|
129
|
-
self.can_pin_messages = data.get('can_pin_messages')
|
130
|
-
self.can_manage_topics = data.get('can_manage_topics')
|
131
|
-
self.is_creator = data.get('status') == 'creator'
|
132
|
-
class BaleException(Exception):
|
133
|
-
"""Base exception for Bale API errors"""
|
134
|
-
def __init__(self, *args):
|
135
|
-
super().__init__(*args)
|
136
|
-
print(traceback.format_exc())
|
137
|
-
|
138
|
-
class LabeledPrice:
|
139
|
-
def __init__(self, label: str, amount: int):
|
140
|
-
self.label = label
|
141
|
-
self.amount = amount
|
142
|
-
self.json = {
|
143
|
-
"label": self.label,
|
144
|
-
"amount": self.amount
|
145
|
-
}
|
146
|
-
|
147
|
-
class Document:
|
148
|
-
def __init__(self, data: dict):
|
149
|
-
if data:
|
150
|
-
self.file_id = data.get('file_id')
|
151
|
-
self.file_unique_id = data.get('file_unique_id')
|
152
|
-
self.file_name = data.get('file_name')
|
153
|
-
self.mime_type = data.get('mime_type')
|
154
|
-
self.file_size = data.get('file_size')
|
155
|
-
else:
|
156
|
-
self.file_id = None
|
157
|
-
self.file_unique_id = None
|
158
|
-
self.file_name = None
|
159
|
-
self.mime_type = None
|
160
|
-
self.file_size = None
|
161
|
-
|
162
|
-
class Invoice:
|
163
|
-
def __init__(self, data: dict):
|
164
|
-
if data:
|
165
|
-
self.title = data.get('title')
|
166
|
-
self.description = data.get('description')
|
167
|
-
self.start_parameter = data.get('start_parameter')
|
168
|
-
self.currency = data.get('currency')
|
169
|
-
self.total_amount = data.get('total_amount')
|
170
|
-
else:
|
171
|
-
self.title = None
|
172
|
-
self.description = None
|
173
|
-
self.start_parameter = None
|
174
|
-
self.currency = None
|
175
|
-
self.total_amount = None
|
176
|
-
|
177
|
-
class Photo:
|
178
|
-
def __init__(self,data):
|
179
|
-
if data:
|
180
|
-
self.file_id = data.get('file_id')
|
181
|
-
self.file_unique_id = data.get('file_unique_id')
|
182
|
-
self.width = data.get('width')
|
183
|
-
self.height = data.get('height')
|
184
|
-
self.file_size = data.get('file_size')
|
185
|
-
else:
|
186
|
-
self.file_id = None
|
187
|
-
self.file_unique_id = None
|
188
|
-
self.width = None
|
189
|
-
self.height = None
|
190
|
-
self.file_size = None
|
191
|
-
|
192
|
-
class Voice:
|
193
|
-
def __init__(self, data: dict):
|
194
|
-
if data:
|
195
|
-
self.file_id = data.get('file_id')
|
196
|
-
self.file_unique_id = data.get('file_unique_id')
|
197
|
-
self.duration = data.get('duration')
|
198
|
-
self.mime_type = data.get('mime_type')
|
199
|
-
self.file_size = data.get('file_size')
|
200
|
-
else:
|
201
|
-
self.file_id = None
|
202
|
-
self.file_unique_id = None
|
203
|
-
self.duration = None
|
204
|
-
self.mime_type = None
|
205
|
-
self.file_size = None
|
206
|
-
|
207
|
-
class Location:
|
208
|
-
def __init__(self,data: dict):
|
209
|
-
if data:
|
210
|
-
self.long = self.longitude = data.get('longitude')
|
211
|
-
self.lat = self.latitude = data.get('latitude')
|
212
|
-
else:
|
213
|
-
self.longitude = self.long = None
|
214
|
-
self.latitude = self.lat = None
|
215
|
-
|
216
|
-
class Contact:
|
217
|
-
def __init__(self, data: dict):
|
218
|
-
if data:
|
219
|
-
self.phone_number = data.get('phone_number')
|
220
|
-
self.first_name = data.get('first_name')
|
221
|
-
self.last_name = data.get('last_name')
|
222
|
-
self.user_id = data.get('user_id')
|
223
|
-
else:
|
224
|
-
self.phone_number = None
|
225
|
-
self.first_name = None
|
226
|
-
self.last_name = None
|
227
|
-
self.user_id = None
|
228
|
-
|
229
|
-
class MenuKeyboardButton:
|
230
|
-
def __init__(self, text: str, request_contact: bool = False, request_location: bool = False):
|
231
|
-
if not text:
|
232
|
-
raise ValueError("Text cannot be empty")
|
233
|
-
if request_contact and request_location:
|
234
|
-
raise ValueError("Cannot request both contact and location")
|
235
|
-
|
236
|
-
self.button = {"text": text}
|
237
|
-
if request_contact:
|
238
|
-
self.button["request_contact"] = True
|
239
|
-
if request_location:
|
240
|
-
self.button["request_location"] = True
|
241
|
-
|
242
|
-
class InlineKeyboardButton:
|
243
|
-
def __init__(self, text: str, callback_data: Optional[str] = None, url: Optional[str] = None, web_app: Optional[str] = None):
|
244
|
-
self.button = {"text": text}
|
245
|
-
if sum(bool(x) for x in [callback_data, url, web_app]) != 1:
|
246
|
-
raise ValueError("Exactly one of callback_data, url, or web_app must be provided")
|
247
|
-
if callback_data:
|
248
|
-
self.button["callback_data"] = callback_data
|
249
|
-
elif url:
|
250
|
-
self.button["url"] = url
|
251
|
-
elif web_app:
|
252
|
-
self.button["web_app"] = {"url": web_app}
|
253
|
-
|
254
|
-
class MenuKeyboardMarkup:
|
255
|
-
def __init__(self):
|
256
|
-
self.menu_keyboard = []
|
257
|
-
|
258
|
-
def add(self, button: MenuKeyboardButton, row: int = 0) -> 'MenuKeyboardMarkup':
|
259
|
-
if row < 0:
|
260
|
-
raise ValueError("Row index cannot be negative")
|
261
|
-
while len(self.menu_keyboard) <= row:
|
262
|
-
self.menu_keyboard.append([])
|
263
|
-
self.menu_keyboard[row].append(button.button)
|
264
|
-
self.cleanup_empty_rows()
|
265
|
-
return self
|
266
|
-
|
267
|
-
def cleanup_empty_rows(self) -> None:
|
268
|
-
self.menu_keyboard = [row for row in self.menu_keyboard if row]
|
269
|
-
|
270
|
-
def clear(self) -> None:
|
271
|
-
self.menu_keyboard = []
|
272
|
-
|
273
|
-
def remove_button(self, text: str) -> bool:
|
274
|
-
found = False
|
275
|
-
for row in self.menu_keyboard:
|
276
|
-
for button in row[:]:
|
277
|
-
if button.get('text') == text:
|
278
|
-
row.remove(button)
|
279
|
-
found = True
|
280
|
-
self.cleanup_empty_rows()
|
281
|
-
return found
|
282
|
-
|
283
|
-
@property
|
284
|
-
def keyboard(self):
|
285
|
-
return {"keyboard": self.menu_keyboard}
|
286
|
-
|
287
|
-
class InlineKeyboardMarkup:
|
288
|
-
def __init__(self):
|
289
|
-
self.inline_keyboard = []
|
290
|
-
|
291
|
-
def add(self, button: InlineKeyboardButton, row: int = 0) -> 'InlineKeyboardMarkup':
|
292
|
-
if row < 0:
|
293
|
-
raise ValueError("Row index cannot be negative")
|
294
|
-
while len(self.inline_keyboard) <= row:
|
295
|
-
self.inline_keyboard.append([])
|
296
|
-
self.inline_keyboard[row].append(button.button)
|
297
|
-
self.cleanup_empty_rows()
|
298
|
-
return self
|
299
|
-
|
300
|
-
def cleanup_empty_rows(self) -> None:
|
301
|
-
self.inline_keyboard = [row for row in self.inline_keyboard if row]
|
302
|
-
|
303
|
-
def clear(self) -> None:
|
304
|
-
self.inline_keyboard = []
|
305
|
-
|
306
|
-
def remove_button(self, text: str) -> bool:
|
307
|
-
found = False
|
308
|
-
for row in self.inline_keyboard:
|
309
|
-
for button in row[:]:
|
310
|
-
if button.get('text') == text:
|
311
|
-
row.remove(button)
|
312
|
-
found = True
|
313
|
-
self.cleanup_empty_rows()
|
314
|
-
return found
|
315
|
-
|
316
|
-
@property
|
317
|
-
def keyboard(self) -> dict:
|
318
|
-
return {"inline_keyboard": self.inline_keyboard}
|
319
|
-
class InputFile:
|
320
|
-
"""Represents a file to be uploaded"""
|
321
|
-
def __init__(self, client: 'Client', file: Union[str, bytes], filename: Optional[str] = None):
|
322
|
-
self.client = client
|
323
|
-
self.filename = filename
|
324
|
-
if isinstance(file, str):
|
325
|
-
if file.startswith(('http://', 'https://')):
|
326
|
-
r = requests.get(file)
|
327
|
-
r.raise_for_status()
|
328
|
-
self.file = r.content
|
329
|
-
else:
|
330
|
-
try:
|
331
|
-
self.file = open(file, 'rb')
|
332
|
-
except IOError as e:
|
333
|
-
raise BaleException(f"Failed to open file: {traceback.format_exc()}")
|
334
|
-
else:
|
335
|
-
self.file = file
|
336
|
-
|
337
|
-
def __del__(self):
|
338
|
-
if hasattr(self, 'file') and hasattr(self.file, 'close'):
|
339
|
-
self.file.close()
|
340
|
-
|
341
|
-
@property
|
342
|
-
def to_bytes(self):
|
343
|
-
if hasattr(self.file, 'read'):
|
344
|
-
return self.file.read()
|
345
|
-
return self.file
|
346
|
-
|
347
|
-
class CallbackQuery:
|
348
|
-
"""Represents a callback query from a callback button"""
|
349
|
-
def __init__(self, client: 'Client', data: Dict[str, Any]):
|
350
|
-
if not data.get('ok'):
|
351
|
-
raise BaleException(f"API request failed: {traceback.format_exc()}")
|
352
|
-
self.client = client
|
353
|
-
result = data.get('result', {})
|
354
|
-
self.id = result.get('id')
|
355
|
-
self.from_user = User(client, {'ok': True, 'result': result.get('from', {})})
|
356
|
-
self.message = Message(client, {'ok': True, 'result': result.get('message', {})})
|
357
|
-
self.inline_message_id = result.get('inline_message_id')
|
358
|
-
self.chat_instance = result.get('chat_instance')
|
359
|
-
self.data = result.get('data')
|
360
|
-
|
361
|
-
|
362
|
-
|
363
|
-
|
364
|
-
|
365
|
-
|
366
|
-
|
367
|
-
|
368
|
-
|
369
|
-
|
370
|
-
|
371
|
-
|
372
|
-
|
373
|
-
self.
|
374
|
-
|
375
|
-
self.
|
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
|
-
return self.client.
|
413
|
-
|
414
|
-
def
|
415
|
-
|
416
|
-
|
417
|
-
|
418
|
-
|
419
|
-
|
420
|
-
|
421
|
-
|
422
|
-
|
423
|
-
|
424
|
-
|
425
|
-
|
426
|
-
|
427
|
-
|
428
|
-
"""Send
|
429
|
-
return self.client.
|
430
|
-
|
431
|
-
def
|
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
|
-
|
627
|
-
|
628
|
-
|
629
|
-
|
630
|
-
|
631
|
-
|
632
|
-
|
633
|
-
|
634
|
-
|
635
|
-
|
636
|
-
|
637
|
-
|
638
|
-
|
639
|
-
|
640
|
-
self.
|
641
|
-
|
642
|
-
|
643
|
-
|
644
|
-
|
645
|
-
self.
|
646
|
-
|
647
|
-
|
648
|
-
|
649
|
-
|
650
|
-
|
651
|
-
|
652
|
-
|
653
|
-
|
654
|
-
|
655
|
-
|
656
|
-
|
657
|
-
|
658
|
-
|
659
|
-
|
660
|
-
|
661
|
-
|
662
|
-
|
663
|
-
|
664
|
-
|
665
|
-
"""Send a
|
666
|
-
return self.client.
|
667
|
-
|
668
|
-
def
|
669
|
-
|
670
|
-
|
671
|
-
|
672
|
-
|
673
|
-
|
674
|
-
|
675
|
-
|
676
|
-
|
677
|
-
|
678
|
-
|
679
|
-
|
680
|
-
"""
|
681
|
-
self.client.
|
682
|
-
|
683
|
-
def
|
684
|
-
|
685
|
-
|
686
|
-
|
687
|
-
"""Send
|
688
|
-
self.client.
|
689
|
-
|
690
|
-
def
|
691
|
-
|
692
|
-
|
693
|
-
|
694
|
-
"""Send a
|
695
|
-
self.client.
|
696
|
-
|
697
|
-
def
|
698
|
-
|
699
|
-
|
700
|
-
|
701
|
-
"""Send
|
702
|
-
|
703
|
-
|
704
|
-
def
|
705
|
-
|
706
|
-
|
707
|
-
|
708
|
-
|
709
|
-
|
710
|
-
|
711
|
-
def
|
712
|
-
|
713
|
-
|
714
|
-
|
715
|
-
|
716
|
-
|
717
|
-
|
718
|
-
def
|
719
|
-
|
720
|
-
|
721
|
-
|
722
|
-
|
723
|
-
|
724
|
-
|
725
|
-
|
726
|
-
|
727
|
-
|
728
|
-
|
729
|
-
|
730
|
-
|
731
|
-
|
732
|
-
|
733
|
-
|
734
|
-
|
735
|
-
self.client
|
736
|
-
|
737
|
-
|
738
|
-
|
739
|
-
|
740
|
-
|
741
|
-
|
742
|
-
self.
|
743
|
-
self.
|
744
|
-
|
745
|
-
|
746
|
-
self.
|
747
|
-
self.
|
748
|
-
self.
|
749
|
-
self.
|
750
|
-
self.
|
751
|
-
self.
|
752
|
-
self.
|
753
|
-
self.
|
754
|
-
self.
|
755
|
-
self.
|
756
|
-
|
757
|
-
|
758
|
-
|
759
|
-
|
760
|
-
|
761
|
-
|
762
|
-
|
763
|
-
|
764
|
-
|
765
|
-
|
766
|
-
|
767
|
-
|
768
|
-
|
769
|
-
|
770
|
-
|
771
|
-
|
772
|
-
|
773
|
-
|
774
|
-
|
775
|
-
|
776
|
-
|
777
|
-
|
778
|
-
|
779
|
-
|
780
|
-
|
781
|
-
|
782
|
-
|
783
|
-
|
784
|
-
|
785
|
-
|
786
|
-
|
787
|
-
|
788
|
-
|
789
|
-
|
790
|
-
|
791
|
-
|
792
|
-
|
793
|
-
|
794
|
-
|
795
|
-
|
796
|
-
|
797
|
-
|
798
|
-
|
799
|
-
|
800
|
-
|
801
|
-
|
802
|
-
|
803
|
-
|
804
|
-
|
805
|
-
|
806
|
-
|
807
|
-
|
808
|
-
|
809
|
-
|
810
|
-
|
811
|
-
|
812
|
-
|
813
|
-
|
814
|
-
|
815
|
-
|
816
|
-
|
817
|
-
|
818
|
-
|
819
|
-
|
820
|
-
|
821
|
-
|
822
|
-
|
823
|
-
|
824
|
-
|
825
|
-
|
826
|
-
|
827
|
-
|
828
|
-
|
829
|
-
|
830
|
-
def
|
831
|
-
|
832
|
-
|
833
|
-
|
834
|
-
|
835
|
-
def
|
836
|
-
|
837
|
-
|
838
|
-
|
839
|
-
|
840
|
-
self.
|
841
|
-
|
842
|
-
|
843
|
-
|
844
|
-
|
845
|
-
|
846
|
-
|
847
|
-
|
848
|
-
|
849
|
-
self.
|
850
|
-
|
851
|
-
|
852
|
-
|
853
|
-
|
854
|
-
|
855
|
-
|
856
|
-
|
857
|
-
|
858
|
-
|
859
|
-
|
860
|
-
|
861
|
-
|
862
|
-
|
863
|
-
|
864
|
-
|
865
|
-
|
866
|
-
|
867
|
-
|
868
|
-
|
869
|
-
|
870
|
-
|
871
|
-
|
872
|
-
|
873
|
-
|
874
|
-
|
875
|
-
|
876
|
-
|
877
|
-
|
878
|
-
|
879
|
-
|
880
|
-
|
881
|
-
|
882
|
-
|
883
|
-
|
884
|
-
|
885
|
-
|
886
|
-
|
887
|
-
|
888
|
-
|
889
|
-
|
890
|
-
|
891
|
-
|
892
|
-
|
893
|
-
return
|
894
|
-
|
895
|
-
|
896
|
-
|
897
|
-
|
898
|
-
|
899
|
-
|
900
|
-
|
901
|
-
|
902
|
-
|
903
|
-
|
904
|
-
|
905
|
-
|
906
|
-
|
907
|
-
|
908
|
-
|
909
|
-
|
910
|
-
|
911
|
-
|
912
|
-
|
913
|
-
|
914
|
-
|
915
|
-
|
916
|
-
|
917
|
-
|
918
|
-
|
919
|
-
|
920
|
-
'
|
921
|
-
'
|
922
|
-
|
923
|
-
|
924
|
-
return
|
925
|
-
|
926
|
-
def
|
927
|
-
|
928
|
-
|
929
|
-
|
930
|
-
|
931
|
-
|
932
|
-
|
933
|
-
|
934
|
-
|
935
|
-
|
936
|
-
|
937
|
-
|
938
|
-
|
939
|
-
|
940
|
-
|
941
|
-
|
942
|
-
|
943
|
-
|
944
|
-
|
945
|
-
|
946
|
-
|
947
|
-
|
948
|
-
|
949
|
-
|
950
|
-
|
951
|
-
|
952
|
-
|
953
|
-
|
954
|
-
|
955
|
-
|
956
|
-
|
957
|
-
|
958
|
-
|
959
|
-
|
960
|
-
|
961
|
-
|
962
|
-
|
963
|
-
|
964
|
-
|
965
|
-
|
966
|
-
|
967
|
-
|
968
|
-
|
969
|
-
|
970
|
-
|
971
|
-
|
972
|
-
|
973
|
-
|
974
|
-
|
975
|
-
|
976
|
-
|
977
|
-
|
978
|
-
|
979
|
-
|
980
|
-
|
981
|
-
|
982
|
-
|
983
|
-
|
984
|
-
|
985
|
-
|
986
|
-
|
987
|
-
|
988
|
-
|
989
|
-
'
|
990
|
-
|
991
|
-
|
992
|
-
|
993
|
-
|
994
|
-
|
995
|
-
|
996
|
-
|
997
|
-
|
998
|
-
|
999
|
-
|
1000
|
-
|
1001
|
-
|
1002
|
-
|
1003
|
-
|
1004
|
-
|
1005
|
-
|
1006
|
-
|
1007
|
-
|
1008
|
-
|
1009
|
-
|
1010
|
-
|
1011
|
-
|
1012
|
-
|
1013
|
-
|
1014
|
-
|
1015
|
-
|
1016
|
-
|
1017
|
-
|
1018
|
-
|
1019
|
-
|
1020
|
-
|
1021
|
-
|
1022
|
-
|
1023
|
-
|
1024
|
-
|
1025
|
-
data = {
|
1026
|
-
|
1027
|
-
|
1028
|
-
|
1029
|
-
|
1030
|
-
|
1031
|
-
|
1032
|
-
|
1033
|
-
|
1034
|
-
|
1035
|
-
|
1036
|
-
|
1037
|
-
|
1038
|
-
|
1039
|
-
|
1040
|
-
|
1041
|
-
|
1042
|
-
|
1043
|
-
|
1044
|
-
|
1045
|
-
|
1046
|
-
|
1047
|
-
data =
|
1048
|
-
|
1049
|
-
|
1050
|
-
|
1051
|
-
|
1052
|
-
|
1053
|
-
|
1054
|
-
|
1055
|
-
|
1056
|
-
|
1057
|
-
|
1058
|
-
|
1059
|
-
|
1060
|
-
|
1061
|
-
|
1062
|
-
|
1063
|
-
|
1064
|
-
|
1065
|
-
|
1066
|
-
|
1067
|
-
|
1068
|
-
|
1069
|
-
|
1070
|
-
|
1071
|
-
|
1072
|
-
|
1073
|
-
|
1074
|
-
|
1075
|
-
|
1076
|
-
|
1077
|
-
|
1078
|
-
|
1079
|
-
|
1080
|
-
|
1081
|
-
|
1082
|
-
|
1083
|
-
|
1084
|
-
|
1085
|
-
|
1086
|
-
|
1087
|
-
|
1088
|
-
|
1089
|
-
|
1090
|
-
|
1091
|
-
|
1092
|
-
|
1093
|
-
data =
|
1094
|
-
|
1095
|
-
|
1096
|
-
|
1097
|
-
|
1098
|
-
|
1099
|
-
|
1100
|
-
|
1101
|
-
|
1102
|
-
|
1103
|
-
|
1104
|
-
|
1105
|
-
|
1106
|
-
|
1107
|
-
|
1108
|
-
|
1109
|
-
|
1110
|
-
|
1111
|
-
|
1112
|
-
|
1113
|
-
|
1114
|
-
|
1115
|
-
|
1116
|
-
data =
|
1117
|
-
|
1118
|
-
|
1119
|
-
|
1120
|
-
|
1121
|
-
|
1122
|
-
|
1123
|
-
|
1124
|
-
|
1125
|
-
|
1126
|
-
|
1127
|
-
|
1128
|
-
|
1129
|
-
|
1130
|
-
|
1131
|
-
|
1132
|
-
|
1133
|
-
|
1134
|
-
|
1135
|
-
|
1136
|
-
|
1137
|
-
'
|
1138
|
-
|
1139
|
-
|
1140
|
-
|
1141
|
-
|
1142
|
-
|
1143
|
-
|
1144
|
-
|
1145
|
-
|
1146
|
-
|
1147
|
-
|
1148
|
-
|
1149
|
-
|
1150
|
-
|
1151
|
-
|
1152
|
-
|
1153
|
-
|
1154
|
-
|
1155
|
-
|
1156
|
-
|
1157
|
-
|
1158
|
-
|
1159
|
-
|
1160
|
-
|
1161
|
-
|
1162
|
-
|
1163
|
-
|
1164
|
-
|
1165
|
-
|
1166
|
-
|
1167
|
-
|
1168
|
-
|
1169
|
-
|
1170
|
-
|
1171
|
-
|
1172
|
-
|
1173
|
-
|
1174
|
-
|
1175
|
-
|
1176
|
-
|
1177
|
-
|
1178
|
-
|
1179
|
-
|
1180
|
-
|
1181
|
-
|
1182
|
-
|
1183
|
-
'
|
1184
|
-
|
1185
|
-
|
1186
|
-
|
1187
|
-
|
1188
|
-
|
1189
|
-
|
1190
|
-
|
1191
|
-
|
1192
|
-
|
1193
|
-
|
1194
|
-
|
1195
|
-
|
1196
|
-
|
1197
|
-
|
1198
|
-
'
|
1199
|
-
'
|
1200
|
-
'
|
1201
|
-
|
1202
|
-
|
1203
|
-
|
1204
|
-
|
1205
|
-
|
1206
|
-
|
1207
|
-
|
1208
|
-
|
1209
|
-
|
1210
|
-
|
1211
|
-
|
1212
|
-
|
1213
|
-
|
1214
|
-
|
1215
|
-
|
1216
|
-
|
1217
|
-
|
1218
|
-
|
1219
|
-
|
1220
|
-
|
1221
|
-
|
1222
|
-
|
1223
|
-
|
1224
|
-
|
1225
|
-
|
1226
|
-
|
1227
|
-
|
1228
|
-
|
1229
|
-
|
1230
|
-
|
1231
|
-
|
1232
|
-
|
1233
|
-
|
1234
|
-
|
1235
|
-
|
1236
|
-
|
1237
|
-
|
1238
|
-
def
|
1239
|
-
|
1240
|
-
|
1241
|
-
|
1242
|
-
|
1243
|
-
|
1244
|
-
|
1245
|
-
|
1246
|
-
|
1247
|
-
|
1248
|
-
def
|
1249
|
-
"""Decorator for handling
|
1250
|
-
|
1251
|
-
|
1252
|
-
|
1253
|
-
|
1254
|
-
|
1255
|
-
|
1256
|
-
|
1257
|
-
|
1258
|
-
|
1259
|
-
|
1260
|
-
|
1261
|
-
|
1262
|
-
|
1263
|
-
|
1264
|
-
|
1265
|
-
return
|
1266
|
-
|
1267
|
-
def
|
1268
|
-
"""Decorator for handling
|
1269
|
-
self.
|
1270
|
-
return func
|
1271
|
-
|
1272
|
-
def
|
1273
|
-
"""Decorator for handling
|
1274
|
-
self.
|
1275
|
-
return func
|
1276
|
-
|
1277
|
-
def
|
1278
|
-
"""Decorator for handling
|
1279
|
-
self.
|
1280
|
-
return func
|
1281
|
-
|
1282
|
-
def
|
1283
|
-
"""Decorator for handling
|
1284
|
-
self.
|
1285
|
-
return func
|
1286
|
-
|
1287
|
-
def
|
1288
|
-
"""
|
1289
|
-
|
1290
|
-
|
1291
|
-
|
1292
|
-
|
1293
|
-
|
1294
|
-
|
1295
|
-
|
1296
|
-
|
1297
|
-
|
1298
|
-
|
1299
|
-
|
1300
|
-
|
1301
|
-
|
1302
|
-
|
1303
|
-
|
1304
|
-
|
1305
|
-
|
1306
|
-
|
1307
|
-
|
1308
|
-
|
1309
|
-
|
1310
|
-
|
1311
|
-
|
1312
|
-
|
1313
|
-
|
1314
|
-
|
1315
|
-
|
1316
|
-
|
1317
|
-
|
1318
|
-
|
1319
|
-
|
1320
|
-
|
1321
|
-
self._create_thread(self.
|
1322
|
-
|
1323
|
-
|
1324
|
-
|
1325
|
-
|
1326
|
-
|
1327
|
-
|
1328
|
-
|
1329
|
-
|
1330
|
-
|
1331
|
-
|
1332
|
-
|
1333
|
-
|
1334
|
-
|
1335
|
-
|
1336
|
-
|
1337
|
-
|
1338
|
-
|
1339
|
-
|
1340
|
-
|
1341
|
-
|
1342
|
-
|
1343
|
-
|
1344
|
-
|
1345
|
-
|
1346
|
-
|
1347
|
-
|
1348
|
-
|
1349
|
-
|
1350
|
-
|
1351
|
-
|
1352
|
-
|
1353
|
-
|
1354
|
-
|
1355
|
-
|
1356
|
-
|
1357
|
-
|
1358
|
-
|
1359
|
-
|
1360
|
-
|
1361
|
-
|
1362
|
-
|
1363
|
-
|
1364
|
-
|
1365
|
-
|
1366
|
-
|
1367
|
-
|
1368
|
-
|
1369
|
-
|
1370
|
-
|
1371
|
-
|
1372
|
-
|
1373
|
-
|
1374
|
-
|
1375
|
-
|
1376
|
-
|
1377
|
-
|
1378
|
-
|
1379
|
-
|
1380
|
-
|
1381
|
-
|
1382
|
-
|
1383
|
-
|
1384
|
-
|
1385
|
-
|
1386
|
-
|
1387
|
-
|
1388
|
-
|
1389
|
-
|
1390
|
-
|
1391
|
-
|
1392
|
-
|
1393
|
-
|
1394
|
-
|
1395
|
-
updates = await client.get_updates(offset=offset)
|
1396
|
-
for update in updates:
|
1397
|
-
update_id = update['update_id']
|
1398
|
-
if update_id not in [u['update_id'] for u in past_updates]:
|
1399
|
-
await client._handle_update(update)
|
1400
|
-
offset = update_id + 1
|
1401
|
-
past_updates.append(update)
|
1402
|
-
if len(past_updates) > 30:
|
1403
|
-
past_updates.pop(0)
|
1404
|
-
|
1405
|
-
await client._handle_tick_events(time.time())
|
1406
|
-
await asyncio.sleep(0.5)
|
1407
|
-
except Exception as e:
|
1408
|
-
print(f"Error in polling: {traceback.format_exc()}")
|
1409
|
-
await asyncio.sleep(1)
|
1410
|
-
continue
|
1411
|
-
|
1412
|
-
loop = asyncio.get_event_loop()
|
1413
|
-
tasks = [loop.create_task(run_client(client)) for client in clients]
|
1414
|
-
|
1415
|
-
try:
|
1416
|
-
loop.run_until_complete(asyncio.gather(*tasks))
|
1417
|
-
except KeyboardInterrupt:
|
1418
|
-
for client in clients:
|
1419
|
-
client.safe_close()
|
1420
|
-
loop.run_until_complete(asyncio.gather(*[task.cancel() for task in tasks]))
|
1421
|
-
finally:
|
1422
|
-
loop.close()
|
1
|
+
import requests, json, time, threading
|
2
|
+
from typing import Optional, Dict, Any, List, Union
|
3
|
+
import traceback
|
4
|
+
import sqlite3
|
5
|
+
import inspect
|
6
|
+
import asyncio
|
7
|
+
|
8
|
+
__version__ = '0.2.3'
|
9
|
+
|
10
|
+
class DataBase:
|
11
|
+
def __init__(self, name):
|
12
|
+
self.name = name
|
13
|
+
self.conn = None
|
14
|
+
self.cursor = None
|
15
|
+
self._initialize_db()
|
16
|
+
|
17
|
+
def _initialize_db(self):
|
18
|
+
self.conn = sqlite3.connect(self.name)
|
19
|
+
self.cursor = self.conn.cursor()
|
20
|
+
self.cursor.execute('''CREATE TABLE IF NOT EXISTS key_value_store
|
21
|
+
(key TEXT PRIMARY KEY, value TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
22
|
+
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
|
23
|
+
self.conn.commit()
|
24
|
+
|
25
|
+
def __enter__(self):
|
26
|
+
return self
|
27
|
+
|
28
|
+
def __exit__(self, exc_type, exc_val, exc_tb):
|
29
|
+
self.close()
|
30
|
+
|
31
|
+
def close(self):
|
32
|
+
if self.conn:
|
33
|
+
self.conn.close()
|
34
|
+
self.conn = None
|
35
|
+
self.cursor = None
|
36
|
+
|
37
|
+
def read_database(self, include_timestamps=False):
|
38
|
+
if not self.conn:
|
39
|
+
self._initialize_db()
|
40
|
+
if include_timestamps:
|
41
|
+
self.cursor.execute("SELECT key, value, created_at, updated_at FROM key_value_store")
|
42
|
+
rows = self.cursor.fetchall()
|
43
|
+
return {key: {'value': json.loads(value), 'created_at': created, 'updated_at': updated}
|
44
|
+
for key, value, created, updated in rows}
|
45
|
+
else:
|
46
|
+
self.cursor.execute("SELECT key, value FROM key_value_store")
|
47
|
+
rows = self.cursor.fetchall()
|
48
|
+
return {key: json.loads(value) for key, value in rows}
|
49
|
+
|
50
|
+
def write_database(self, data_dict):
|
51
|
+
if not self.conn:
|
52
|
+
self._initialize_db()
|
53
|
+
for key, value in data_dict.items():
|
54
|
+
self.cursor.execute("""
|
55
|
+
INSERT INTO key_value_store (key, value, updated_at)
|
56
|
+
VALUES (?, ?, CURRENT_TIMESTAMP)
|
57
|
+
ON CONFLICT(key) DO UPDATE SET
|
58
|
+
value=excluded.value, updated_at=CURRENT_TIMESTAMP""",
|
59
|
+
(key, json.dumps(value, default=str)))
|
60
|
+
self.conn.commit()
|
61
|
+
|
62
|
+
def read_key(self, key: str, default=None):
|
63
|
+
if not self.conn:
|
64
|
+
self._initialize_db()
|
65
|
+
self.cursor.execute("SELECT value FROM key_value_store WHERE key = ?", (key,))
|
66
|
+
result = self.cursor.fetchone()
|
67
|
+
return json.loads(result[0]) if result else default
|
68
|
+
|
69
|
+
def write_key(self, key: str, value):
|
70
|
+
if not self.conn:
|
71
|
+
self._initialize_db()
|
72
|
+
self.cursor.execute("""
|
73
|
+
INSERT INTO key_value_store (key, value, updated_at)
|
74
|
+
VALUES (?, ?, CURRENT_TIMESTAMP)
|
75
|
+
ON CONFLICT(key) DO UPDATE SET
|
76
|
+
value=excluded.value, updated_at=CURRENT_TIMESTAMP""",
|
77
|
+
(key, json.dumps(value, default=str)))
|
78
|
+
self.conn.commit()
|
79
|
+
|
80
|
+
def delete_key(self, key: str):
|
81
|
+
if not self.conn:
|
82
|
+
self._initialize_db()
|
83
|
+
self.cursor.execute("DELETE FROM key_value_store WHERE key = ?", (key,))
|
84
|
+
self.conn.commit()
|
85
|
+
|
86
|
+
def keys(self):
|
87
|
+
if not self.conn:
|
88
|
+
self._initialize_db()
|
89
|
+
self.cursor.execute("SELECT key FROM key_value_store")
|
90
|
+
return [row[0] for row in self.cursor.fetchall()]
|
91
|
+
|
92
|
+
def clear(self):
|
93
|
+
if not self.conn:
|
94
|
+
self._initialize_db()
|
95
|
+
self.cursor.execute("DELETE FROM key_value_store")
|
96
|
+
self.conn.commit()
|
97
|
+
|
98
|
+
def get_metadata(self, key: str):
|
99
|
+
if not self.conn:
|
100
|
+
self._initialize_db()
|
101
|
+
self.cursor.execute("""
|
102
|
+
SELECT created_at, updated_at
|
103
|
+
FROM key_value_store
|
104
|
+
WHERE key = ?""", (key,))
|
105
|
+
result = self.cursor.fetchone()
|
106
|
+
return {'created_at': result[0], 'updated_at': result[1]} if result else None
|
107
|
+
|
108
|
+
def exists(self, key: str) -> bool:
|
109
|
+
if not self.conn:
|
110
|
+
self._initialize_db()
|
111
|
+
self.cursor.execute("SELECT 1 FROM key_value_store WHERE key = ?", (key,))
|
112
|
+
return bool(self.cursor.fetchone())
|
113
|
+
|
114
|
+
|
115
|
+
class ChatMember:
|
116
|
+
def __init__(self, client: 'Client', data: Dict[str, Any]):
|
117
|
+
if data:
|
118
|
+
self.status = data.get('status')
|
119
|
+
self.user = User(client, {'ok': True, 'result': data.get('user', {})})
|
120
|
+
self.is_anonymous = data.get('is_anonymous')
|
121
|
+
self.can_be_edited = data.get('can_be_edited')
|
122
|
+
self.can_manage_chat = data.get('can_manage_chat')
|
123
|
+
self.can_delete_messages = data.get('can_delete_messages')
|
124
|
+
self.can_manage_video_chats = data.get('can_manage_video_chats')
|
125
|
+
self.can_restrict_members = data.get('can_restrict_members')
|
126
|
+
self.can_promote_members = data.get('can_promote_members')
|
127
|
+
self.can_change_info = data.get('can_change_info')
|
128
|
+
self.can_invite_users = data.get('can_invite_users')
|
129
|
+
self.can_pin_messages = data.get('can_pin_messages')
|
130
|
+
self.can_manage_topics = data.get('can_manage_topics')
|
131
|
+
self.is_creator = data.get('status') == 'creator'
|
132
|
+
class BaleException(Exception):
|
133
|
+
"""Base exception for Bale API errors"""
|
134
|
+
def __init__(self, *args):
|
135
|
+
super().__init__(*args)
|
136
|
+
print(traceback.format_exc())
|
137
|
+
|
138
|
+
class LabeledPrice:
|
139
|
+
def __init__(self, label: str, amount: int):
|
140
|
+
self.label = label
|
141
|
+
self.amount = amount
|
142
|
+
self.json = {
|
143
|
+
"label": self.label,
|
144
|
+
"amount": self.amount
|
145
|
+
}
|
146
|
+
|
147
|
+
class Document:
|
148
|
+
def __init__(self, data: dict):
|
149
|
+
if data:
|
150
|
+
self.file_id = data.get('file_id')
|
151
|
+
self.file_unique_id = data.get('file_unique_id')
|
152
|
+
self.file_name = data.get('file_name')
|
153
|
+
self.mime_type = data.get('mime_type')
|
154
|
+
self.file_size = data.get('file_size')
|
155
|
+
else:
|
156
|
+
self.file_id = None
|
157
|
+
self.file_unique_id = None
|
158
|
+
self.file_name = None
|
159
|
+
self.mime_type = None
|
160
|
+
self.file_size = None
|
161
|
+
|
162
|
+
class Invoice:
|
163
|
+
def __init__(self, data: dict):
|
164
|
+
if data:
|
165
|
+
self.title = data.get('title')
|
166
|
+
self.description = data.get('description')
|
167
|
+
self.start_parameter = data.get('start_parameter')
|
168
|
+
self.currency = data.get('currency')
|
169
|
+
self.total_amount = data.get('total_amount')
|
170
|
+
else:
|
171
|
+
self.title = None
|
172
|
+
self.description = None
|
173
|
+
self.start_parameter = None
|
174
|
+
self.currency = None
|
175
|
+
self.total_amount = None
|
176
|
+
|
177
|
+
class Photo:
|
178
|
+
def __init__(self,data):
|
179
|
+
if data:
|
180
|
+
self.file_id = data.get('file_id')
|
181
|
+
self.file_unique_id = data.get('file_unique_id')
|
182
|
+
self.width = data.get('width')
|
183
|
+
self.height = data.get('height')
|
184
|
+
self.file_size = data.get('file_size')
|
185
|
+
else:
|
186
|
+
self.file_id = None
|
187
|
+
self.file_unique_id = None
|
188
|
+
self.width = None
|
189
|
+
self.height = None
|
190
|
+
self.file_size = None
|
191
|
+
|
192
|
+
class Voice:
|
193
|
+
def __init__(self, data: dict):
|
194
|
+
if data:
|
195
|
+
self.file_id = data.get('file_id')
|
196
|
+
self.file_unique_id = data.get('file_unique_id')
|
197
|
+
self.duration = data.get('duration')
|
198
|
+
self.mime_type = data.get('mime_type')
|
199
|
+
self.file_size = data.get('file_size')
|
200
|
+
else:
|
201
|
+
self.file_id = None
|
202
|
+
self.file_unique_id = None
|
203
|
+
self.duration = None
|
204
|
+
self.mime_type = None
|
205
|
+
self.file_size = None
|
206
|
+
|
207
|
+
class Location:
|
208
|
+
def __init__(self,data: dict):
|
209
|
+
if data:
|
210
|
+
self.long = self.longitude = data.get('longitude')
|
211
|
+
self.lat = self.latitude = data.get('latitude')
|
212
|
+
else:
|
213
|
+
self.longitude = self.long = None
|
214
|
+
self.latitude = self.lat = None
|
215
|
+
|
216
|
+
class Contact:
|
217
|
+
def __init__(self, data: dict):
|
218
|
+
if data:
|
219
|
+
self.phone_number = data.get('phone_number')
|
220
|
+
self.first_name = data.get('first_name')
|
221
|
+
self.last_name = data.get('last_name')
|
222
|
+
self.user_id = data.get('user_id')
|
223
|
+
else:
|
224
|
+
self.phone_number = None
|
225
|
+
self.first_name = None
|
226
|
+
self.last_name = None
|
227
|
+
self.user_id = None
|
228
|
+
|
229
|
+
class MenuKeyboardButton:
|
230
|
+
def __init__(self, text: str, request_contact: bool = False, request_location: bool = False):
|
231
|
+
if not text:
|
232
|
+
raise ValueError("Text cannot be empty")
|
233
|
+
if request_contact and request_location:
|
234
|
+
raise ValueError("Cannot request both contact and location")
|
235
|
+
|
236
|
+
self.button = {"text": text}
|
237
|
+
if request_contact:
|
238
|
+
self.button["request_contact"] = True
|
239
|
+
if request_location:
|
240
|
+
self.button["request_location"] = True
|
241
|
+
|
242
|
+
class InlineKeyboardButton:
|
243
|
+
def __init__(self, text: str, callback_data: Optional[str] = None, url: Optional[str] = None, web_app: Optional[str] = None):
|
244
|
+
self.button = {"text": text}
|
245
|
+
if sum(bool(x) for x in [callback_data, url, web_app]) != 1:
|
246
|
+
raise ValueError("Exactly one of callback_data, url, or web_app must be provided")
|
247
|
+
if callback_data:
|
248
|
+
self.button["callback_data"] = callback_data
|
249
|
+
elif url:
|
250
|
+
self.button["url"] = url
|
251
|
+
elif web_app:
|
252
|
+
self.button["web_app"] = {"url": web_app}
|
253
|
+
|
254
|
+
class MenuKeyboardMarkup:
|
255
|
+
def __init__(self):
|
256
|
+
self.menu_keyboard = []
|
257
|
+
|
258
|
+
def add(self, button: MenuKeyboardButton, row: int = 0) -> 'MenuKeyboardMarkup':
|
259
|
+
if row < 0:
|
260
|
+
raise ValueError("Row index cannot be negative")
|
261
|
+
while len(self.menu_keyboard) <= row:
|
262
|
+
self.menu_keyboard.append([])
|
263
|
+
self.menu_keyboard[row].append(button.button)
|
264
|
+
self.cleanup_empty_rows()
|
265
|
+
return self
|
266
|
+
|
267
|
+
def cleanup_empty_rows(self) -> None:
|
268
|
+
self.menu_keyboard = [row for row in self.menu_keyboard if row]
|
269
|
+
|
270
|
+
def clear(self) -> None:
|
271
|
+
self.menu_keyboard = []
|
272
|
+
|
273
|
+
def remove_button(self, text: str) -> bool:
|
274
|
+
found = False
|
275
|
+
for row in self.menu_keyboard:
|
276
|
+
for button in row[:]:
|
277
|
+
if button.get('text') == text:
|
278
|
+
row.remove(button)
|
279
|
+
found = True
|
280
|
+
self.cleanup_empty_rows()
|
281
|
+
return found
|
282
|
+
|
283
|
+
@property
|
284
|
+
def keyboard(self):
|
285
|
+
return {"keyboard": self.menu_keyboard}
|
286
|
+
|
287
|
+
class InlineKeyboardMarkup:
|
288
|
+
def __init__(self):
|
289
|
+
self.inline_keyboard = []
|
290
|
+
|
291
|
+
def add(self, button: InlineKeyboardButton, row: int = 0) -> 'InlineKeyboardMarkup':
|
292
|
+
if row < 0:
|
293
|
+
raise ValueError("Row index cannot be negative")
|
294
|
+
while len(self.inline_keyboard) <= row:
|
295
|
+
self.inline_keyboard.append([])
|
296
|
+
self.inline_keyboard[row].append(button.button)
|
297
|
+
self.cleanup_empty_rows()
|
298
|
+
return self
|
299
|
+
|
300
|
+
def cleanup_empty_rows(self) -> None:
|
301
|
+
self.inline_keyboard = [row for row in self.inline_keyboard if row]
|
302
|
+
|
303
|
+
def clear(self) -> None:
|
304
|
+
self.inline_keyboard = []
|
305
|
+
|
306
|
+
def remove_button(self, text: str) -> bool:
|
307
|
+
found = False
|
308
|
+
for row in self.inline_keyboard:
|
309
|
+
for button in row[:]:
|
310
|
+
if button.get('text') == text:
|
311
|
+
row.remove(button)
|
312
|
+
found = True
|
313
|
+
self.cleanup_empty_rows()
|
314
|
+
return found
|
315
|
+
|
316
|
+
@property
|
317
|
+
def keyboard(self) -> dict:
|
318
|
+
return {"inline_keyboard": self.inline_keyboard}
|
319
|
+
class InputFile:
|
320
|
+
"""Represents a file to be uploaded"""
|
321
|
+
def __init__(self, client: 'Client', file: Union[str, bytes], filename: Optional[str] = None):
|
322
|
+
self.client = client
|
323
|
+
self.filename = filename
|
324
|
+
if isinstance(file, str):
|
325
|
+
if file.startswith(('http://', 'https://')):
|
326
|
+
r = requests.get(file)
|
327
|
+
r.raise_for_status()
|
328
|
+
self.file = r.content
|
329
|
+
else:
|
330
|
+
try:
|
331
|
+
self.file = open(file, 'rb')
|
332
|
+
except IOError as e:
|
333
|
+
raise BaleException(f"Failed to open file: {traceback.format_exc()}")
|
334
|
+
else:
|
335
|
+
self.file = file
|
336
|
+
|
337
|
+
def __del__(self):
|
338
|
+
if hasattr(self, 'file') and hasattr(self.file, 'close'):
|
339
|
+
self.file.close()
|
340
|
+
|
341
|
+
@property
|
342
|
+
def to_bytes(self):
|
343
|
+
if hasattr(self.file, 'read'):
|
344
|
+
return self.file.read()
|
345
|
+
return self.file
|
346
|
+
|
347
|
+
class CallbackQuery:
|
348
|
+
"""Represents a callback query from a callback button"""
|
349
|
+
def __init__(self, client: 'Client', data: Dict[str, Any]):
|
350
|
+
if not data.get('ok'):
|
351
|
+
raise BaleException(f"API request failed: {traceback.format_exc()}")
|
352
|
+
self.client = client
|
353
|
+
result = data.get('result', {})
|
354
|
+
self.id = result.get('id')
|
355
|
+
self.from_user = self.user = self.author = User(client, {'ok': True, 'result': result.get('from', {})})
|
356
|
+
self.message = Message(client, {'ok': True, 'result': result.get('message', {})})
|
357
|
+
self.inline_message_id = result.get('inline_message_id')
|
358
|
+
self.chat_instance = result.get('chat_instance')
|
359
|
+
self.data = result.get('data')
|
360
|
+
|
361
|
+
def answer(self, text: str, reply_markup: Optional[Union[MenuKeyboardMarkup, InlineKeyboardMarkup]] = None) -> 'Message':
|
362
|
+
return self.client.send_message(chat_id=self.message.chat.id, text=text, reply_markup=reply_markup)
|
363
|
+
|
364
|
+
def reply(self, text: str, reply_markup: Optional[Union[MenuKeyboardMarkup, InlineKeyboardMarkup]] = None) -> 'Message':
|
365
|
+
return self.client.send_message(chat_id=self.message.chat.id, text=text, reply_markup=reply_markup, reply_to_message=self.message.id)
|
366
|
+
|
367
|
+
|
368
|
+
class Chat:
|
369
|
+
"""Represents a chat conversation"""
|
370
|
+
def __init__(self, client: 'Client', data: Dict[str, Any]):
|
371
|
+
if not data.get('ok'):
|
372
|
+
raise BaleException(f"API request failed: {traceback.format_exc()}")
|
373
|
+
self.client = client
|
374
|
+
result = data.get('result', {})
|
375
|
+
self.data = data
|
376
|
+
self.id = result.get('id')
|
377
|
+
self.type = result.get('type')
|
378
|
+
self.title = result.get('title')
|
379
|
+
self.username = result.get('username')
|
380
|
+
self.description = result.get('description')
|
381
|
+
self.invite_link = result.get('invite_link')
|
382
|
+
self.photo = result.get('photo')
|
383
|
+
|
384
|
+
def send_photo(self, photo: Union[str, bytes, InputFile],
|
385
|
+
caption: Optional[str] = None,
|
386
|
+
parse_mode: Optional[str] = None,
|
387
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
388
|
+
"""Send a photo to a chat"""
|
389
|
+
files = None
|
390
|
+
data = {
|
391
|
+
'chat_id': self.id,
|
392
|
+
'caption': caption,
|
393
|
+
'parse_mode': parse_mode,
|
394
|
+
'reply_markup': reply_markup.keyboard if isinstance(reply_markup, MenuKeyboardMarkup) else reply_markup.keyboard if isinstance(reply_markup, InlineKeyboardMarkup) else None
|
395
|
+
}
|
396
|
+
|
397
|
+
if isinstance(photo, (bytes, InputFile)) or hasattr(photo, 'read'):
|
398
|
+
files = {'photo': photo if not isinstance(photo, InputFile) else photo.file}
|
399
|
+
else:
|
400
|
+
data['photo'] = photo
|
401
|
+
|
402
|
+
response = self.client._make_request('POST', 'sendPhoto', data=data, files=files)
|
403
|
+
return Message(self.client, response)
|
404
|
+
|
405
|
+
def send_message(self, text: str,
|
406
|
+
parse_mode: Optional[str] = None,
|
407
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
408
|
+
return self.client.send_message(self.id, text, parse_mode, reply_markup)
|
409
|
+
|
410
|
+
def forward_message(self, from_chat_id: Union[int, str], message_id: int) -> 'Message':
|
411
|
+
"""Forward a message from another chat"""
|
412
|
+
return self.client.forward_message(self.id, from_chat_id, message_id)
|
413
|
+
|
414
|
+
def copy_message(self, from_chat_id: Union[int, str], message_id: int,
|
415
|
+
caption: Optional[str] = None,
|
416
|
+
parse_mode: Optional[str] = None,
|
417
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
418
|
+
"""Copy a message from another chat"""
|
419
|
+
return self.client.copy_message(self.id, from_chat_id, message_id, caption, parse_mode, reply_markup)
|
420
|
+
|
421
|
+
def send_audio(self, audio: Union[str, bytes, InputFile],
|
422
|
+
caption: Optional[str] = None,
|
423
|
+
parse_mode: Optional[str] = None,
|
424
|
+
duration: Optional[int] = None,
|
425
|
+
performer: Optional[str] = None,
|
426
|
+
title: Optional[str] = None,
|
427
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
428
|
+
"""Send an audio file"""
|
429
|
+
return self.client.send_audio(self.id, audio, caption, parse_mode, duration, performer, title, reply_markup)
|
430
|
+
|
431
|
+
def send_document(self, document: Union[str, bytes, InputFile],
|
432
|
+
caption: Optional[str] = None,
|
433
|
+
parse_mode: Optional[str] = None,
|
434
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
435
|
+
"""Send a document"""
|
436
|
+
return self.client.send_document(self.id, document, caption, parse_mode, reply_markup)
|
437
|
+
|
438
|
+
def send_video(self, video: Union[str, bytes, InputFile],
|
439
|
+
caption: Optional[str] = None,
|
440
|
+
parse_mode: Optional[str] = None,
|
441
|
+
duration: Optional[int] = None,
|
442
|
+
width: Optional[int] = None,
|
443
|
+
height: Optional[int] = None,
|
444
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
445
|
+
"""Send a video"""
|
446
|
+
return self.client.send_video(self.id, video, caption, parse_mode, duration, width, height, reply_markup)
|
447
|
+
|
448
|
+
def send_animation(self, animation: Union[str, bytes, InputFile],
|
449
|
+
caption: Optional[str] = None,
|
450
|
+
parse_mode: Optional[str] = None,
|
451
|
+
duration: Optional[int] = None,
|
452
|
+
width: Optional[int] = None,
|
453
|
+
height: Optional[int] = None,
|
454
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
455
|
+
"""Send an animation"""
|
456
|
+
return self.client.send_animation(self.id, animation, caption, parse_mode, duration, width, height, reply_markup)
|
457
|
+
|
458
|
+
def send_voice(self, voice: Union[str, bytes, InputFile],
|
459
|
+
caption: Optional[str] = None,
|
460
|
+
parse_mode: Optional[str] = None,
|
461
|
+
duration: Optional[int] = None,
|
462
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
463
|
+
"""Send a voice message"""
|
464
|
+
return self.client.send_voice(self.id, voice, caption, parse_mode, duration, reply_markup)
|
465
|
+
|
466
|
+
def send_media_group(self, chat_id: Union[int, str],
|
467
|
+
media: List[Dict],
|
468
|
+
reply_to_message: Union['Message', int, str] = None) -> List['Message']:
|
469
|
+
"""Send a group of photos, videos, documents or audios as an album"""
|
470
|
+
data = {
|
471
|
+
'chat_id': chat_id,
|
472
|
+
'media': media,
|
473
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
474
|
+
}
|
475
|
+
response = self._make_request('POST', 'sendMediaGroup', json=data)
|
476
|
+
return [Message(self, msg) for msg in response]
|
477
|
+
|
478
|
+
def send_location(self, latitude: float, longitude: float,
|
479
|
+
live_period: Optional[int] = None,
|
480
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
481
|
+
"""Send a location"""
|
482
|
+
return self.client.send_location(self.id, latitude, longitude, live_period, reply_markup)
|
483
|
+
|
484
|
+
def send_contact(self, phone_number: str, first_name: str,
|
485
|
+
last_name: Optional[str] = None,
|
486
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
487
|
+
"""Send a contact"""
|
488
|
+
return self.client.send_contact(self.id, phone_number, first_name, last_name, reply_markup)
|
489
|
+
|
490
|
+
def send_invoice(self,title:str,description:str,payload:str,provider_token:str,prices:list,photo_url: Optional[str] = None,reply_to_message: Union[int,str,'Message'] = None, reply_markup: Union[MenuKeyboardMarkup|InlineKeyboardMarkup] = None):
|
491
|
+
return self.client.send_invoice(self.id,title,description,payload,provider_token,prices,photo_url,reply_to_message,reply_markup)
|
492
|
+
|
493
|
+
def banChatMember(self, user_id: int, until_date: Optional[int] = None) -> bool:
|
494
|
+
"""Ban a user from the chat"""
|
495
|
+
data = {
|
496
|
+
'chat_id': self.id,
|
497
|
+
'user_id': user_id,
|
498
|
+
'until_date': until_date
|
499
|
+
}
|
500
|
+
response = self.client._make_request('POST', 'banChatMember', data=data)
|
501
|
+
return response.get('ok', False)
|
502
|
+
|
503
|
+
def unbanChatMember(self, user_id: int, only_if_banned: bool = False) -> bool:
|
504
|
+
"""Unban a previously banned user from the chat"""
|
505
|
+
data = {
|
506
|
+
'chat_id': self.id,
|
507
|
+
'user_id': user_id,
|
508
|
+
'only_if_banned': only_if_banned
|
509
|
+
}
|
510
|
+
response = self.client._make_request('POST', 'unbanChatMember', data=data)
|
511
|
+
return response.get('ok', False)
|
512
|
+
|
513
|
+
def promoteChatMember(self, user_id: int, can_change_info: bool = None,
|
514
|
+
can_post_messages: bool = None, can_edit_messages: bool = None,
|
515
|
+
can_delete_messages: bool = None, can_manage_video_chats: bool = None,
|
516
|
+
can_invite_users: bool = None, can_restrict_members: bool = None) -> bool:
|
517
|
+
"""Promote or demote a chat member"""
|
518
|
+
data = {
|
519
|
+
'chat_id': self.id,
|
520
|
+
'user_id': user_id,
|
521
|
+
'can_change_info': can_change_info,
|
522
|
+
'can_post_messages': can_post_messages,
|
523
|
+
'can_edit_messages': can_edit_messages,
|
524
|
+
'can_delete_messages': can_delete_messages,
|
525
|
+
'can_manage_video_chats': can_manage_video_chats,
|
526
|
+
'can_invite_users': can_invite_users,
|
527
|
+
'can_restrict_members': can_restrict_members
|
528
|
+
}
|
529
|
+
response = self.client._make_request('POST', 'promoteChatMember', data=data)
|
530
|
+
return response.get('ok', False)
|
531
|
+
|
532
|
+
def setChatPhoto(self, photo: Union[str, bytes, InputFile]) -> bool:
|
533
|
+
"""Set a new chat photo"""
|
534
|
+
files = None
|
535
|
+
data = {'chat_id': self.id}
|
536
|
+
|
537
|
+
if isinstance(photo, (bytes, InputFile)) or hasattr(photo, 'read'):
|
538
|
+
files = {'photo': photo if not isinstance(photo, InputFile) else photo.file}
|
539
|
+
else:
|
540
|
+
data['photo'] = photo
|
541
|
+
|
542
|
+
response = self.client._make_request('POST', 'setChatPhoto', data=data, files=files)
|
543
|
+
return response.get('ok', False)
|
544
|
+
|
545
|
+
def leaveChat(self) -> bool:
|
546
|
+
"""Leave the chat"""
|
547
|
+
data = {'chat_id': self.id}
|
548
|
+
response = self.client._make_request('POST', 'leaveChat', data=data)
|
549
|
+
return response.get('ok', False)
|
550
|
+
|
551
|
+
def getChat(self) -> 'Chat':
|
552
|
+
"""Get up to date information about the chat"""
|
553
|
+
data = {'chat_id': self.id}
|
554
|
+
response = self.client._make_request('GET', 'getChat', data=data)
|
555
|
+
return Chat(self.client, response)
|
556
|
+
|
557
|
+
def getChatMembersCount(self) -> int:
|
558
|
+
"""Get the number of members in the chat"""
|
559
|
+
data = {'chat_id': self.id}
|
560
|
+
response = self.client._make_request('POST', 'getChatMembersCount', data=data)
|
561
|
+
return response.get('result', 0)
|
562
|
+
|
563
|
+
def pinChatMessage(self, message_id: int, disable_notification: bool = False) -> bool:
|
564
|
+
"""Pin a message in the chat"""
|
565
|
+
data = {
|
566
|
+
'chat_id': self.id,
|
567
|
+
'message_id': message_id,
|
568
|
+
'disable_notification': disable_notification
|
569
|
+
}
|
570
|
+
response = self.client._make_request('POST', 'pinChatMessage', data=data)
|
571
|
+
return response.get('ok', False)
|
572
|
+
|
573
|
+
def unPinChatMessage(self, message_id: int) -> bool:
|
574
|
+
"""Unpin a message in the chat"""
|
575
|
+
data = {
|
576
|
+
'chat_id': self.id,
|
577
|
+
'message_id': message_id
|
578
|
+
}
|
579
|
+
response = self.client._make_request('POST', 'unpinChatMessage', data=data)
|
580
|
+
return response.get('ok', False)
|
581
|
+
|
582
|
+
def unpinAllChatMessages(self) -> bool:
|
583
|
+
"""Unpin all messages in the chat"""
|
584
|
+
data = {'chat_id': self.id}
|
585
|
+
response = self.client._make_request('POST', 'unpinAllChatMessages', data=data)
|
586
|
+
return response.get('ok', False)
|
587
|
+
|
588
|
+
def setChatTitle(self, title: str) -> bool:
|
589
|
+
"""Change the title of the chat"""
|
590
|
+
data = {
|
591
|
+
'chat_id': self.id,
|
592
|
+
'title': title
|
593
|
+
}
|
594
|
+
response = self.client._make_request('POST', 'setChatTitle', data=data)
|
595
|
+
return response.get('ok', False)
|
596
|
+
|
597
|
+
def setChatDescription(self, description: str) -> bool:
|
598
|
+
"""Change the description of the chat"""
|
599
|
+
data = {
|
600
|
+
'chat_id': self.id,
|
601
|
+
'description': description
|
602
|
+
}
|
603
|
+
response = self.client._make_request('POST', 'setChatDescription', data=data)
|
604
|
+
return response.get('ok', False)
|
605
|
+
|
606
|
+
def deleteChatPhoto(self) -> bool:
|
607
|
+
"""Delete the chat photo"""
|
608
|
+
data = {'chat_id': self.id}
|
609
|
+
response = self.client._make_request('POST', 'deleteChatPhoto', data=data)
|
610
|
+
return response.get('ok', False)
|
611
|
+
|
612
|
+
def createChatInviteLink(self) -> str:
|
613
|
+
"""Create an invite link for the chat"""
|
614
|
+
data = {'chat_id': self.id}
|
615
|
+
response = self.client._make_request('POST', 'createChatInviteLink', data=data)
|
616
|
+
return response.get('result', {}).get('invite_link')
|
617
|
+
|
618
|
+
def revokeChatInviteLink(self, invite_link: str) -> bool:
|
619
|
+
"""Revoke an invite link for the chat"""
|
620
|
+
data = {
|
621
|
+
'chat_id': self.id,
|
622
|
+
'invite_link': invite_link
|
623
|
+
}
|
624
|
+
response = self.client._make_request('POST', 'revokeChatInviteLink', data=data)
|
625
|
+
return response.get('ok', False)
|
626
|
+
|
627
|
+
def exportChatInviteLink(self) -> str:
|
628
|
+
"""Generate a new invite link for the chat"""
|
629
|
+
data = {'chat_id': self.id}
|
630
|
+
response = self.client._make_request('POST', 'exportChatInviteLink', data=data)
|
631
|
+
return response.get('result')
|
632
|
+
|
633
|
+
|
634
|
+
|
635
|
+
class User:
|
636
|
+
"""Represents a Bale user"""
|
637
|
+
def __init__(self, client: 'Client', data: Dict[str, Any]):
|
638
|
+
if not data.get('ok'):
|
639
|
+
raise BaleException(f"API request failed: {traceback.format_exc()}")
|
640
|
+
self.client = client
|
641
|
+
result = data.get('result', {})
|
642
|
+
self.data = data
|
643
|
+
self.ok = data.get('ok')
|
644
|
+
self.id = result.get('id')
|
645
|
+
self.is_bot = result.get('is_bot')
|
646
|
+
self.first_name = result.get('first_name')
|
647
|
+
self.last_name = result.get('last_name')
|
648
|
+
self.username = result.get('username')
|
649
|
+
|
650
|
+
def set_state(self, state: str) -> None:
|
651
|
+
"""Set the state for a chat or user"""
|
652
|
+
self.client.states[str(self.id)] = state
|
653
|
+
|
654
|
+
def get_state(self) -> str|None:
|
655
|
+
"""Get the state for a chat or user"""
|
656
|
+
return self.client.states.get(str(self.id))
|
657
|
+
|
658
|
+
def del_state(self) -> None:
|
659
|
+
"""Delete the state for a chat or user"""
|
660
|
+
self.client.states.pop(str(self.id), None)
|
661
|
+
|
662
|
+
|
663
|
+
def send_message(self, text: str, parse_mode: Optional[str] = None,
|
664
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
665
|
+
"""Send a message to this user"""
|
666
|
+
return self.client.send_message(self.id, text, parse_mode, reply_markup)
|
667
|
+
|
668
|
+
def send_photo(self, photo: Union[str, bytes, InputFile],
|
669
|
+
caption: Optional[str] = None,
|
670
|
+
parse_mode: Optional[str] = None,
|
671
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
672
|
+
"""Send a photo to a chat"""
|
673
|
+
return self.client.send_photo(self.id, photo, caption, parse_mode, reply_markup)
|
674
|
+
|
675
|
+
def forward_message(self, from_chat_id: Union[int, str], message_id: int) -> 'Message':
|
676
|
+
"""Forward a message to this user"""
|
677
|
+
self.client.forward_message(self.id,from_chat_id,message_id)
|
678
|
+
|
679
|
+
def copy_message(self, from_chat_id: Union[int, str], message_id: int) -> 'Message':
|
680
|
+
"""Copy a message to this user"""
|
681
|
+
self.client.copy_message(self.id,from_chat_id,message_id)
|
682
|
+
|
683
|
+
def send_audio(self, audio: Union[str, bytes, InputFile],
|
684
|
+
caption: Optional[str] = None,
|
685
|
+
parse_mode: Optional[str] = None,
|
686
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None, reply_to_message: Union[str,int,'Message'] = None) -> 'Message':
|
687
|
+
"""Send an audio file to this user"""
|
688
|
+
self.client.send_audio(self.id, audio, caption, parse_mode, reply_markup, reply_to_message)
|
689
|
+
|
690
|
+
def send_document(self, document: Union[str, bytes, InputFile],
|
691
|
+
caption: Optional[str] = None,
|
692
|
+
parse_mode: Optional[str] = None,
|
693
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None, reply_to_message: Union[str,int,'Message'] = None) -> 'Message':
|
694
|
+
"""Send a document to this user"""
|
695
|
+
self.client.send_document(self.id, document, caption, parse_mode, reply_markup, reply_markup)
|
696
|
+
|
697
|
+
def send_video(self, video: Union[str, bytes, InputFile],
|
698
|
+
caption: Optional[str] = None,
|
699
|
+
parse_mode: Optional[str] = None,
|
700
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None, reply_to_message: Union[str,int,'Message'] = None) -> 'Message':
|
701
|
+
"""Send a video to this user"""
|
702
|
+
self.client.send_video(self.id,video,caption,parse_mode,reply_markup,reply_to_message)
|
703
|
+
|
704
|
+
def send_animation(self, animation: Union[str, bytes, InputFile],
|
705
|
+
caption: Optional[str] = None,
|
706
|
+
parse_mode: Optional[str] = None,
|
707
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None, reply_to_message: Union[int,str,'Message'] = None) -> 'Message':
|
708
|
+
"""Send an animation to this user"""
|
709
|
+
return self.client.send_animation(self.id,animation,caption,parse_mode,reply_markup,reply_to_message)
|
710
|
+
|
711
|
+
def send_voice(self, voice: Union[str, bytes, InputFile],
|
712
|
+
caption: Optional[str] = None,
|
713
|
+
parse_mode: Optional[str] = None,
|
714
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,reply_to_message: Union[int,str,'Message'] = None) -> 'Message':
|
715
|
+
"""Send a voice message to this user"""
|
716
|
+
return self.client.send_voice(self.id,voice,caption,parse_mode,reply_markup,reply_to_message)
|
717
|
+
|
718
|
+
def send_media_group(self, chat_id: Union[int, str],
|
719
|
+
media: List[Dict],
|
720
|
+
reply_to_message: Union['Message', int, str] = None) -> List['Message']:
|
721
|
+
"""Send a group of photos, videos, documents or audios as an album"""
|
722
|
+
return self.client.send_media_group(chat_id, media, reply_to_message)
|
723
|
+
|
724
|
+
|
725
|
+
def send_location(self, latitude: float, longitude: float,
|
726
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,reply_to_message: Union[str,int,'Message'] = None) -> 'Message':
|
727
|
+
"""Send a location to this user"""
|
728
|
+
return self.send_location(latitude,longitude,reply_markup,reply_to_message)
|
729
|
+
|
730
|
+
def send_contact(self, phone_number: str, first_name: str,last_name: Optional[str] = None,reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None, reply_to_message: Union[str,int,'Message'] = None) -> 'Message':
|
731
|
+
"""Send a contact to this user"""
|
732
|
+
return self.client.send_contact(self.id,phone_number,first_name,last_name,reply_markup,reply_to_message)
|
733
|
+
|
734
|
+
def send_invoice(self,title:str,description:str,payload:str,provider_token:str,prices:list,photo_url: Optional[str] = None,reply_to_message: Union[int,str,'Message'] = None, reply_markup: Union[MenuKeyboardMarkup|InlineKeyboardMarkup] = None):
|
735
|
+
return self.client.send_invoice(self.id,title,description,payload,provider_token,prices,photo_url,reply_to_message,reply_markup)
|
736
|
+
|
737
|
+
class Message:
|
738
|
+
"""Represents a message in Bale"""
|
739
|
+
def __init__(self, client: 'Client', data: Dict[str, Any]):
|
740
|
+
if not data.get('ok'):
|
741
|
+
raise BaleException(f"API request failed: {traceback.format_exc()}")
|
742
|
+
self.client = client
|
743
|
+
self.ok = data.get('ok')
|
744
|
+
result = data.get('result', {})
|
745
|
+
|
746
|
+
self.message_id = self.id = result.get('message_id')
|
747
|
+
self.from_user = self.author = User(client,{'ok': True, 'result': result.get('from', {})})
|
748
|
+
self.date = result.get('date')
|
749
|
+
self.chat = Chat(client, {'ok': True, 'result': result.get('chat', {})})
|
750
|
+
self.text = result.get('text')
|
751
|
+
self.caption = result.get('caption')
|
752
|
+
self.document = Document(result.get('document'))
|
753
|
+
self.photo = Document(result.get('photo'))
|
754
|
+
self.video = Document(result.get('video'))
|
755
|
+
self.audio = Document(result.get('audio'))
|
756
|
+
self.voice = Voice(result.get('voice'))
|
757
|
+
self.animation = result.get('animation')
|
758
|
+
self.contact = Contact(result.get('contact'))
|
759
|
+
self.location = Location(result.get('location'))
|
760
|
+
self.forward_from = User(client, {'ok': True, 'result': result.get('forward_from', {})})
|
761
|
+
self.forward_from_message_id = result.get('forward_from_message_id')
|
762
|
+
self.invoice = Invoice(result.get('invoice'))
|
763
|
+
self.reply = self.reply_message
|
764
|
+
self.send = lambda text, parse_mode=None, reply_markup=None: self.client.send_message(self.chat.id, text, parse_mode, reply_markup, reply_to_message=self)
|
765
|
+
|
766
|
+
|
767
|
+
|
768
|
+
def edit(self, text: str, parse_mode: Optional[str] = None,
|
769
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
770
|
+
"""Edit this message"""
|
771
|
+
return self.client.edit_message(self.chat.id, self.message_id, text, parse_mode, reply_markup)
|
772
|
+
|
773
|
+
def delete(self) -> bool:
|
774
|
+
"""Delete this message"""
|
775
|
+
return self.client.delete_message(self.chat.id, self.message_id)
|
776
|
+
|
777
|
+
def reply_message(self, text: str, parse_mode: Optional[str] = None,
|
778
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
779
|
+
"""Send a message to this user"""
|
780
|
+
return self.client.send_message(self.chat.id, text, parse_mode, reply_markup,reply_to_message=self)
|
781
|
+
def reply_photo(self, photo: Union[str, bytes, InputFile],
|
782
|
+
caption: Optional[str] = None,
|
783
|
+
parse_mode: Optional[str] = None,
|
784
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
785
|
+
"""Send a photo to a chat"""
|
786
|
+
return self.client.send_photo(self.chat.id, photo, caption, parse_mode, reply_markup,reply_to_message=self)
|
787
|
+
|
788
|
+
|
789
|
+
def reply_audio(self, audio: Union[str, bytes, InputFile],
|
790
|
+
caption: Optional[str] = None,
|
791
|
+
parse_mode: Optional[str] = None,
|
792
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
793
|
+
"""Send an audio file to this user"""
|
794
|
+
self.client.send_audio(self.chat.id, audio, caption, parse_mode, reply_markup, reply_to_message=self)
|
795
|
+
|
796
|
+
def reply_document(self, document: Union[str, bytes, InputFile],
|
797
|
+
caption: Optional[str] = None,
|
798
|
+
parse_mode: Optional[str] = None,
|
799
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
800
|
+
"""Send a document to this user"""
|
801
|
+
self.client.send_document(self.chat.id, document, caption, parse_mode, reply_markup, reply_markup, reply_to_message=self)
|
802
|
+
|
803
|
+
def reply_video(self, video: Union[str, bytes, InputFile],
|
804
|
+
caption: Optional[str] = None,
|
805
|
+
parse_mode: Optional[str] = None,
|
806
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
807
|
+
"""Send a video to this user"""
|
808
|
+
self.client.send_video(self.chat.id,video,caption,parse_mode,reply_markup, reply_to_message=self)
|
809
|
+
|
810
|
+
def reply_animation(self, animation: Union[str, bytes, InputFile],
|
811
|
+
caption: Optional[str] = None,
|
812
|
+
parse_mode: Optional[str] = None,
|
813
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
814
|
+
"""Send an animation to this user"""
|
815
|
+
return self.client.send_animation(self.chat.id,animation,caption,parse_mode,reply_markup, reply_to_message=self)
|
816
|
+
|
817
|
+
def reply_voice(self, voice: Union[str, bytes, InputFile],
|
818
|
+
caption: Optional[str] = None,
|
819
|
+
parse_mode: Optional[str] = None,
|
820
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
821
|
+
"""Send a voice message to this user"""
|
822
|
+
return self.client.send_voice(self.chat.id,voice,caption,parse_mode,reply_markup, reply_to_message=self)
|
823
|
+
|
824
|
+
def reply_media_group(self, media: List[Dict],
|
825
|
+
reply_to_message: Union['Message', int, str] = None) -> List['Message']:
|
826
|
+
"""Send a group of photos, videos, documents or audios as an album"""
|
827
|
+
return self.client.send_media_group(self.chat.id, media, reply_to_message=self)
|
828
|
+
|
829
|
+
|
830
|
+
def reply_location(self, latitude: float, longitude: float,
|
831
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> 'Message':
|
832
|
+
"""Send a location to this user"""
|
833
|
+
return self.client.send_location(self.chat.id,latitude,longitude,reply_markup, reply_to_message=self)
|
834
|
+
|
835
|
+
def reply_contact(self, phone_number: str, first_name: str,last_name: Optional[str] = None,reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None, reply_to_message: Union[str,int,'Message'] = None) -> 'Message':
|
836
|
+
"""Send a contact to this user"""
|
837
|
+
return self.client.send_contact(self.chat.id,phone_number,first_name,last_name,reply_markup,reply_to_message)
|
838
|
+
|
839
|
+
def reply_invoice(self,title:str,description:str,payload:str,provider_token:str,prices:list,photo_url: Optional[str] = None, reply_markup: Union[MenuKeyboardMarkup|InlineKeyboardMarkup] = None):
|
840
|
+
return self.client.send_invoice(self.chat.id,title,description,payload,provider_token,prices,photo_url,self,reply_markup)
|
841
|
+
|
842
|
+
class Client:
|
843
|
+
"""Main client class for interacting with Bale API"""
|
844
|
+
def __init__(self, token: str, session: str = 'https://tapi.bale.ai', database_name='database.db'):
|
845
|
+
self.token = token
|
846
|
+
self.session = session
|
847
|
+
self.states = {}
|
848
|
+
self.database_name = database_name
|
849
|
+
self._base_url = f"{session}/bot{token}"
|
850
|
+
self._session = requests.Session()
|
851
|
+
self._message_handler = None
|
852
|
+
self._threads = []
|
853
|
+
|
854
|
+
def set_state(self, chat_or_user_id: Union[Chat,User,int,str], state: str) -> None:
|
855
|
+
"""Set the state for a chat or user"""
|
856
|
+
if isinstance(chat_or_user_id, (Chat, User)):
|
857
|
+
chat_or_user_id = chat_or_user_id.id
|
858
|
+
self.states[str(chat_or_user_id)] = state
|
859
|
+
|
860
|
+
def get_state(self, chat_or_user_id: Union[Chat,User,int,str]) -> str|None:
|
861
|
+
"""Get the state for a chat or user"""
|
862
|
+
if isinstance(chat_or_user_id, (Chat, User)):
|
863
|
+
chat_or_user_id = chat_or_user_id.id
|
864
|
+
return self.states.get(str(chat_or_user_id))
|
865
|
+
|
866
|
+
def del_state(self, chat_or_user_id: Union[Chat,User,int,str]) -> None:
|
867
|
+
"""Delete the state for a chat or user"""
|
868
|
+
if isinstance(chat_or_user_id, (Chat, User)):
|
869
|
+
chat_or_user_id = chat_or_user_id.id
|
870
|
+
self.states.pop(str(chat_or_user_id), None)
|
871
|
+
|
872
|
+
@property
|
873
|
+
def database(self) -> DataBase:
|
874
|
+
"""Get the database name"""
|
875
|
+
db = DataBase(self.database_name)
|
876
|
+
return db
|
877
|
+
|
878
|
+
|
879
|
+
def get_chat(self, chat_id: int) -> Optional[Dict]:
|
880
|
+
"""Get chat information from database"""
|
881
|
+
conn = sqlite3.connect(self.database)
|
882
|
+
cursor = conn.cursor()
|
883
|
+
cursor.execute('SELECT * FROM chats WHERE chat_id = ?', (chat_id,))
|
884
|
+
chat = cursor.fetchone()
|
885
|
+
conn.close()
|
886
|
+
if chat:
|
887
|
+
return {
|
888
|
+
'chat_id': chat[0],
|
889
|
+
'type': chat[1],
|
890
|
+
'title': chat[2],
|
891
|
+
'created_at': chat[3]
|
892
|
+
}
|
893
|
+
return None
|
894
|
+
|
895
|
+
|
896
|
+
def _make_request(self, method: str, endpoint: str, **kwargs) -> Dict[str, Any]:
|
897
|
+
"""Make an HTTP request to Bale API"""
|
898
|
+
url = f"{self._base_url}/{endpoint}"
|
899
|
+
response = self._session.request(method, url, **kwargs)
|
900
|
+
response_data = response.json()
|
901
|
+
if not response_data.get('ok'):
|
902
|
+
raise BaleException(response_data['error_code'], response_data['description'])
|
903
|
+
return response_data
|
904
|
+
|
905
|
+
def __del__(self):
|
906
|
+
if hasattr(self, '_session'):
|
907
|
+
self._session.close()
|
908
|
+
|
909
|
+
def get_me(self) -> User:
|
910
|
+
"""Get information about the bot"""
|
911
|
+
data = self._make_request('GET', 'getMe')
|
912
|
+
return User(self, data)
|
913
|
+
|
914
|
+
def get_updates(self, offset: Optional[int] = None,
|
915
|
+
limit: Optional[int] = None,
|
916
|
+
timeout: Optional[int] = None) -> List[Dict[str, Any]]:
|
917
|
+
"""Get latest updates/messages"""
|
918
|
+
params = {
|
919
|
+
'offset': offset,
|
920
|
+
'limit': limit,
|
921
|
+
'timeout': timeout
|
922
|
+
}
|
923
|
+
response = self._make_request('GET', 'getUpdates', params=params)
|
924
|
+
return response.get('result', [])
|
925
|
+
|
926
|
+
def set_webhook(self, url: str, certificate: Optional[str] = None,
|
927
|
+
max_connections: Optional[int] = None) -> bool:
|
928
|
+
"""Set webhook for getting updates"""
|
929
|
+
data = {
|
930
|
+
'url': url,
|
931
|
+
'certificate': certificate,
|
932
|
+
'max_connections': max_connections
|
933
|
+
}
|
934
|
+
return self._make_request('POST', 'setWebhook', json=data)
|
935
|
+
|
936
|
+
def get_webhook_info(self) -> Dict[str, Any]:
|
937
|
+
"""Get current webhook status"""
|
938
|
+
return self._make_request('GET', 'getWebhookInfo')
|
939
|
+
|
940
|
+
def send_message(self, chat_id: Union[int, str], text: str,
|
941
|
+
parse_mode: Optional[str] = None,
|
942
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,
|
943
|
+
reply_to_message: Union[Message,int,str] = None) -> Message:
|
944
|
+
"""Send a message to a chat"""
|
945
|
+
# Convert text to string if it isn't already
|
946
|
+
text = str(text)
|
947
|
+
|
948
|
+
data = {
|
949
|
+
'chat_id': chat_id,
|
950
|
+
'text': text,
|
951
|
+
'parse_mode': parse_mode,
|
952
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None,
|
953
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
954
|
+
}
|
955
|
+
response = self._make_request('POST', 'sendMessage', json=data)
|
956
|
+
return Message(self, response)
|
957
|
+
|
958
|
+
|
959
|
+
def forward_message(self, chat_id: Union[int, str],
|
960
|
+
from_chat_id: Union[int, str],
|
961
|
+
message_id: int) -> Message:
|
962
|
+
"""Forward a message from one chat to another"""
|
963
|
+
data = {
|
964
|
+
'chat_id': chat_id,
|
965
|
+
'from_chat_id': from_chat_id,
|
966
|
+
'message_id': message_id
|
967
|
+
}
|
968
|
+
response = self._make_request('POST', 'forwardMessage', json=data)
|
969
|
+
return Message(self, response)
|
970
|
+
|
971
|
+
def send_photo(self, chat_id: Union[int, str], photo: Union[str, bytes, InputFile],
|
972
|
+
caption: Optional[str] = None,
|
973
|
+
parse_mode: Optional[str] = None,
|
974
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,
|
975
|
+
reply_to_message: Union[Message, int, str] = None) -> Message:
|
976
|
+
"""Send a photo to a chat"""
|
977
|
+
files = None
|
978
|
+
data = {
|
979
|
+
'chat_id': chat_id,
|
980
|
+
'caption': caption,
|
981
|
+
'parse_mode': parse_mode,
|
982
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None,
|
983
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
984
|
+
}
|
985
|
+
|
986
|
+
if isinstance(photo, (bytes, InputFile)) or hasattr(photo, 'read'):
|
987
|
+
files = {'photo': photo if not isinstance(photo, InputFile) else photo.file}
|
988
|
+
else:
|
989
|
+
data['photo'] = photo
|
990
|
+
|
991
|
+
response = self._make_request('POST', 'sendPhoto', data=data, files=files)
|
992
|
+
return Message(self, response)
|
993
|
+
|
994
|
+
def delete_message(self, chat_id: Union[int, str],
|
995
|
+
message_id: int) -> bool:
|
996
|
+
"""Delete a message from a chat"""
|
997
|
+
data = {
|
998
|
+
'chat_id': chat_id,
|
999
|
+
'message_id': message_id
|
1000
|
+
}
|
1001
|
+
return self._make_request('POST', 'deleteMessage', json=data)
|
1002
|
+
|
1003
|
+
def get_user(self, user_id: Union[int, str]) -> User:
|
1004
|
+
"""Get information about a user"""
|
1005
|
+
data = self._make_request('POST', 'getChat', json={'chat_id': user_id})
|
1006
|
+
return User(self, data)
|
1007
|
+
|
1008
|
+
def edit_message(self, chat_id: Union[int, str],
|
1009
|
+
message_id: int, text: str,
|
1010
|
+
parse_mode: Optional[str] = None,
|
1011
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None) -> Message:
|
1012
|
+
"""Edit a message in a chat"""
|
1013
|
+
data = {
|
1014
|
+
'chat_id': chat_id,
|
1015
|
+
'message_id': message_id,
|
1016
|
+
'text': text,
|
1017
|
+
'parse_mode': parse_mode,
|
1018
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None
|
1019
|
+
}
|
1020
|
+
response = self._make_request('POST', 'editMessageText', json=data)
|
1021
|
+
return Message(self, response)
|
1022
|
+
|
1023
|
+
def get_chat(self, chat_id: Union[int, str]) -> Chat:
|
1024
|
+
"""Get information about a chat"""
|
1025
|
+
data = self._make_request('POST', 'getChat', json={'chat_id': chat_id})
|
1026
|
+
return Chat(self, data)
|
1027
|
+
|
1028
|
+
def send_audio(self, chat_id: Union[int, str], audio,
|
1029
|
+
caption: Optional[str] = None,
|
1030
|
+
parse_mode: Optional[str] = None,
|
1031
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,
|
1032
|
+
reply_to_message: Union[Message, int, str] = None) -> Message:
|
1033
|
+
"""Send an audio file"""
|
1034
|
+
files = None
|
1035
|
+
data = {
|
1036
|
+
'chat_id': chat_id,
|
1037
|
+
'caption': caption,
|
1038
|
+
'parse_mode': parse_mode,
|
1039
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None,
|
1040
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
1041
|
+
}
|
1042
|
+
if isinstance(audio, (bytes, InputFile)) or hasattr(audio, 'read'):
|
1043
|
+
files = {'audio': audio if not isinstance(audio, InputFile) else audio.file}
|
1044
|
+
else:
|
1045
|
+
data['audio'] = audio
|
1046
|
+
|
1047
|
+
response = self._make_request('POST', 'sendAudio', data=data, files=files)
|
1048
|
+
return Message(self, response)
|
1049
|
+
|
1050
|
+
def send_document(self, chat_id: Union[int, str], document,
|
1051
|
+
caption: Optional[str] = None,
|
1052
|
+
parse_mode: Optional[str] = None,
|
1053
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,
|
1054
|
+
reply_to_message: Union[Message, int, str] = None) -> Message:
|
1055
|
+
"""Send a document"""
|
1056
|
+
files = None
|
1057
|
+
data = {
|
1058
|
+
'chat_id': chat_id,
|
1059
|
+
'caption': caption,
|
1060
|
+
'parse_mode': parse_mode,
|
1061
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None,
|
1062
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
1063
|
+
}
|
1064
|
+
|
1065
|
+
if isinstance(document, (bytes, InputFile)) or hasattr(document, 'read'):
|
1066
|
+
files = {'document': document if not isinstance(document, InputFile) else document.file}
|
1067
|
+
else:
|
1068
|
+
data['document'] = document
|
1069
|
+
|
1070
|
+
response = self._make_request('POST', 'sendDocument', data=data, files=files)
|
1071
|
+
return Message(self, response)
|
1072
|
+
|
1073
|
+
def send_video(self, chat_id: Union[int, str], video,
|
1074
|
+
caption: Optional[str] = None,
|
1075
|
+
parse_mode: Optional[str] = None,
|
1076
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,
|
1077
|
+
reply_to_message: Union[Message, int, str] = None) -> Message:
|
1078
|
+
"""Send a video"""
|
1079
|
+
files = None
|
1080
|
+
data = {
|
1081
|
+
'chat_id': chat_id,
|
1082
|
+
'caption': caption,
|
1083
|
+
'parse_mode': parse_mode,
|
1084
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None,
|
1085
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
1086
|
+
}
|
1087
|
+
|
1088
|
+
if isinstance(video, (bytes, InputFile)) or hasattr(video, 'read'):
|
1089
|
+
files = {'video': video if not isinstance(video, InputFile) else video.file}
|
1090
|
+
else:
|
1091
|
+
data['video'] = video
|
1092
|
+
|
1093
|
+
response = self._make_request('POST', 'sendVideo', data=data, files=files)
|
1094
|
+
return Message(self, response)
|
1095
|
+
|
1096
|
+
def send_animation(self, chat_id: Union[int, str], animation,
|
1097
|
+
caption: Optional[str] = None,
|
1098
|
+
parse_mode: Optional[str] = None,
|
1099
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,
|
1100
|
+
reply_to_message: Union[Message, int, str] = None) -> Message:
|
1101
|
+
"""Send an animation (GIF or H.264/MPEG-4 AVC video without sound)"""
|
1102
|
+
files = None
|
1103
|
+
data = {
|
1104
|
+
'chat_id': chat_id,
|
1105
|
+
'caption': caption,
|
1106
|
+
'parse_mode': parse_mode,
|
1107
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None,
|
1108
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
1109
|
+
}
|
1110
|
+
|
1111
|
+
if isinstance(animation, (bytes, InputFile)) or hasattr(animation, 'read'):
|
1112
|
+
files = {'animation': animation if not isinstance(animation, InputFile) else animation.file}
|
1113
|
+
else:
|
1114
|
+
data['animation'] = animation
|
1115
|
+
|
1116
|
+
response = self._make_request('POST', 'sendAnimation', data=data, files=files)
|
1117
|
+
return Message(self, response)
|
1118
|
+
|
1119
|
+
def send_voice(self, chat_id: Union[int, str], voice,
|
1120
|
+
caption: Optional[str] = None,
|
1121
|
+
parse_mode: Optional[str] = None,
|
1122
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,
|
1123
|
+
reply_to_message: Union[Message, int, str] = None) -> Message:
|
1124
|
+
"""Send a voice message"""
|
1125
|
+
files = None
|
1126
|
+
data = {
|
1127
|
+
'chat_id': chat_id,
|
1128
|
+
'caption': caption,
|
1129
|
+
'parse_mode': parse_mode,
|
1130
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None,
|
1131
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
1132
|
+
}
|
1133
|
+
|
1134
|
+
if isinstance(voice, (bytes, InputFile)) or hasattr(voice, 'read'):
|
1135
|
+
files = {'voice': voice if not isinstance(voice, InputFile) else voice.file}
|
1136
|
+
else:
|
1137
|
+
data['voice'] = voice
|
1138
|
+
|
1139
|
+
response = self._make_request('POST', 'sendVoice', data=data, files=files)
|
1140
|
+
return Message(self, response)
|
1141
|
+
|
1142
|
+
def send_media_group(self, chat_id: Union[int, str],
|
1143
|
+
media: List[Dict],
|
1144
|
+
reply_to_message: Union[Message, int, str] = None) -> List[Message]:
|
1145
|
+
"""Send a group of photos, videos, documents or audios as an album"""
|
1146
|
+
data = {
|
1147
|
+
'chat_id': chat_id,
|
1148
|
+
'media': media,
|
1149
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
1150
|
+
}
|
1151
|
+
response = self._make_request('POST', 'sendMediaGroup', json=data)
|
1152
|
+
return [Message(self, msg) for msg in response]
|
1153
|
+
|
1154
|
+
def send_location(self, chat_id: Union[int, str],
|
1155
|
+
latitude: float, longitude: float,
|
1156
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,
|
1157
|
+
reply_to_message: Union[Message, int, str] = None) -> Message:
|
1158
|
+
"""Send a point on the map"""
|
1159
|
+
data = {
|
1160
|
+
'chat_id': chat_id,
|
1161
|
+
'latitude': latitude,
|
1162
|
+
'longitude': longitude,
|
1163
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None,
|
1164
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
1165
|
+
}
|
1166
|
+
response = self._make_request('POST', 'sendLocation', json=data)
|
1167
|
+
return Message(self, response)
|
1168
|
+
|
1169
|
+
def send_contact(self, chat_id: Union[int, str],
|
1170
|
+
phone_number: str, first_name: str,
|
1171
|
+
last_name: Optional[str] = None,
|
1172
|
+
reply_markup: Union[MenuKeyboardMarkup,InlineKeyboardMarkup] = None,
|
1173
|
+
reply_to_message: Union[Message, int, str] = None) -> Message:
|
1174
|
+
"""Send a phone contact"""
|
1175
|
+
data = {
|
1176
|
+
'chat_id': chat_id,
|
1177
|
+
'phone_number': phone_number,
|
1178
|
+
'first_name': first_name,
|
1179
|
+
'last_name': last_name,
|
1180
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None,
|
1181
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message
|
1182
|
+
}
|
1183
|
+
response = self._make_request('POST', 'sendContact', json=data)
|
1184
|
+
return Message(self, response)
|
1185
|
+
|
1186
|
+
def send_invoice(self,chat_id: Union[int,str],title:str,description:str,payload:str,provider_token:str,prices:list,photo_url: Optional[str] = None,reply_to_message: Union[int|str|Message] = None, reply_markup: Union[MenuKeyboardMarkup|InlineKeyboardMarkup] = None) -> Message:
|
1187
|
+
"""Send a invoice"""
|
1188
|
+
r = []
|
1189
|
+
for x in prices:
|
1190
|
+
r.append(x.json)
|
1191
|
+
prices = r
|
1192
|
+
data = {
|
1193
|
+
'chat_id': chat_id,
|
1194
|
+
'title': title,
|
1195
|
+
'description': description,
|
1196
|
+
'payload': payload,
|
1197
|
+
'provider_token': provider_token,
|
1198
|
+
'prices': prices,
|
1199
|
+
'photo_url': photo_url,
|
1200
|
+
'reply_to_message_id': reply_to_message.message_id if isinstance(reply_to_message, Message) else reply_to_message,
|
1201
|
+
'reply_markup': reply_markup.keyboard if reply_markup else None
|
1202
|
+
}
|
1203
|
+
response = self._make_request('POST', 'sendInvoice', json=data)
|
1204
|
+
return Message(self, response)
|
1205
|
+
|
1206
|
+
def copy_message(self, chat_id: Union[int,str,'Chat'], from_chat_id: Union[int,str,'Chat'], message_id: Union[int,str,'Chat']):
|
1207
|
+
data = {
|
1208
|
+
'chat_id': chat_id if isinstance(chat_id, (int, str)) else chat_id.id,
|
1209
|
+
'from_chat_id': from_chat_id if isinstance(from_chat_id, (int, str)) else from_chat_id.id,
|
1210
|
+
'message_id': message_id if isinstance(message_id, (int, str)) else message_id.id
|
1211
|
+
}
|
1212
|
+
response = self._make_request('POST', 'copyMessage', json=data)
|
1213
|
+
return Message(self, response)
|
1214
|
+
|
1215
|
+
def get_chat_member(self, chat: Union[int,str,'Chat'], user: Union[int,str,'User']) -> ChatMember:
|
1216
|
+
"""Get information about a member of a chat including their permissions"""
|
1217
|
+
data = {
|
1218
|
+
'chat_id': chat if isinstance(chat, (int, str)) else chat.id,
|
1219
|
+
'user_id': user if isinstance(user, (int, str)) else user.id
|
1220
|
+
}
|
1221
|
+
response = self._make_request('POST', 'getChatMember', json=data)
|
1222
|
+
return ChatMember(self, response['result'])
|
1223
|
+
|
1224
|
+
def get_chat_administrators(self, chat: Union[int,str,'Chat']) -> List[ChatMember]:
|
1225
|
+
"""Get a list of administrators in a chat"""
|
1226
|
+
data = {'chat_id': getattr(chat, 'id', chat)}
|
1227
|
+
response = self._make_request('POST', 'getChatAdministrators', json=data)
|
1228
|
+
return [ChatMember(self, member) for member in response.get('result', [])]
|
1229
|
+
|
1230
|
+
def get_chat_members_count(self, chat: Union[int,str,'Chat']) -> int:
|
1231
|
+
"""Get the number of members in a chat"""
|
1232
|
+
data = {
|
1233
|
+
'chat_id': chat if isinstance(chat, (int, str)) else chat.id
|
1234
|
+
}
|
1235
|
+
response = self._make_request('GET', 'getChatMembersCount', json=data)
|
1236
|
+
return response['result']
|
1237
|
+
|
1238
|
+
def is_joined(self, user: Union[User,int,str], chat: Union[Chat,int,str]) -> bool:
|
1239
|
+
"""Check if user is a member of the chat"""
|
1240
|
+
data = {
|
1241
|
+
'chat_id': chat if isinstance(chat, (int, str)) else chat.id,
|
1242
|
+
'user_id': user if isinstance(user, (int, str)) else user.id
|
1243
|
+
}
|
1244
|
+
response = self._make_request('GET', 'getChatMember', json=data)
|
1245
|
+
return response.get('status') not in ['left', 'kicked']
|
1246
|
+
|
1247
|
+
|
1248
|
+
def on_message(self, func):
|
1249
|
+
"""Decorator for handling new messages"""
|
1250
|
+
self._message_handler = func
|
1251
|
+
return func
|
1252
|
+
|
1253
|
+
def on_callback_query(self, func):
|
1254
|
+
"""Decorator for handling callback queries"""
|
1255
|
+
self._callback_handler = func
|
1256
|
+
return func
|
1257
|
+
|
1258
|
+
def on_tick(self, seconds: int):
|
1259
|
+
"""Decorator for handling periodic events"""
|
1260
|
+
def decorator(func):
|
1261
|
+
if not hasattr(self, '_tick_handlers'):
|
1262
|
+
self._tick_handlers = {}
|
1263
|
+
self._tick_handlers[func] = {'interval': seconds, 'last_run': 0}
|
1264
|
+
return func
|
1265
|
+
return decorator
|
1266
|
+
|
1267
|
+
def on_close(self, func):
|
1268
|
+
"""Decorator for handling close event"""
|
1269
|
+
self._close_handler = func
|
1270
|
+
return func
|
1271
|
+
|
1272
|
+
def on_ready(self, func):
|
1273
|
+
"""Decorator for handling ready event"""
|
1274
|
+
self._ready_handler = func
|
1275
|
+
return func
|
1276
|
+
|
1277
|
+
def on_update(self, func):
|
1278
|
+
"""Decorator for handling raw updates"""
|
1279
|
+
self._update_handler = func
|
1280
|
+
return func
|
1281
|
+
|
1282
|
+
def on_member_chat_join(self, func):
|
1283
|
+
"""Decorator for handling new chat members"""
|
1284
|
+
self._member_join_handler = func
|
1285
|
+
return func
|
1286
|
+
|
1287
|
+
def on_member_chat_leave(self, func):
|
1288
|
+
"""Decorator for handling members leaving chat"""
|
1289
|
+
self._member_leave_handler = func
|
1290
|
+
return func
|
1291
|
+
|
1292
|
+
def on_message_edit(self, func):
|
1293
|
+
"""Decorator for handling edited messages"""
|
1294
|
+
self._message_edit_handler = func
|
1295
|
+
return func
|
1296
|
+
|
1297
|
+
def _create_thread(self, handler, *args):
|
1298
|
+
"""Helper method to create and start a thread"""
|
1299
|
+
thread = threading.Thread(target=handler, args=args, daemon=True)
|
1300
|
+
thread.start()
|
1301
|
+
self._threads.append(thread)
|
1302
|
+
|
1303
|
+
def _handle_message(self, message, update):
|
1304
|
+
"""Handle different types of messages"""
|
1305
|
+
if 'message' in update:
|
1306
|
+
msg_data = update['message']
|
1307
|
+
if 'new_chat_members' in msg_data and hasattr(self, '_member_join_handler'):
|
1308
|
+
chat = msg_data['chat']
|
1309
|
+
user = msg_data['new_chat_members'][0]
|
1310
|
+
self._create_thread(self._member_join_handler, message, Chat(self,{"ok":True,"result":chat}), User(self,{"ok":True,"result":user}))
|
1311
|
+
elif 'left_chat_member' in msg_data and hasattr(self, '_member_leave_handler'):
|
1312
|
+
chat = msg_data['chat']
|
1313
|
+
user = msg_data['left_chat_member']
|
1314
|
+
self._create_thread(self._member_leave_handler, message, Chat(self,{"ok":True,"result":chat}), User(self,{"ok":True,"result":user}))
|
1315
|
+
elif self._message_handler:
|
1316
|
+
args = (message, update) if len(inspect.signature(self._message_handler).parameters) > 1 else (message,)
|
1317
|
+
self._create_thread(self._message_handler, *args)
|
1318
|
+
|
1319
|
+
def _handle_update(self, update):
|
1320
|
+
if hasattr(self, '_update_handler'):
|
1321
|
+
self._create_thread(self._update_handler, update)
|
1322
|
+
|
1323
|
+
update_type = next((key for key in ('message', 'edited_message', 'callback_query') if key in update), None)
|
1324
|
+
if update_type == 'message':
|
1325
|
+
message = Message(self, {'ok': True, 'result': update['message']})
|
1326
|
+
self._handle_message(message, update)
|
1327
|
+
elif update_type == 'edited_message' and hasattr(self, '_message_edit_handler'):
|
1328
|
+
edited_message = Message(self, {'ok': True, 'result': update['edited_message']})
|
1329
|
+
args = (edited_message, update) if len(inspect.signature(self._message_edit_handler).parameters) > 1 else (edited_message,)
|
1330
|
+
self._create_thread(self._message_edit_handler, *args)
|
1331
|
+
elif update_type == 'callback_query' and self._callback_handler:
|
1332
|
+
callback_query = CallbackQuery(self, {'ok': True, 'result': update['callback_query']})
|
1333
|
+
args = (callback_query, update) if len(inspect.signature(self._callback_handler).parameters) > 1 else (callback_query,)
|
1334
|
+
self._create_thread(self._callback_handler, *args)
|
1335
|
+
|
1336
|
+
def _handle_tick_events(self, current_time):
|
1337
|
+
"""Handle periodic tick events"""
|
1338
|
+
if hasattr(self, '_tick_handlers'):
|
1339
|
+
for handler, info in self._tick_handlers.items():
|
1340
|
+
if current_time - info['last_run'] >= info['interval']:
|
1341
|
+
self._create_thread(handler)
|
1342
|
+
info['last_run'] = current_time
|
1343
|
+
|
1344
|
+
def run(self):
|
1345
|
+
"""Start polling for new messages"""
|
1346
|
+
self._polling = True
|
1347
|
+
offset = 0
|
1348
|
+
past_updates = set()
|
1349
|
+
|
1350
|
+
if hasattr(self, '_ready_handler'):
|
1351
|
+
self._ready_handler()
|
1352
|
+
|
1353
|
+
while self._polling:
|
1354
|
+
try:
|
1355
|
+
updates = self.get_updates(offset=offset, timeout=30)
|
1356
|
+
for update in updates:
|
1357
|
+
update_id = update['update_id']
|
1358
|
+
if update_id not in past_updates:
|
1359
|
+
self._handle_update(update)
|
1360
|
+
offset = update_id + 1
|
1361
|
+
past_updates.add(update_id)
|
1362
|
+
if len(past_updates) > 100:
|
1363
|
+
past_updates.clear()
|
1364
|
+
past_updates = set(sorted(list(past_updates))[-50:])
|
1365
|
+
|
1366
|
+
current_time = time.time()
|
1367
|
+
self._handle_tick_events(current_time)
|
1368
|
+
self._threads = [t for t in self._threads if t.is_alive()]
|
1369
|
+
time.sleep(0.1) # Reduced sleep time
|
1370
|
+
except Exception as e:
|
1371
|
+
print(f"Error in polling: {traceback.format_exc()}")
|
1372
|
+
time.sleep(1)
|
1373
|
+
continue
|
1374
|
+
|
1375
|
+
def get_updates(self, offset: Optional[int] = None,
|
1376
|
+
limit: Optional[int] = None,
|
1377
|
+
timeout: Optional[int] = None) -> List[Dict[str, Any]]:
|
1378
|
+
"""Get latest updates/messages"""
|
1379
|
+
params = {k: v for k, v in {
|
1380
|
+
'offset': offset,
|
1381
|
+
'limit': limit,
|
1382
|
+
'timeout': timeout
|
1383
|
+
}.items() if v is not None}
|
1384
|
+
response = self._make_request('GET', 'getUpdates', params=params)
|
1385
|
+
return response.get('result', [])
|
1386
|
+
|
1387
|
+
def safe_close(self):
|
1388
|
+
"""Close the client and stop polling"""
|
1389
|
+
self._polling = False
|
1390
|
+
for thread in self._threads:
|
1391
|
+
thread.join(timeout=1.0)
|
1392
|
+
self._threads.clear()
|
1393
|
+
if hasattr(self, '_close_handler'):
|
1394
|
+
self._close_handler()
|