pyrobale 0.2.3__py3-none-any.whl → 0.2.8__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.py CHANGED
@@ -1,1394 +1,2269 @@
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()
1
+ """
2
+ PyRobale - A Python library for developing bale bots.
3
+
4
+ Features:
5
+ - Simple and fast
6
+ - Customizable and Customizes
7
+ - Eazy to learn
8
+ - New and Up to date
9
+ - Internal database management
10
+ """
11
+ import json
12
+ import time
13
+ from typing import Optional, Dict, Any, List, Union
14
+ import threading
15
+ import traceback
16
+ import sqlite3
17
+ import inspect
18
+ import requests
19
+ import re
20
+ import sys
21
+ import os
22
+ from urllib.parse import urlparse, unquote
23
+
24
+ __version__ = '0.2.8'
25
+
26
+ class ChatActions:
27
+ """Represents different chat action states that can be sent to Bale"""
28
+ TYPING: str = 'typing'
29
+ PHOTO: str = 'upload_photo'
30
+ VIDEO: str = 'record_video'
31
+ CHOOSE_STICKER: str = 'choose_sticker'
32
+ class conditions:
33
+
34
+ """
35
+ A class for defining conditions for message handling.
36
+ """
37
+
38
+ def __init__(
39
+ self,
40
+ client: 'Client' = None,
41
+ user: 'User' = None,
42
+ message: 'Message' = None,
43
+ callback: 'CallbackQuery' = None,
44
+ chat: 'Chat' = None):
45
+ self.client = client
46
+ self.user = user
47
+ self.message = message
48
+ self.callback = callback
49
+ self.chat = chat
50
+
51
+ def is_joined(self, *chats) -> bool:
52
+ """Check if user is member of all specified chats"""
53
+ return all(self.client.is_joined(chat_id, self.user.id)
54
+ for chat_id in chats)
55
+
56
+ def is_admin(self, chat: 'Chat') -> bool:
57
+ """Check if user is an admin"""
58
+ member = self.client.get_chat_member(chat.id, self.user.id)
59
+ return member.status in ['administrator', 'owner']
60
+
61
+ def is_owner(self, chat: 'Chat') -> bool:
62
+ """Check if user is the owner"""
63
+ member = self.client.get_chat_member(chat.id, self.user.id)
64
+ return member.is_creator
65
+
66
+ def is_private_chat(self) -> bool:
67
+ """Check if message is in private chat"""
68
+ return self.chat.type == 'private'
69
+
70
+ def is_group_chat(self) -> bool:
71
+ """Check if message is in group chat"""
72
+ return self.chat.type in ['group', 'supergroup']
73
+
74
+ def is_channel(self) -> bool:
75
+ """Check if message is in channel"""
76
+ return self.chat.type == 'channel'
77
+
78
+ def has_text(self) -> bool:
79
+ """Check if message contains text"""
80
+ return bool(self.message.text)
81
+
82
+ def has_photo(self) -> bool:
83
+ """Check if message contains photo"""
84
+ return bool(self.message.photo)
85
+
86
+ def has_document(self) -> bool:
87
+ """Check if message contains document"""
88
+ return bool(self.message.document)
89
+
90
+ def is_reply(self) -> bool:
91
+ """Check if message is a reply"""
92
+ return bool(self.message.reply_to_message)
93
+
94
+ def is_forwarded(self) -> bool:
95
+ """Check if message is forwarded"""
96
+ return bool(self.message.forward_from)
97
+
98
+ def at_state(self, state: str) -> bool:
99
+ """Check if user is in the specified state"""
100
+ return self.client.get_state(self.chat.id) == state
101
+
102
+ def is_bot(self) -> bool:
103
+ """Check if user is a bot"""
104
+ return self.user.is_bot
105
+
106
+ def is_user(self) -> bool:
107
+ """Check if user is a user"""
108
+ return not self.user.is_bot
109
+
110
+ def is_admin_or_owner(self, chat: 'Chat') -> bool:
111
+ """Check if user is an admin or owner"""
112
+ return self.is_admin(chat) or self.is_owner(chat)
113
+
114
+ def matches_regex(self, pattern: str) -> bool:
115
+ """Check if message text matches regex pattern"""
116
+ if not self.message.text:
117
+ return False
118
+ return bool(re.match(pattern, self.message.text))
119
+
120
+ def contains_url(self) -> bool:
121
+ """Check if message contains url"""
122
+ if not self.message.text:
123
+ return False
124
+ return bool(
125
+ re.search(
126
+ r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
127
+ self.message.text))
128
+
129
+
130
+ class DataBase:
131
+ """
132
+ Database class for managing key-value pairs in a SQLite database.
133
+ """
134
+
135
+ def __init__(self, name):
136
+ self.name = name
137
+ self.conn = None
138
+ self.cursor = None
139
+ self._initialize_db()
140
+
141
+ def _initialize_db(self):
142
+ self.conn = sqlite3.connect(self.name)
143
+ self.cursor = self.conn.cursor()
144
+ self.cursor.execute('''CREATE TABLE IF NOT EXISTS key_value_store
145
+ (key TEXT PRIMARY KEY, value TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
146
+ updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')
147
+ self.conn.commit()
148
+
149
+ def __enter__(self):
150
+ return self
151
+
152
+ def __exit__(self, exc_type, exc_val, exc_tb):
153
+ self.close()
154
+
155
+ def close(self):
156
+ if self.conn:
157
+ self.conn.close()
158
+ self.conn = None
159
+ self.cursor = None
160
+
161
+ def read_database(self, include_timestamps=False):
162
+ if not self.conn:
163
+ self._initialize_db()
164
+ if include_timestamps:
165
+ self.cursor.execute(
166
+ "SELECT key, value, created_at, updated_at FROM key_value_store")
167
+ rows = self.cursor.fetchall()
168
+ return {
169
+ key: {
170
+ 'value': json.loads(value),
171
+ 'created_at': created,
172
+ 'updated_at': updated} for key,
173
+ value,
174
+ created,
175
+ updated in rows}
176
+ else:
177
+ self.cursor.execute("SELECT key, value FROM key_value_store")
178
+ rows = self.cursor.fetchall()
179
+ return {key: json.loads(value) for key, value in rows}
180
+
181
+ def write_database(self, data_dict):
182
+ if not self.conn:
183
+ self._initialize_db()
184
+ for key, value in data_dict.items():
185
+ self.cursor.execute("""
186
+ INSERT INTO key_value_store (key, value, updated_at)
187
+ VALUES (?, ?, CURRENT_TIMESTAMP)
188
+ ON CONFLICT(key) DO UPDATE SET
189
+ value=excluded.value, updated_at=CURRENT_TIMESTAMP""",
190
+ (key, json.dumps(value, default=str)))
191
+ self.conn.commit()
192
+
193
+ def read_key(self, key: str, default=None):
194
+ if not self.conn:
195
+ self._initialize_db()
196
+ self.cursor.execute(
197
+ "SELECT value FROM key_value_store WHERE key = ?", (key,))
198
+ result = self.cursor.fetchone()
199
+ return json.loads(result[0]) if result else default
200
+
201
+ def write_key(self, key: str, value):
202
+ if not self.conn:
203
+ self._initialize_db()
204
+ self.cursor.execute("""
205
+ INSERT INTO key_value_store (key, value, updated_at)
206
+ VALUES (?, ?, CURRENT_TIMESTAMP)
207
+ ON CONFLICT(key) DO UPDATE SET
208
+ value=excluded.value, updated_at=CURRENT_TIMESTAMP""",
209
+ (key, json.dumps(value, default=str)))
210
+ self.conn.commit()
211
+
212
+ def delete_key(self, key: str):
213
+ if not self.conn:
214
+ self._initialize_db()
215
+ self.cursor.execute(
216
+ "DELETE FROM key_value_store WHERE key = ?", (key,))
217
+ self.conn.commit()
218
+
219
+ def keys(self):
220
+ if not self.conn:
221
+ self._initialize_db()
222
+ self.cursor.execute("SELECT key FROM key_value_store")
223
+ return [row[0] for row in self.cursor.fetchall()]
224
+
225
+ def clear(self):
226
+ if not self.conn:
227
+ self._initialize_db()
228
+ self.cursor.execute("DELETE FROM key_value_store")
229
+ self.conn.commit()
230
+
231
+ def get_metadata(self, key: str):
232
+ if not self.conn:
233
+ self._initialize_db()
234
+ self.cursor.execute("""
235
+ SELECT created_at, updated_at
236
+ FROM key_value_store
237
+ WHERE key = ?""", (key,))
238
+ result = self.cursor.fetchone()
239
+ return {
240
+ 'created_at': result[0],
241
+ 'updated_at': result[1]} if result else None
242
+
243
+ def exists(self, key: str) -> bool:
244
+ if not self.conn:
245
+ self._initialize_db()
246
+ self.cursor.execute(
247
+ "SELECT 1 FROM key_value_store WHERE key = ?", (key,))
248
+ return bool(self.cursor.fetchone())
249
+
250
+
251
+ class ChatMember:
252
+ def __init__(self, client: 'Client', data: Dict[str, Any]):
253
+ if data:
254
+ self.status = data.get('status')
255
+ self.user = User(
256
+ client, {
257
+ 'ok': True, 'result': data.get(
258
+ 'user', {})})
259
+ self.is_anonymous = data.get('is_anonymous')
260
+ self.can_be_edited = data.get('can_be_edited')
261
+ self.can_manage_chat = data.get('can_manage_chat')
262
+ self.can_delete_messages = data.get('can_delete_messages')
263
+ self.can_manage_video_chats = data.get('can_manage_video_chats')
264
+ self.can_restrict_members = data.get('can_restrict_members')
265
+ self.can_promote_members = data.get('can_promote_members')
266
+ self.can_change_info = data.get('can_change_info')
267
+ self.can_invite_users = data.get('can_invite_users')
268
+ self.can_pin_messages = data.get('can_pin_messages')
269
+ self.can_manage_topics = data.get('can_manage_topics')
270
+ self.is_creator = data.get('status') == 'creator'
271
+
272
+
273
+ class BaleException(Exception):
274
+ """Base exception for Bale API errors"""
275
+
276
+ def __init__(self, message=None, error_code=None, response=None):
277
+ self.message = message
278
+ self.error_code = error_code
279
+ self.response = response
280
+
281
+ error_text = f"Error {error_code}: {message}" if error_code else message
282
+ super().__init__(error_text)
283
+
284
+ def __str__(self):
285
+ return f"{self.__class__.__name__}: {self.message}"
286
+
287
+
288
+ class BaleAPIError(BaleException):
289
+ """Exception for API-specific errors"""
290
+ pass
291
+
292
+
293
+ class BaleNetworkError(BaleException):
294
+ """Exception for network-related errors"""
295
+ pass
296
+
297
+
298
+ class BaleAuthError(BaleException):
299
+ """Exception for authentication errors"""
300
+ pass
301
+
302
+
303
+ class BaleValidationError(BaleException):
304
+ """Exception for data validation errors"""
305
+ pass
306
+
307
+
308
+ class BaleTimeoutError(BaleException):
309
+ """Exception for timeout errors"""
310
+ pass
311
+
312
+
313
+ class BaleNotFoundError(BaleException):
314
+ """Exception for when a resource is not found"""
315
+ pass
316
+
317
+
318
+ class BaleForbiddenError(BaleException):
319
+ """Exception for forbidden access errors"""
320
+ pass
321
+
322
+
323
+ class BaleServerError(BaleException):
324
+ """Exception for server-side errors"""
325
+ pass
326
+
327
+
328
+ class BaleRateLimitError(BaleException):
329
+ """Exception for rate limit errors"""
330
+ pass
331
+
332
+
333
+ class BaleTokenNotFoundError(BaleException):
334
+ """Exception for when a token is not found"""
335
+ pass
336
+
337
+
338
+ class BaleUnknownError(BaleException):
339
+ """Exception for unknown errors"""
340
+ pass
341
+
342
+
343
+ class LabeledPrice:
344
+ def __init__(self, label: str, amount: int):
345
+ self.label = label
346
+ self.amount = amount
347
+ self.json = {
348
+ "label": self.label,
349
+ "amount": self.amount
350
+ }
351
+
352
+
353
+ class Document:
354
+ def __init__(self, data: dict):
355
+ if data:
356
+ self.file_id = data.get('file_id')
357
+ self.file_unique_id = data.get('file_unique_id')
358
+ self.file_name = data.get('file_name')
359
+ self.mime_type = data.get('mime_type')
360
+ self.file_size = data.get('file_size')
361
+ else:
362
+ self.file_id = None
363
+ self.file_unique_id = None
364
+ self.file_name = None
365
+ self.mime_type = None
366
+ self.file_size = None
367
+
368
+
369
+ class Invoice:
370
+ def __init__(self, data: dict):
371
+ if data:
372
+ self.title = data.get('title')
373
+ self.description = data.get('description')
374
+ self.start_parameter = data.get('start_parameter')
375
+ self.currency = data.get('currency')
376
+ self.total_amount = data.get('total_amount')
377
+ else:
378
+ self.title = None
379
+ self.description = None
380
+ self.start_parameter = None
381
+ self.currency = None
382
+ self.total_amount = None
383
+
384
+
385
+ class Photo:
386
+ def __init__(self, data):
387
+ if data:
388
+ self.file_id = data.get('file_id')
389
+ self.file_unique_id = data.get('file_unique_id')
390
+ self.width = data.get('width')
391
+ self.height = data.get('height')
392
+ self.file_size = data.get('file_size')
393
+ else:
394
+ self.file_id = None
395
+ self.file_unique_id = None
396
+ self.width = None
397
+ self.height = None
398
+ self.file_size = None
399
+
400
+
401
+ class Voice:
402
+ def __init__(self, data: dict):
403
+ if data:
404
+ self.file_id = data.get('file_id')
405
+ self.file_unique_id = data.get('file_unique_id')
406
+ self.duration = data.get('duration')
407
+ self.mime_type = data.get('mime_type')
408
+ self.file_size = data.get('file_size')
409
+ else:
410
+ self.file_id = None
411
+ self.file_unique_id = None
412
+ self.duration = None
413
+ self.mime_type = None
414
+ self.file_size = None
415
+
416
+
417
+ class Location:
418
+ def __init__(self, data: dict):
419
+ if data:
420
+ self.long = self.longitude = data.get('longitude')
421
+ self.lat = self.latitude = data.get('latitude')
422
+ else:
423
+ self.longitude = self.long = None
424
+ self.latitude = self.lat = None
425
+
426
+
427
+ class Contact:
428
+ def __init__(self, data: dict):
429
+ if data:
430
+ self.phone_number = data.get('phone_number')
431
+ self.first_name = data.get('first_name')
432
+ self.last_name = data.get('last_name')
433
+ self.user_id = data.get('user_id')
434
+ else:
435
+ self.phone_number = None
436
+ self.first_name = None
437
+ self.last_name = None
438
+ self.user_id = None
439
+
440
+
441
+ class MenuKeyboardButton:
442
+ def __init__(
443
+ self,
444
+ text: str,
445
+ request_contact: bool = False,
446
+ request_location: bool = False):
447
+ if not text:
448
+ raise ValueError("Text cannot be empty")
449
+ if request_contact and request_location:
450
+ raise ValueError("Cannot request both contact and location")
451
+
452
+ self.button = {"text": text}
453
+ if request_contact:
454
+ self.button["request_contact"] = True
455
+ if request_location:
456
+ self.button["request_location"] = True
457
+
458
+
459
+ class InlineKeyboardButton:
460
+ def __init__(
461
+ self,
462
+ text: str,
463
+ callback_data: Optional[str] = None,
464
+ url: Optional[str] = None,
465
+ web_app: Optional[str] = None):
466
+ self.button = {"text": text}
467
+ if sum(bool(x) for x in [callback_data, url, web_app]) != 1:
468
+ raise ValueError(
469
+ "Exactly one of callback_data, url, or web_app must be provided")
470
+ if callback_data:
471
+ self.button["callback_data"] = callback_data
472
+ elif url:
473
+ self.button["url"] = url
474
+ elif web_app:
475
+ self.button["web_app"] = {"url": web_app}
476
+
477
+
478
+ class MenuKeyboardMarkup:
479
+ def __init__(self):
480
+ self.menu_keyboard = []
481
+
482
+ def add(self, button: MenuKeyboardButton,
483
+ row: int = 0) -> 'MenuKeyboardMarkup':
484
+ if row < 0:
485
+ raise ValueError("Row index cannot be negative")
486
+ while len(self.menu_keyboard) <= row:
487
+ self.menu_keyboard.append([])
488
+ self.menu_keyboard[row].append(button.button)
489
+ self.cleanup_empty_rows()
490
+ return self
491
+
492
+ def cleanup_empty_rows(self) -> None:
493
+ self.menu_keyboard = [row for row in self.menu_keyboard if row]
494
+
495
+ def clear(self) -> None:
496
+ self.menu_keyboard = []
497
+
498
+ def remove_button(self, text: str) -> bool:
499
+ found = False
500
+ for row in self.menu_keyboard:
501
+ for button in row[:]:
502
+ if button.get('text') == text:
503
+ row.remove(button)
504
+ found = True
505
+ self.cleanup_empty_rows()
506
+ return found
507
+
508
+ @property
509
+ def keyboard(self):
510
+ return {"keyboard": self.menu_keyboard}
511
+
512
+
513
+ class InlineKeyboardMarkup:
514
+ def __init__(self):
515
+ self.inline_keyboard = []
516
+
517
+ def add(self, button: InlineKeyboardButton,
518
+ row: int = 0) -> 'InlineKeyboardMarkup':
519
+ if row < 0:
520
+ raise ValueError("Row index cannot be negative")
521
+ while len(self.inline_keyboard) <= row:
522
+ self.inline_keyboard.append([])
523
+ self.inline_keyboard[row].append(button.button)
524
+ self.cleanup_empty_rows()
525
+ return self
526
+
527
+ def cleanup_empty_rows(self) -> None:
528
+ self.inline_keyboard = [row for row in self.inline_keyboard if row]
529
+
530
+ def clear(self) -> None:
531
+ self.inline_keyboard = []
532
+
533
+ def remove_button(self, text: str) -> bool:
534
+ found = False
535
+ for row in self.inline_keyboard:
536
+ for button in row[:]:
537
+ if button.get('text') == text:
538
+ row.remove(button)
539
+ found = True
540
+ self.cleanup_empty_rows()
541
+ return found
542
+
543
+ @property
544
+ def keyboard(self) -> dict:
545
+ return {"inline_keyboard": self.inline_keyboard}
546
+
547
+
548
+ class InputFile:
549
+ """Represents a file to be uploaded"""
550
+
551
+ def __init__(self,
552
+ client: 'Client',
553
+ file: Union[str,
554
+ bytes],
555
+ filename: Optional[str] = None):
556
+ self.client = client
557
+ self.filename = filename
558
+ if isinstance(file, str):
559
+ if file.startswith(('http://', 'https://')):
560
+ r = requests.get(file)
561
+ r.raise_for_status()
562
+ self.file = r.content
563
+ else:
564
+ try:
565
+ self.file = open(file, 'rb')
566
+ except IOError:
567
+ raise BaleException(
568
+ f"Failed to open file: {traceback.format_exc()}")
569
+ else:
570
+ self.file = file
571
+
572
+ def __del__(self):
573
+ if hasattr(self, 'file') and hasattr(self.file, 'close'):
574
+ self.file.close()
575
+
576
+ @property
577
+ def to_bytes(self):
578
+ if hasattr(self.file, 'read'):
579
+ return self.file.read()
580
+ return self.file
581
+
582
+
583
+ class CallbackQuery:
584
+ """Represents a callback query from a callback button"""
585
+
586
+ def __init__(self, client: 'Client', data: Dict[str, Any]):
587
+ if not data.get('ok'):
588
+ raise BaleException(
589
+ f"API request failed: {traceback.format_exc()}")
590
+ self.client = client
591
+ result = data.get('result', {})
592
+ self.id = result.get('id')
593
+ self.from_user = self.user = self.author = User(
594
+ client, {'ok': True, 'result': result.get('from', {})})
595
+ self.message = Message(
596
+ client, {
597
+ 'ok': True, 'result': result.get(
598
+ 'message', {})})
599
+ self.inline_message_id = result.get('inline_message_id')
600
+ self.chat_instance = result.get('chat_instance')
601
+ self.data = result.get('data')
602
+
603
+ def answer(self,
604
+ text: str,
605
+ reply_markup: Optional[Union[MenuKeyboardMarkup,
606
+ InlineKeyboardMarkup]] = None) -> 'Message':
607
+ return self.client.send_message(
608
+ chat_id=self.message.chat.id,
609
+ text=text,
610
+ reply_markup=reply_markup)
611
+
612
+ def reply(self,
613
+ text: str,
614
+ reply_markup: Optional[Union[MenuKeyboardMarkup,
615
+ InlineKeyboardMarkup]] = None) -> 'Message':
616
+ return self.client.send_message(
617
+ chat_id=self.message.chat.id,
618
+ text=text,
619
+ reply_markup=reply_markup,
620
+ reply_to_message=self.message.id)
621
+
622
+
623
+ class Chat:
624
+ """Represents a chat conversation"""
625
+
626
+ def __init__(self, client: 'Client', data: Dict[str, Any]):
627
+ if not data.get('ok'):
628
+ raise BaleException(
629
+ f"API request failed: {traceback.format_exc()}")
630
+ self.client = client
631
+ result = data.get('result', {})
632
+ self.data = data
633
+ self.id = result.get('id')
634
+ self.type = result.get('type')
635
+ self.title = result.get('title')
636
+ self.username = result.get('username')
637
+ self.description = result.get('description')
638
+ self.invite_link = result.get('invite_link')
639
+ self.photo = result.get('photo')
640
+
641
+ def send_photo(self,
642
+ photo: Union[str,
643
+ bytes,
644
+ InputFile],
645
+ caption: Optional[str] = None,
646
+ parse_mode: Optional[str] = None,
647
+ reply_markup: Union[MenuKeyboardMarkup,
648
+ InlineKeyboardMarkup] = None) -> 'Message':
649
+ """Send a photo to a chat"""
650
+ files = None
651
+ data = {
652
+ 'chat_id': self.id,
653
+ 'caption': caption,
654
+ 'parse_mode': parse_mode,
655
+ 'reply_markup': reply_markup.keyboard if isinstance(
656
+ reply_markup,
657
+ MenuKeyboardMarkup) else reply_markup.keyboard if isinstance(
658
+ reply_markup,
659
+ InlineKeyboardMarkup) else None}
660
+
661
+ if isinstance(photo, (bytes, InputFile)) or hasattr(photo, 'read'):
662
+ files = {
663
+ 'photo': photo if not isinstance(
664
+ photo, InputFile) else photo.file}
665
+ else:
666
+ data['photo'] = photo
667
+
668
+ response = self.client._make_request(
669
+ 'POST', 'sendPhoto', data=data, files=files)
670
+ return Message(self.client, response)
671
+
672
+ def send_message(self,
673
+ text: str,
674
+ parse_mode: Optional[str] = None,
675
+ reply_markup: Union[MenuKeyboardMarkup,
676
+ InlineKeyboardMarkup] = None) -> 'Message':
677
+ return self.client.send_message(
678
+ self.id, text, parse_mode, reply_markup)
679
+
680
+ def forward_message(
681
+ self, from_chat_id: Union[int, str], message_id: int) -> 'Message':
682
+ """Forward a message from another chat"""
683
+ return self.client.forward_message(self.id, from_chat_id, message_id)
684
+
685
+ def copy_message(self,
686
+ from_chat_id: Union[int,
687
+ str],
688
+ message_id: int,
689
+ caption: Optional[str] = None,
690
+ parse_mode: Optional[str] = None,
691
+ reply_markup: Union[MenuKeyboardMarkup,
692
+ InlineKeyboardMarkup] = None) -> 'Message':
693
+ """Copy a message from another chat"""
694
+ return self.client.copy_message(
695
+ self.id,
696
+ from_chat_id,
697
+ message_id,
698
+ caption,
699
+ parse_mode,
700
+ reply_markup)
701
+
702
+ def send_audio(self,
703
+ audio: Union[str,
704
+ bytes,
705
+ InputFile],
706
+ caption: Optional[str] = None,
707
+ parse_mode: Optional[str] = None,
708
+ duration: Optional[int] = None,
709
+ performer: Optional[str] = None,
710
+ title: Optional[str] = None,
711
+ reply_markup: Union[MenuKeyboardMarkup,
712
+ InlineKeyboardMarkup] = None) -> 'Message':
713
+ """Send an audio file"""
714
+ return self.client.send_audio(
715
+ self.id,
716
+ audio,
717
+ caption,
718
+ parse_mode,
719
+ duration,
720
+ performer,
721
+ title,
722
+ reply_markup)
723
+
724
+ def send_document(self,
725
+ document: Union[str,
726
+ bytes,
727
+ InputFile],
728
+ caption: Optional[str] = None,
729
+ parse_mode: Optional[str] = None,
730
+ reply_markup: Union[MenuKeyboardMarkup,
731
+ InlineKeyboardMarkup] = None) -> 'Message':
732
+ """Send a document"""
733
+ return self.client.send_document(
734
+ self.id, document, caption, parse_mode, reply_markup)
735
+
736
+ def send_video(self,
737
+ video: Union[str,
738
+ bytes,
739
+ InputFile],
740
+ caption: Optional[str] = None,
741
+ parse_mode: Optional[str] = None,
742
+ duration: Optional[int] = None,
743
+ width: Optional[int] = None,
744
+ height: Optional[int] = None,
745
+ reply_markup: Union[MenuKeyboardMarkup,
746
+ InlineKeyboardMarkup] = None) -> 'Message':
747
+ """Send a video"""
748
+ return self.client.send_video(
749
+ self.id,
750
+ video,
751
+ caption,
752
+ parse_mode,
753
+ duration,
754
+ width,
755
+ height,
756
+ reply_markup)
757
+
758
+ def send_animation(self,
759
+ animation: Union[str,
760
+ bytes,
761
+ InputFile],
762
+ caption: Optional[str] = None,
763
+ parse_mode: Optional[str] = None,
764
+ duration: Optional[int] = None,
765
+ width: Optional[int] = None,
766
+ height: Optional[int] = None,
767
+ reply_markup: Union[MenuKeyboardMarkup,
768
+ InlineKeyboardMarkup] = None) -> 'Message':
769
+ """Send an animation"""
770
+ return self.client.send_animation(
771
+ self.id,
772
+ animation,
773
+ caption,
774
+ parse_mode,
775
+ duration,
776
+ width,
777
+ height,
778
+ reply_markup)
779
+
780
+ def send_voice(self,
781
+ voice: Union[str,
782
+ bytes,
783
+ InputFile],
784
+ caption: Optional[str] = None,
785
+ parse_mode: Optional[str] = None,
786
+ duration: Optional[int] = None,
787
+ reply_markup: Union[MenuKeyboardMarkup,
788
+ InlineKeyboardMarkup] = None) -> 'Message':
789
+ """Send a voice message"""
790
+ return self.client.send_voice(
791
+ self.id,
792
+ voice,
793
+ caption,
794
+ parse_mode,
795
+ duration,
796
+ reply_markup)
797
+
798
+ def send_media_group(self,
799
+ chat_id: Union[int,
800
+ str],
801
+ media: List[Dict],
802
+ reply_to_message: Union['Message',
803
+ int,
804
+ str] = None) -> List['Message']:
805
+ """Send a group of photos, videos, documents or audios as an album"""
806
+ data = {
807
+ 'chat_id': chat_id,
808
+ 'media': media,
809
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
810
+ reply_to_message,
811
+ Message) else reply_to_message}
812
+ response = self._make_request('POST', 'sendMediaGroup', json=data)
813
+ return [Message(self, msg) for msg in response]
814
+
815
+ def send_location(self,
816
+ latitude: float,
817
+ longitude: float,
818
+ live_period: Optional[int] = None,
819
+ reply_markup: Union[MenuKeyboardMarkup,
820
+ InlineKeyboardMarkup] = None) -> 'Message':
821
+ """Send a location"""
822
+ return self.client.send_location(
823
+ self.id, latitude, longitude, live_period, reply_markup)
824
+
825
+ def send_contact(self,
826
+ phone_number: str,
827
+ first_name: str,
828
+ last_name: Optional[str] = None,
829
+ reply_markup: Union[MenuKeyboardMarkup,
830
+ InlineKeyboardMarkup] = None) -> 'Message':
831
+ """Send a contact"""
832
+ return self.client.send_contact(
833
+ self.id,
834
+ phone_number,
835
+ first_name,
836
+ last_name,
837
+ reply_markup)
838
+
839
+ def send_invoice(self,
840
+ title: str,
841
+ description: str,
842
+ payload: str,
843
+ provider_token: str,
844
+ prices: list,
845
+ photo_url: Optional[str] = None,
846
+ reply_to_message: Union[int,
847
+ str,
848
+ 'Message'] = None,
849
+ reply_markup: Union[MenuKeyboardMarkup | InlineKeyboardMarkup] = None):
850
+ return self.client.send_invoice(
851
+ self.id,
852
+ title,
853
+ description,
854
+ payload,
855
+ provider_token,
856
+ prices,
857
+ photo_url,
858
+ reply_to_message,
859
+ reply_markup)
860
+
861
+ def send_action(self, action: str, how_many_times = 1) -> bool:
862
+ """Send a chat action"""
863
+ return self.client.send_chat_action(self.id, action, how_many_times)
864
+
865
+ def banChatMember(
866
+ self,
867
+ user_id: int,
868
+ until_date: Optional[int] = None) -> bool:
869
+ """Ban a user from the chat"""
870
+ data = {
871
+ 'chat_id': self.id,
872
+ 'user_id': user_id,
873
+ 'until_date': until_date
874
+ }
875
+ response = self.client._make_request(
876
+ 'POST', 'banChatMember', data=data)
877
+ return response.get('ok', False)
878
+
879
+ def unbanChatMember(
880
+ self,
881
+ user_id: int,
882
+ only_if_banned: bool = False) -> bool:
883
+ """Unban a previously banned user from the chat"""
884
+ data = {
885
+ 'chat_id': self.id,
886
+ 'user_id': user_id,
887
+ 'only_if_banned': only_if_banned
888
+ }
889
+ response = self.client._make_request(
890
+ 'POST', 'unbanChatMember', data=data)
891
+ return response.get('ok', False)
892
+
893
+ def promoteChatMember(
894
+ self,
895
+ user_id: int,
896
+ can_change_info: bool = None,
897
+ can_post_messages: bool = None,
898
+ can_edit_messages: bool = None,
899
+ can_delete_messages: bool = None,
900
+ can_manage_video_chats: bool = None,
901
+ can_invite_users: bool = None,
902
+ can_restrict_members: bool = None) -> bool:
903
+ """Promote or demote a chat member"""
904
+ data = {
905
+ 'chat_id': self.id,
906
+ 'user_id': user_id,
907
+ 'can_change_info': can_change_info,
908
+ 'can_post_messages': can_post_messages,
909
+ 'can_edit_messages': can_edit_messages,
910
+ 'can_delete_messages': can_delete_messages,
911
+ 'can_manage_video_chats': can_manage_video_chats,
912
+ 'can_invite_users': can_invite_users,
913
+ 'can_restrict_members': can_restrict_members
914
+ }
915
+ response = self.client._make_request(
916
+ 'POST', 'promoteChatMember', data=data)
917
+ return response.get('ok', False)
918
+
919
+ def setChatPhoto(self, photo: Union[str, bytes, InputFile]) -> bool:
920
+ """Set a new chat photo"""
921
+ files = None
922
+ data = {'chat_id': self.id}
923
+
924
+ if isinstance(photo, (bytes, InputFile)) or hasattr(photo, 'read'):
925
+ files = {
926
+ 'photo': photo if not isinstance(
927
+ photo, InputFile) else photo.file}
928
+ else:
929
+ data['photo'] = photo
930
+
931
+ response = self.client._make_request(
932
+ 'POST', 'setChatPhoto', data=data, files=files)
933
+ return response.get('ok', False)
934
+
935
+ def leaveChat(self) -> bool:
936
+ """Leave the chat"""
937
+ data = {'chat_id': self.id}
938
+ response = self.client._make_request('POST', 'leaveChat', data=data)
939
+ return response.get('ok', False)
940
+
941
+ def getChat(self) -> 'Chat':
942
+ """Get up to date information about the chat"""
943
+ data = {'chat_id': self.id}
944
+ response = self.client._make_request('GET', 'getChat', data=data)
945
+ return Chat(self.client, response)
946
+
947
+ def getChatMembersCount(self) -> int:
948
+ """Get the number of members in the chat"""
949
+ data = {'chat_id': self.id}
950
+ response = self.client._make_request(
951
+ 'POST', 'getChatMembersCount', data=data)
952
+ return response.get('result', 0)
953
+
954
+ def pinChatMessage(
955
+ self,
956
+ message_id: int,
957
+ disable_notification: bool = False) -> bool:
958
+ """Pin a message in the chat"""
959
+ data = {
960
+ 'chat_id': self.id,
961
+ 'message_id': message_id,
962
+ 'disable_notification': disable_notification
963
+ }
964
+ response = self.client._make_request(
965
+ 'POST', 'pinChatMessage', data=data)
966
+ return response.get('ok', False)
967
+
968
+ def unPinChatMessage(self, message_id: int) -> bool:
969
+ """Unpin a message in the chat"""
970
+ data = {
971
+ 'chat_id': self.id,
972
+ 'message_id': message_id
973
+ }
974
+ response = self.client._make_request(
975
+ 'POST', 'unpinChatMessage', data=data)
976
+ return response.get('ok', False)
977
+
978
+ def unpinAllChatMessages(self) -> bool:
979
+ """Unpin all messages in the chat"""
980
+ data = {'chat_id': self.id}
981
+ response = self.client._make_request(
982
+ 'POST', 'unpinAllChatMessages', data=data)
983
+ return response.get('ok', False)
984
+
985
+ def setChatTitle(self, title: str) -> bool:
986
+ """Change the title of the chat"""
987
+ data = {
988
+ 'chat_id': self.id,
989
+ 'title': title
990
+ }
991
+ response = self.client._make_request('POST', 'setChatTitle', data=data)
992
+ return response.get('ok', False)
993
+
994
+ def setChatDescription(self, description: str) -> bool:
995
+ """Change the description of the chat"""
996
+ data = {
997
+ 'chat_id': self.id,
998
+ 'description': description
999
+ }
1000
+ response = self.client._make_request(
1001
+ 'POST', 'setChatDescription', data=data)
1002
+ return response.get('ok', False)
1003
+
1004
+ def deleteChatPhoto(self) -> bool:
1005
+ """Delete the chat photo"""
1006
+ data = {'chat_id': self.id}
1007
+ response = self.client._make_request(
1008
+ 'POST', 'deleteChatPhoto', data=data)
1009
+ return response.get('ok', False)
1010
+
1011
+ def createChatInviteLink(self) -> str:
1012
+ """Create an invite link for the chat"""
1013
+ data = {'chat_id': self.id}
1014
+ response = self.client._make_request(
1015
+ 'POST', 'createChatInviteLink', data=data)
1016
+ return response.get('result', {}).get('invite_link')
1017
+
1018
+ def revokeChatInviteLink(self, invite_link: str) -> bool:
1019
+ """Revoke an invite link for the chat"""
1020
+ data = {
1021
+ 'chat_id': self.id,
1022
+ 'invite_link': invite_link
1023
+ }
1024
+ response = self.client._make_request(
1025
+ 'POST', 'revokeChatInviteLink', data=data)
1026
+ return response.get('ok', False)
1027
+
1028
+ def exportChatInviteLink(self) -> str:
1029
+ """Generate a new invite link for the chat"""
1030
+ data = {'chat_id': self.id}
1031
+ response = self.client._make_request(
1032
+ 'POST', 'exportChatInviteLink', data=data)
1033
+ return response.get('result')
1034
+
1035
+
1036
+ class User:
1037
+ """Represents a Bale user"""
1038
+
1039
+ def __init__(self, client: 'Client', data: Dict[str, Any]):
1040
+ if not data.get('ok'):
1041
+ raise BaleException(
1042
+ f"API request failed: {traceback.format_exc()}")
1043
+ self.client = client
1044
+ result = data.get('result', {})
1045
+ self.data = data
1046
+ self.ok = data.get('ok')
1047
+ self.id = result.get('id')
1048
+ self.is_bot = result.get('is_bot')
1049
+ self.first_name = result.get('first_name')
1050
+ self.last_name = result.get('last_name')
1051
+ self.username = result.get('username')
1052
+
1053
+ def set_state(self, state: str) -> None:
1054
+ """Set the state for a chat or user"""
1055
+ self.client.states[str(self.id)] = state
1056
+
1057
+ def get_state(self) -> str | None:
1058
+ """Get the state for a chat or user"""
1059
+ return self.client.states.get(str(self.id))
1060
+
1061
+ def del_state(self) -> None:
1062
+ """Delete the state for a chat or user"""
1063
+ self.client.states.pop(str(self.id), None)
1064
+
1065
+ def send_message(self,
1066
+ text: str,
1067
+ parse_mode: Optional[str] = None,
1068
+ reply_markup: Union[MenuKeyboardMarkup,
1069
+ InlineKeyboardMarkup] = None) -> 'Message':
1070
+ """Send a message to this user"""
1071
+ return self.client.send_message(
1072
+ self.id, text, parse_mode, reply_markup)
1073
+
1074
+ def send_photo(self,
1075
+ photo: Union[str,
1076
+ bytes,
1077
+ InputFile],
1078
+ caption: Optional[str] = None,
1079
+ parse_mode: Optional[str] = None,
1080
+ reply_markup: Union[MenuKeyboardMarkup,
1081
+ InlineKeyboardMarkup] = None) -> 'Message':
1082
+ """Send a photo to a chat"""
1083
+ return self.client.send_photo(
1084
+ self.id, photo, caption, parse_mode, reply_markup)
1085
+
1086
+ def forward_message(
1087
+ self, from_chat_id: Union[int, str], message_id: int) -> 'Message':
1088
+ """Forward a message to this user"""
1089
+ self.client.forward_message(self.id, from_chat_id, message_id)
1090
+
1091
+ def copy_message(self,
1092
+ from_chat_id: Union[int,
1093
+ str],
1094
+ message_id: int) -> 'Message':
1095
+ """Copy a message to this user"""
1096
+ self.client.copy_message(self.id, from_chat_id, message_id)
1097
+
1098
+ def send_audio(self,
1099
+ audio: Union[str,
1100
+ bytes,
1101
+ InputFile],
1102
+ caption: Optional[str] = None,
1103
+ parse_mode: Optional[str] = None,
1104
+ reply_markup: Union[MenuKeyboardMarkup,
1105
+ InlineKeyboardMarkup] = None,
1106
+ reply_to_message: Union[str,
1107
+ int,
1108
+ 'Message'] = None) -> 'Message':
1109
+ """Send an audio file to this user"""
1110
+ self.client.send_audio(
1111
+ self.id,
1112
+ audio,
1113
+ caption,
1114
+ parse_mode,
1115
+ reply_markup,
1116
+ reply_to_message)
1117
+
1118
+ def send_document(self,
1119
+ document: Union[str,
1120
+ bytes,
1121
+ InputFile],
1122
+ caption: Optional[str] = None,
1123
+ parse_mode: Optional[str] = None,
1124
+ reply_markup: Union[MenuKeyboardMarkup,
1125
+ InlineKeyboardMarkup] = None,
1126
+ reply_to_message: Union[str,
1127
+ int,
1128
+ 'Message'] = None) -> 'Message':
1129
+ """Send a document to this user"""
1130
+ self.client.send_document(
1131
+ self.id,
1132
+ document,
1133
+ caption,
1134
+ parse_mode,
1135
+ reply_markup,
1136
+ reply_markup)
1137
+
1138
+ def send_video(self,
1139
+ video: Union[str,
1140
+ bytes,
1141
+ InputFile],
1142
+ caption: Optional[str] = None,
1143
+ parse_mode: Optional[str] = None,
1144
+ reply_markup: Union[MenuKeyboardMarkup,
1145
+ InlineKeyboardMarkup] = None,
1146
+ reply_to_message: Union[str,
1147
+ int,
1148
+ 'Message'] = None) -> 'Message':
1149
+ """Send a video to this user"""
1150
+ self.client.send_video(
1151
+ self.id,
1152
+ video,
1153
+ caption,
1154
+ parse_mode,
1155
+ reply_markup,
1156
+ reply_to_message)
1157
+
1158
+ def send_animation(self,
1159
+ animation: Union[str,
1160
+ bytes,
1161
+ InputFile],
1162
+ caption: Optional[str] = None,
1163
+ parse_mode: Optional[str] = None,
1164
+ reply_markup: Union[MenuKeyboardMarkup,
1165
+ InlineKeyboardMarkup] = None,
1166
+ reply_to_message: Union[int,
1167
+ str,
1168
+ 'Message'] = None) -> 'Message':
1169
+ """Send an animation to this user"""
1170
+ return self.client.send_animation(
1171
+ self.id,
1172
+ animation,
1173
+ caption,
1174
+ parse_mode,
1175
+ reply_markup,
1176
+ reply_to_message)
1177
+
1178
+ def send_voice(self,
1179
+ voice: Union[str,
1180
+ bytes,
1181
+ InputFile],
1182
+ caption: Optional[str] = None,
1183
+ parse_mode: Optional[str] = None,
1184
+ reply_markup: Union[MenuKeyboardMarkup,
1185
+ InlineKeyboardMarkup] = None,
1186
+ reply_to_message: Union[int,
1187
+ str,
1188
+ 'Message'] = None) -> 'Message':
1189
+ """Send a voice message to this user"""
1190
+ return self.client.send_voice(
1191
+ self.id,
1192
+ voice,
1193
+ caption,
1194
+ parse_mode,
1195
+ reply_markup,
1196
+ reply_to_message)
1197
+
1198
+ def send_media_group(self,
1199
+ chat_id: Union[int,
1200
+ str],
1201
+ media: List[Dict],
1202
+ reply_to_message: Union['Message',
1203
+ int,
1204
+ str] = None) -> List['Message']:
1205
+ """Send a group of photos, videos, documents or audios as an album"""
1206
+ return self.client.send_media_group(chat_id, media, reply_to_message)
1207
+
1208
+ def send_location(self,
1209
+ latitude: float,
1210
+ longitude: float,
1211
+ reply_markup: Union[MenuKeyboardMarkup,
1212
+ InlineKeyboardMarkup] = None,
1213
+ reply_to_message: Union[str,
1214
+ int,
1215
+ 'Message'] = None) -> 'Message':
1216
+ """Send a location to this user"""
1217
+ return self.send_location(
1218
+ latitude,
1219
+ longitude,
1220
+ reply_markup,
1221
+ reply_to_message)
1222
+
1223
+ def send_contact(self,
1224
+ phone_number: str,
1225
+ first_name: str,
1226
+ last_name: Optional[str] = None,
1227
+ reply_markup: Union[MenuKeyboardMarkup,
1228
+ InlineKeyboardMarkup] = None,
1229
+ reply_to_message: Union[str,
1230
+ int,
1231
+ 'Message'] = None) -> 'Message':
1232
+ """Send a contact to this user"""
1233
+ return self.client.send_contact(
1234
+ self.id,
1235
+ phone_number,
1236
+ first_name,
1237
+ last_name,
1238
+ reply_markup,
1239
+ reply_to_message)
1240
+
1241
+ def send_invoice(self,
1242
+ title: str,
1243
+ description: str,
1244
+ payload: str,
1245
+ provider_token: str,
1246
+ prices: list,
1247
+ photo_url: Optional[str] = None,
1248
+ reply_to_message: Union[int,
1249
+ str,
1250
+ 'Message'] = None,
1251
+ reply_markup: Union[MenuKeyboardMarkup | InlineKeyboardMarkup] = None):
1252
+ return self.client.send_invoice(
1253
+ self.id,
1254
+ title,
1255
+ description,
1256
+ payload,
1257
+ provider_token,
1258
+ prices,
1259
+ photo_url,
1260
+ reply_to_message,
1261
+ reply_markup)
1262
+ def send_action(self, action: str, how_many_times: int = 1):
1263
+ """Send a chat action to this user"""
1264
+ return self.client.send_chat_action(self.id, action, how_many_times)
1265
+
1266
+
1267
+ class Message:
1268
+ """Represents a message in Bale"""
1269
+
1270
+ def __init__(self, client: 'Client', data: Dict[str, Any]):
1271
+ if not data.get('ok'):
1272
+ raise BaleException(
1273
+ f"API request failed: {traceback.format_exc()}")
1274
+ self.client = client
1275
+ self.ok = data.get('ok')
1276
+ result = data.get('result', {})
1277
+ self.json_result = result
1278
+
1279
+ self.message_id = self.id = result.get('message_id')
1280
+ self.from_user = self.author = User(
1281
+ client, {'ok': True, 'result': result.get('from', {})})
1282
+ self.date = result.get('date')
1283
+ self.chat = Chat(
1284
+ client, {
1285
+ 'ok': True, 'result': result.get(
1286
+ 'chat', {})})
1287
+ self.text = result.get('text')
1288
+ self.caption = result.get('caption')
1289
+ self.document = Document(result.get('document'))
1290
+ self.photo = Document(result.get('photo'))
1291
+ self.video = Document(result.get('video'))
1292
+ self.audio = Document(result.get('audio'))
1293
+ self.voice = Voice(result.get('voice'))
1294
+ self.animation = result.get('animation')
1295
+ self.contact = Contact(result.get('contact'))
1296
+ self.location = Location(result.get('location'))
1297
+ self.forward_from = User(client, {'ok': True, 'result': result.get(
1298
+ 'forward_from', {})}) if result.get('forward_from') else None
1299
+ self.forward_from_message_id = result.get('forward_from_message_id')
1300
+ self.invoice = Invoice(result.get('invoice'))
1301
+ self.reply_to_message = Message(client, {'ok': True, 'result': result.get(
1302
+ 'reply_to_message', {})}) if result.get('reply_to_message') else None
1303
+ self.reply = self.reply_message
1304
+ self.send = lambda text, parse_mode=None, reply_markup=None: self.client.send_message(
1305
+ self.chat.id, text, parse_mode, reply_markup, reply_to_message=self)
1306
+
1307
+ self.command = None
1308
+ self.args = None
1309
+ txt = self.text.split(' ')
1310
+
1311
+ self.command = txt[0]
1312
+ self.has_slash_command = self.command.startswith('/')
1313
+ self.args = txt[1:]
1314
+
1315
+ self.start = self.command == '/start'
1316
+
1317
+ def edit(self,
1318
+ text: str,
1319
+ parse_mode: Optional[str] = None,
1320
+ reply_markup: Union[MenuKeyboardMarkup,
1321
+ InlineKeyboardMarkup] = None) -> 'Message':
1322
+ """Edit this message"""
1323
+ return self.client.edit_message(
1324
+ self.chat.id,
1325
+ self.message_id,
1326
+ text,
1327
+ parse_mode,
1328
+ reply_markup)
1329
+
1330
+ def delete(self) -> bool:
1331
+ """Delete this message"""
1332
+ return self.client.delete_message(self.chat.id, self.message_id)
1333
+
1334
+ def reply_message(self,
1335
+ text: str,
1336
+ parse_mode: Optional[str] = None,
1337
+ reply_markup: Union[MenuKeyboardMarkup,
1338
+ InlineKeyboardMarkup] = None) -> 'Message':
1339
+ """Send a message to this user"""
1340
+ return self.client.send_message(
1341
+ self.chat.id,
1342
+ text,
1343
+ parse_mode,
1344
+ reply_markup,
1345
+ reply_to_message=self)
1346
+
1347
+ def reply_photo(self,
1348
+ photo: Union[str,
1349
+ bytes,
1350
+ InputFile],
1351
+ caption: Optional[str] = None,
1352
+ parse_mode: Optional[str] = None,
1353
+ reply_markup: Union[MenuKeyboardMarkup,
1354
+ InlineKeyboardMarkup] = None) -> 'Message':
1355
+ """Send a photo to a chat"""
1356
+ return self.client.send_photo(
1357
+ self.chat.id,
1358
+ photo,
1359
+ caption,
1360
+ parse_mode,
1361
+ reply_markup,
1362
+ reply_to_message=self)
1363
+
1364
+ def reply_audio(self,
1365
+ audio: Union[str,
1366
+ bytes,
1367
+ InputFile],
1368
+ caption: Optional[str] = None,
1369
+ parse_mode: Optional[str] = None,
1370
+ reply_markup: Union[MenuKeyboardMarkup,
1371
+ InlineKeyboardMarkup] = None) -> 'Message':
1372
+ """Send an audio file to this user"""
1373
+ self.client.send_audio(
1374
+ self.chat.id,
1375
+ audio,
1376
+ caption,
1377
+ parse_mode,
1378
+ reply_markup,
1379
+ reply_to_message=self)
1380
+
1381
+ def reply_document(self,
1382
+ document: Union[str,
1383
+ bytes,
1384
+ InputFile],
1385
+ caption: Optional[str] = None,
1386
+ parse_mode: Optional[str] = None,
1387
+ reply_markup: Union[MenuKeyboardMarkup,
1388
+ InlineKeyboardMarkup] = None) -> 'Message':
1389
+ """Send a document to this user"""
1390
+ self.client.send_document(
1391
+ self.chat.id,
1392
+ document,
1393
+ caption,
1394
+ parse_mode,
1395
+ reply_markup,
1396
+ reply_markup,
1397
+ reply_to_message=self)
1398
+
1399
+ def reply_video(self,
1400
+ video: Union[str,
1401
+ bytes,
1402
+ InputFile],
1403
+ caption: Optional[str] = None,
1404
+ parse_mode: Optional[str] = None,
1405
+ reply_markup: Union[MenuKeyboardMarkup,
1406
+ InlineKeyboardMarkup] = None) -> 'Message':
1407
+ """Send a video to this user"""
1408
+ self.client.send_video(
1409
+ self.chat.id,
1410
+ video,
1411
+ caption,
1412
+ parse_mode,
1413
+ reply_markup,
1414
+ reply_to_message=self)
1415
+
1416
+ def reply_animation(self,
1417
+ animation: Union[str,
1418
+ bytes,
1419
+ InputFile],
1420
+ caption: Optional[str] = None,
1421
+ parse_mode: Optional[str] = None,
1422
+ reply_markup: Union[MenuKeyboardMarkup,
1423
+ InlineKeyboardMarkup] = None) -> 'Message':
1424
+ """Send an animation to this user"""
1425
+ return self.client.send_animation(
1426
+ self.chat.id,
1427
+ animation,
1428
+ caption,
1429
+ parse_mode,
1430
+ reply_markup,
1431
+ reply_to_message=self)
1432
+
1433
+ def reply_voice(self,
1434
+ voice: Union[str,
1435
+ bytes,
1436
+ InputFile],
1437
+ caption: Optional[str] = None,
1438
+ parse_mode: Optional[str] = None,
1439
+ reply_markup: Union[MenuKeyboardMarkup,
1440
+ InlineKeyboardMarkup] = None) -> 'Message':
1441
+ """Send a voice message to this user"""
1442
+ return self.client.send_voice(
1443
+ self.chat.id,
1444
+ voice,
1445
+ caption,
1446
+ parse_mode,
1447
+ reply_markup,
1448
+ reply_to_message=self)
1449
+
1450
+ def reply_media_group(self,
1451
+ media: List[Dict],
1452
+ reply_to_message: Union['Message',
1453
+ int,
1454
+ str] = None) -> List['Message']:
1455
+ """Send a group of photos, videos, documents or audios as an album"""
1456
+ return self.client.send_media_group(
1457
+ self.chat.id, media, reply_to_message=self)
1458
+
1459
+ def reply_location(self,
1460
+ latitude: float,
1461
+ longitude: float,
1462
+ reply_markup: Union[MenuKeyboardMarkup,
1463
+ InlineKeyboardMarkup] = None) -> 'Message':
1464
+ """Send a location to this user"""
1465
+ return self.client.send_location(
1466
+ self.chat.id,
1467
+ latitude,
1468
+ longitude,
1469
+ reply_markup,
1470
+ reply_to_message=self)
1471
+
1472
+ def reply_contact(self,
1473
+ phone_number: str,
1474
+ first_name: str,
1475
+ last_name: Optional[str] = None,
1476
+ reply_markup: Union[MenuKeyboardMarkup,
1477
+ InlineKeyboardMarkup] = None,
1478
+ reply_to_message: Union[str,
1479
+ int,
1480
+ 'Message'] = None) -> 'Message':
1481
+ """Send a contact to this user"""
1482
+ return self.client.send_contact(
1483
+ self.chat.id,
1484
+ phone_number,
1485
+ first_name,
1486
+ last_name,
1487
+ reply_markup,
1488
+ reply_to_message)
1489
+
1490
+ def reply_invoice(self,
1491
+ title: str,
1492
+ description: str,
1493
+ payload: str,
1494
+ provider_token: str,
1495
+ prices: list,
1496
+ photo_url: Optional[str] = None,
1497
+ reply_markup: Union[MenuKeyboardMarkup | InlineKeyboardMarkup] = None):
1498
+ return self.client.send_invoice(
1499
+ self.chat.id,
1500
+ title,
1501
+ description,
1502
+ payload,
1503
+ provider_token,
1504
+ prices,
1505
+ photo_url,
1506
+ self,
1507
+ reply_markup)
1508
+
1509
+
1510
+ class Client:
1511
+ """Main client class for interacting with Bale API"""
1512
+
1513
+ def __init__(
1514
+ self,
1515
+ token: str,
1516
+ session: str = 'https://tapi.bale.ai',
1517
+ database_name='database.db',
1518
+ auto_log_start_message: bool = True,
1519
+ ):
1520
+ self.token = token
1521
+ self.session = session
1522
+ self.states = {}
1523
+ self.database_name = database_name
1524
+ self.auto_log_start_message = auto_log_start_message
1525
+ self._base_url = f"{session}/bot{token}"
1526
+ self._session = requests.Session()
1527
+ self._message_handler = None
1528
+ self._message_edit_handler = None
1529
+ self._callback_handler = None
1530
+ self._member_leave_handler = None
1531
+ self._member_join_handler = None
1532
+ self._threads = []
1533
+
1534
+ def set_state(self,
1535
+ chat_or_user_id: Union[Chat,
1536
+ User,
1537
+ int,
1538
+ str],
1539
+ state: str) -> None:
1540
+ """Set the state for a chat or user"""
1541
+ if isinstance(chat_or_user_id, (Chat, User)):
1542
+ chat_or_user_id = chat_or_user_id.id
1543
+ self.states[str(chat_or_user_id)] = state
1544
+
1545
+ def get_state(self,
1546
+ chat_or_user_id: Union[Chat,
1547
+ User,
1548
+ int,
1549
+ str]) -> str | None:
1550
+ """Get the state for a chat or user"""
1551
+ if isinstance(chat_or_user_id, (Chat, User)):
1552
+ chat_or_user_id = chat_or_user_id.id
1553
+ return self.states.get(str(chat_or_user_id))
1554
+
1555
+ def del_state(self, chat_or_user_id: Union[Chat, User, int, str]) -> None:
1556
+ """Delete the state for a chat or user"""
1557
+ if isinstance(chat_or_user_id, (Chat, User)):
1558
+ chat_or_user_id = chat_or_user_id.id
1559
+ self.states.pop(str(chat_or_user_id), None)
1560
+
1561
+ @property
1562
+ def database(self) -> DataBase:
1563
+ """Get the database name"""
1564
+ db = DataBase(self.database_name)
1565
+ return db
1566
+
1567
+ def get_chat(self, chat_id: int) -> Optional[Dict]:
1568
+ """Get chat information from database"""
1569
+ conn = sqlite3.connect(self.database)
1570
+ cursor = conn.cursor()
1571
+ cursor.execute('SELECT * FROM chats WHERE chat_id = ?', (chat_id,))
1572
+ chat = cursor.fetchone()
1573
+ conn.close()
1574
+ if chat:
1575
+ return {
1576
+ 'chat_id': chat[0],
1577
+ 'type': chat[1],
1578
+ 'title': chat[2],
1579
+ 'created_at': chat[3]
1580
+ }
1581
+ return None
1582
+
1583
+ def _make_request(self, method: str, endpoint: str,
1584
+ **kwargs) -> Dict[str, Any]:
1585
+ """Make an HTTP request to Bale API"""
1586
+ url = f"{self._base_url}/{endpoint}"
1587
+ response = self._session.request(method, url, **kwargs)
1588
+ response_data = response.json()
1589
+ if not response_data.get('ok'):
1590
+ raise BaleException(
1591
+ response_data['error_code'],
1592
+ response_data['description'])
1593
+ return response_data
1594
+
1595
+ def __del__(self):
1596
+ if hasattr(self, '_session'):
1597
+ self._session.close()
1598
+
1599
+ def get_me(self) -> User:
1600
+ """Get information about the bot"""
1601
+ data = self._make_request('GET', 'getMe')
1602
+ return User(self, data)
1603
+
1604
+ def set_webhook(self, url: str, certificate: Optional[str] = None,
1605
+ max_connections: Optional[int] = None) -> bool:
1606
+ """Set webhook for getting updates"""
1607
+ data = {
1608
+ 'url': url,
1609
+ 'certificate': certificate,
1610
+ 'max_connections': max_connections
1611
+ }
1612
+ return self._make_request('POST', 'setWebhook', json=data)
1613
+
1614
+ def get_webhook_info(self) -> Dict[str, Any]:
1615
+ """Get current webhook status"""
1616
+ return self._make_request('GET', 'getWebhookInfo')
1617
+
1618
+ def send_message(self,
1619
+ chat_id: Union[int,
1620
+ str],
1621
+ text: str,
1622
+ parse_mode: Optional[str] = None,
1623
+ reply_markup: Union[MenuKeyboardMarkup,
1624
+ InlineKeyboardMarkup] = None,
1625
+ reply_to_message: Union[Message,
1626
+ int,
1627
+ str] = None) -> Message:
1628
+ """Send a message to a chat"""
1629
+
1630
+ text = str(text)
1631
+
1632
+ data = {
1633
+ 'chat_id': chat_id,
1634
+ 'text': text,
1635
+ 'parse_mode': parse_mode,
1636
+ 'reply_markup': reply_markup.keyboard if reply_markup else None,
1637
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1638
+ reply_to_message,
1639
+ Message) else reply_to_message}
1640
+ response = self._make_request('POST', 'sendMessage', json=data)
1641
+ return Message(self, response)
1642
+
1643
+ def forward_message(self, chat_id: Union[int, str],
1644
+ from_chat_id: Union[int, str],
1645
+ message_id: int) -> Message:
1646
+ """Forward a message from one chat to another"""
1647
+ data = {
1648
+ 'chat_id': chat_id,
1649
+ 'from_chat_id': from_chat_id,
1650
+ 'message_id': message_id
1651
+ }
1652
+ response = self._make_request('POST', 'forwardMessage', json=data)
1653
+ return Message(self, response)
1654
+
1655
+ def send_photo(self,
1656
+ chat_id: Union[int,
1657
+ str],
1658
+ photo: Union[str,
1659
+ bytes,
1660
+ InputFile],
1661
+ caption: Optional[str] = None,
1662
+ parse_mode: Optional[str] = None,
1663
+ reply_markup: Union[MenuKeyboardMarkup,
1664
+ InlineKeyboardMarkup] = None,
1665
+ reply_to_message: Union[Message,
1666
+ int,
1667
+ str] = None) -> Message:
1668
+ """Send a photo to a chat"""
1669
+ files = None
1670
+ data = {
1671
+ 'chat_id': chat_id,
1672
+ 'caption': caption,
1673
+ 'parse_mode': parse_mode,
1674
+ 'reply_markup': reply_markup.keyboard if reply_markup else None,
1675
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1676
+ reply_to_message,
1677
+ Message) else reply_to_message}
1678
+
1679
+ if isinstance(photo, (bytes, InputFile)) or hasattr(photo, 'read'):
1680
+ files = {
1681
+ 'photo': photo if not isinstance(
1682
+ photo, InputFile) else photo.file}
1683
+ else:
1684
+ data['photo'] = photo
1685
+
1686
+ response = self._make_request(
1687
+ 'POST', 'sendPhoto', data=data, files=files)
1688
+ return Message(self, response)
1689
+
1690
+ def delete_message(self, chat_id: Union[int, str],
1691
+ message_id: int) -> bool:
1692
+ """Delete a message from a chat"""
1693
+ data = {
1694
+ 'chat_id': chat_id,
1695
+ 'message_id': message_id
1696
+ }
1697
+ return self._make_request('POST', 'deleteMessage', json=data)
1698
+
1699
+ def get_user(self, user_id: Union[int, str]) -> User:
1700
+ """Get information about a user"""
1701
+ data = self._make_request('POST', 'getChat', json={'chat_id': user_id})
1702
+ return User(self, data)
1703
+
1704
+ def edit_message(self,
1705
+ chat_id: Union[int,
1706
+ str],
1707
+ message_id: int,
1708
+ text: str,
1709
+ parse_mode: Optional[str] = None,
1710
+ reply_markup: Union[MenuKeyboardMarkup,
1711
+ InlineKeyboardMarkup] = None) -> Message:
1712
+ """Edit a message in a chat"""
1713
+ data = {
1714
+ 'chat_id': chat_id,
1715
+ 'message_id': message_id,
1716
+ 'text': text,
1717
+ 'parse_mode': parse_mode,
1718
+ 'reply_markup': reply_markup.keyboard if reply_markup else None
1719
+ }
1720
+ response = self._make_request('POST', 'editMessageText', json=data)
1721
+ return Message(self, response)
1722
+
1723
+ def get_chat(self, chat_id: Union[int, str]) -> Chat:
1724
+ """Get information about a chat"""
1725
+ data = self._make_request('POST', 'getChat', json={'chat_id': chat_id})
1726
+ return Chat(self, data)
1727
+
1728
+ def send_audio(self,
1729
+ chat_id: Union[int,
1730
+ str],
1731
+ audio,
1732
+ caption: Optional[str] = None,
1733
+ parse_mode: Optional[str] = None,
1734
+ reply_markup: Union[MenuKeyboardMarkup,
1735
+ InlineKeyboardMarkup] = None,
1736
+ reply_to_message: Union[Message,
1737
+ int,
1738
+ str] = None) -> Message:
1739
+ """Send an audio file"""
1740
+ files = None
1741
+ data = {
1742
+ 'chat_id': chat_id,
1743
+ 'caption': caption,
1744
+ 'parse_mode': parse_mode,
1745
+ 'reply_markup': reply_markup.keyboard if reply_markup else None,
1746
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1747
+ reply_to_message,
1748
+ Message) else reply_to_message}
1749
+ if isinstance(audio, (bytes, InputFile)) or hasattr(audio, 'read'):
1750
+ files = {
1751
+ 'audio': audio if not isinstance(
1752
+ audio, InputFile) else audio.file}
1753
+ else:
1754
+ data['audio'] = audio
1755
+
1756
+ response = self._make_request(
1757
+ 'POST', 'sendAudio', data=data, files=files)
1758
+ return Message(self, response)
1759
+
1760
+ def send_document(self,
1761
+ chat_id: Union[int,
1762
+ str],
1763
+ document,
1764
+ caption: Optional[str] = None,
1765
+ parse_mode: Optional[str] = None,
1766
+ reply_markup: Union[MenuKeyboardMarkup,
1767
+ InlineKeyboardMarkup] = None,
1768
+ reply_to_message: Union[Message,
1769
+ int,
1770
+ str] = None) -> Message:
1771
+ """Send a document"""
1772
+ files = None
1773
+ data = {
1774
+ 'chat_id': chat_id,
1775
+ 'caption': caption,
1776
+ 'parse_mode': parse_mode,
1777
+ 'reply_markup': reply_markup.keyboard if reply_markup else None,
1778
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1779
+ reply_to_message,
1780
+ Message) else reply_to_message}
1781
+
1782
+ if isinstance(
1783
+ document, (bytes, InputFile)) or hasattr(
1784
+ document, 'read'):
1785
+ files = {'document': document if not isinstance(
1786
+ document, InputFile) else document.file}
1787
+ else:
1788
+ data['document'] = document
1789
+
1790
+ response = self._make_request(
1791
+ 'POST', 'sendDocument', data=data, files=files)
1792
+ return Message(self, response)
1793
+
1794
+ def send_video(self,
1795
+ chat_id: Union[int,
1796
+ str],
1797
+ video,
1798
+ caption: Optional[str] = None,
1799
+ parse_mode: Optional[str] = None,
1800
+ reply_markup: Union[MenuKeyboardMarkup,
1801
+ InlineKeyboardMarkup] = None,
1802
+ reply_to_message: Union[Message,
1803
+ int,
1804
+ str] = None) -> Message:
1805
+ """Send a video"""
1806
+ files = None
1807
+ data = {
1808
+ 'chat_id': chat_id,
1809
+ 'caption': caption,
1810
+ 'parse_mode': parse_mode,
1811
+ 'reply_markup': reply_markup.keyboard if reply_markup else None,
1812
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1813
+ reply_to_message,
1814
+ Message) else reply_to_message}
1815
+
1816
+ if isinstance(video, (bytes, InputFile)) or hasattr(video, 'read'):
1817
+ files = {
1818
+ 'video': video if not isinstance(
1819
+ video, InputFile) else video.file}
1820
+ else:
1821
+ data['video'] = video
1822
+
1823
+ response = self._make_request(
1824
+ 'POST', 'sendVideo', data=data, files=files)
1825
+ return Message(self, response)
1826
+
1827
+ def send_animation(self,
1828
+ chat_id: Union[int,
1829
+ str],
1830
+ animation,
1831
+ caption: Optional[str] = None,
1832
+ parse_mode: Optional[str] = None,
1833
+ reply_markup: Union[MenuKeyboardMarkup,
1834
+ InlineKeyboardMarkup] = None,
1835
+ reply_to_message: Union[Message,
1836
+ int,
1837
+ str] = None) -> Message:
1838
+ """Send an animation (GIF or H.264/MPEG-4 AVC video without sound)"""
1839
+ files = None
1840
+ data = {
1841
+ 'chat_id': chat_id,
1842
+ 'caption': caption,
1843
+ 'parse_mode': parse_mode,
1844
+ 'reply_markup': reply_markup.keyboard if reply_markup else None,
1845
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1846
+ reply_to_message,
1847
+ Message) else reply_to_message}
1848
+
1849
+ if isinstance(
1850
+ animation, (bytes, InputFile)) or hasattr(
1851
+ animation, 'read'):
1852
+ files = {'animation': animation if not isinstance(
1853
+ animation, InputFile) else animation.file}
1854
+ else:
1855
+ data['animation'] = animation
1856
+
1857
+ response = self._make_request(
1858
+ 'POST', 'sendAnimation', data=data, files=files)
1859
+ return Message(self, response)
1860
+
1861
+ def send_voice(self,
1862
+ chat_id: Union[int,
1863
+ str],
1864
+ voice,
1865
+ caption: Optional[str] = None,
1866
+ parse_mode: Optional[str] = None,
1867
+ reply_markup: Union[MenuKeyboardMarkup,
1868
+ InlineKeyboardMarkup] = None,
1869
+ reply_to_message: Union[Message,
1870
+ int,
1871
+ str] = None) -> Message:
1872
+ """Send a voice message"""
1873
+ files = None
1874
+ data = {
1875
+ 'chat_id': chat_id,
1876
+ 'caption': caption,
1877
+ 'parse_mode': parse_mode,
1878
+ 'reply_markup': reply_markup.keyboard if reply_markup else None,
1879
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1880
+ reply_to_message,
1881
+ Message) else reply_to_message}
1882
+
1883
+ if isinstance(voice, (bytes, InputFile)) or hasattr(voice, 'read'):
1884
+ files = {
1885
+ 'voice': voice if not isinstance(
1886
+ voice, InputFile) else voice.file}
1887
+ else:
1888
+ data['voice'] = voice
1889
+
1890
+ response = self._make_request(
1891
+ 'POST', 'sendVoice', data=data, files=files)
1892
+ return Message(self, response)
1893
+
1894
+ def send_media_group(self,
1895
+ chat_id: Union[int,
1896
+ str],
1897
+ media: List[Dict],
1898
+ reply_to_message: Union[Message,
1899
+ int,
1900
+ str] = None) -> List[Message]:
1901
+ """Send a group of photos, videos, documents or audios as an album"""
1902
+ data = {
1903
+ 'chat_id': chat_id,
1904
+ 'media': media,
1905
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1906
+ reply_to_message,
1907
+ Message) else reply_to_message}
1908
+ response = self._make_request('POST', 'sendMediaGroup', json=data)
1909
+ return [Message(self, msg) for msg in response]
1910
+
1911
+ def send_location(self,
1912
+ chat_id: Union[int,
1913
+ str],
1914
+ latitude: float,
1915
+ longitude: float,
1916
+ reply_markup: Union[MenuKeyboardMarkup,
1917
+ InlineKeyboardMarkup] = None,
1918
+ reply_to_message: Union[Message,
1919
+ int,
1920
+ str] = None) -> Message:
1921
+ """Send a point on the map"""
1922
+ data = {
1923
+ 'chat_id': chat_id,
1924
+ 'latitude': latitude,
1925
+ 'longitude': longitude,
1926
+ 'reply_markup': reply_markup.keyboard if reply_markup else None,
1927
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1928
+ reply_to_message,
1929
+ Message) else reply_to_message}
1930
+ response = self._make_request('POST', 'sendLocation', json=data)
1931
+ return Message(self, response)
1932
+
1933
+ def send_contact(self,
1934
+ chat_id: Union[int,
1935
+ str],
1936
+ phone_number: str,
1937
+ first_name: str,
1938
+ last_name: Optional[str] = None,
1939
+ reply_markup: Union[MenuKeyboardMarkup,
1940
+ InlineKeyboardMarkup] = None,
1941
+ reply_to_message: Union[Message,
1942
+ int,
1943
+ str] = None) -> Message:
1944
+ """Send a phone contact"""
1945
+ data = {
1946
+ 'chat_id': chat_id,
1947
+ 'phone_number': phone_number,
1948
+ 'first_name': first_name,
1949
+ 'last_name': last_name,
1950
+ 'reply_markup': reply_markup.keyboard if reply_markup else None,
1951
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1952
+ reply_to_message,
1953
+ Message) else reply_to_message}
1954
+ response = self._make_request('POST', 'sendContact', json=data)
1955
+ return Message(self, response)
1956
+
1957
+ def send_invoice(self,
1958
+ chat_id: Union[int,
1959
+ str],
1960
+ title: str,
1961
+ description: str,
1962
+ payload: str,
1963
+ provider_token: str,
1964
+ prices: list,
1965
+ photo_url: Optional[str] = None,
1966
+ reply_to_message: Union[int | str | Message] = None,
1967
+ reply_markup: Union[MenuKeyboardMarkup | InlineKeyboardMarkup] = None) -> Message:
1968
+ """Send a invoice"""
1969
+ r = []
1970
+ for x in prices:
1971
+ r.append(x.json)
1972
+ prices = r
1973
+ data = {
1974
+ 'chat_id': chat_id,
1975
+ 'title': title,
1976
+ 'description': description,
1977
+ 'payload': payload,
1978
+ 'provider_token': provider_token,
1979
+ 'prices': prices,
1980
+ 'photo_url': photo_url,
1981
+ 'reply_to_message_id': reply_to_message.message_id if isinstance(
1982
+ reply_to_message,
1983
+ Message) else reply_to_message,
1984
+ 'reply_markup': reply_markup.keyboard if reply_markup else None}
1985
+ response = self._make_request('POST', 'sendInvoice', json=data)
1986
+ return Message(self, response)
1987
+
1988
+ def send_chat_action(self, chat: Union[int, str, 'Chat'], action: str, how_many_times: int = 1) -> bool:
1989
+ """Send a chat action"""
1990
+ if not chat:
1991
+ raise ValueError("Chat ID cannot be empty")
1992
+
1993
+ data = {
1994
+ 'chat_id': str(chat) if isinstance(chat, (int, str)) else str(chat.id),
1995
+ 'action': action
1996
+ }
1997
+ res = []
1998
+ for _ in range(how_many_times):
1999
+ response = self._make_request('POST', 'sendChatAction', json=data)
2000
+ res.append(response.get('ok', False))
2001
+ return all(res)
2002
+
2003
+ def copy_message(self,
2004
+ chat_id: Union[int,
2005
+ str,
2006
+ 'Chat'],
2007
+ from_chat_id: Union[int,
2008
+ str,
2009
+ 'Chat'],
2010
+ message_id: Union[int,
2011
+ str,
2012
+ 'Chat']):
2013
+ data = {
2014
+ 'chat_id': chat_id if isinstance(
2015
+ chat_id, (int, str)) else chat_id.id, 'from_chat_id': from_chat_id if isinstance(
2016
+ from_chat_id, (int, str)) else from_chat_id.id, 'message_id': message_id if isinstance(
2017
+ message_id, (int, str)) else message_id.id}
2018
+ response = self._make_request('POST', 'copyMessage', json=data)
2019
+ return Message(self, response)
2020
+
2021
+ def get_chat_member(self,
2022
+ chat: Union[int,
2023
+ str,
2024
+ 'Chat'],
2025
+ user: Union[int,
2026
+ str,
2027
+ 'User']) -> ChatMember:
2028
+ """Get information about a member of a chat including their permissions"""
2029
+ data = {
2030
+ 'chat_id': chat if isinstance(chat, (int, str)) else chat.id,
2031
+ 'user_id': user if isinstance(user, (int, str)) else user.id
2032
+ }
2033
+ response = self._make_request('POST', 'getChatMember', json=data)
2034
+ return ChatMember(self, response['result'])
2035
+
2036
+ def get_chat_administrators(
2037
+ self, chat: Union[int, str, 'Chat']) -> List[ChatMember]:
2038
+ """Get a list of administrators in a chat"""
2039
+ data = {'chat_id': getattr(chat, 'id', chat)}
2040
+ response = self._make_request(
2041
+ 'POST', 'getChatAdministrators', json=data)
2042
+ return [ChatMember(self, member)
2043
+ for member in response.get('result', [])]
2044
+
2045
+ def get_chat_members_count(self, chat: Union[int, str, 'Chat']) -> int:
2046
+ """Get the number of members in a chat"""
2047
+ data = {
2048
+ 'chat_id': chat if isinstance(chat, (int, str)) else chat.id
2049
+ }
2050
+ response = self._make_request('GET', 'getChatMembersCount', json=data)
2051
+ return response['result']
2052
+
2053
+ def is_joined(self, user: Union[User, int, str],
2054
+ chat: Union[Chat, int, str]) -> bool:
2055
+ """Check if user is a member of the chat"""
2056
+ data = {
2057
+ 'chat_id': chat if isinstance(chat, (int, str)) else chat.id,
2058
+ 'user_id': user if isinstance(user, (int, str)) else user.id
2059
+ }
2060
+ response = self._make_request('GET', 'getChatMember', json=data)
2061
+ return response.get('status') not in ['left', 'kicked']
2062
+
2063
+ def on_message(self, func):
2064
+ """Decorator for handling new messages"""
2065
+ self._message_handler = func
2066
+ return func
2067
+
2068
+ def on_callback_query(self, func):
2069
+ """Decorator for handling callback queries"""
2070
+ self._callback_handler = func
2071
+ return func
2072
+
2073
+ def on_tick(self, seconds: int):
2074
+ """Decorator for handling periodic events"""
2075
+ def decorator(func):
2076
+ self._tick_handlers = getattr(self, '_tick_handlers', {})
2077
+ self._tick_handlers[func] = {'interval': seconds, 'last_run': 0}
2078
+ return func
2079
+ return decorator
2080
+
2081
+ def on_close(self, func):
2082
+ """Decorator for handling close event"""
2083
+ self._close_handler = func
2084
+ return func
2085
+
2086
+ def on_ready(self, func):
2087
+ """Decorator for handling ready event"""
2088
+ self._ready_handler = func
2089
+ return func
2090
+
2091
+ def on_update(self, func):
2092
+ """Decorator for handling raw updates"""
2093
+ self._update_handler = func
2094
+ return func
2095
+
2096
+ def on_member_chat_join(self, func):
2097
+ """Decorator for handling new chat members"""
2098
+ self._member_join_handler = func
2099
+ return func
2100
+
2101
+ def on_member_chat_leave(self, func):
2102
+ """Decorator for handling members leaving chat"""
2103
+ self._member_leave_handler = func
2104
+ return func
2105
+
2106
+ def on_message_edit(self, func):
2107
+ """Decorator for handling edited messages"""
2108
+ self._message_edit_handler = func
2109
+ return func
2110
+
2111
+ def on_command(self, command: str = None):
2112
+ """Decorator for handling specific text commands"""
2113
+ def decorator(func):
2114
+ self._text_handlers = getattr(self, '_text_handlers', {})
2115
+ cmd = f"/{func.__name__}" if command is None else f"/{command.lstrip('/')}"
2116
+ self._text_handlers[cmd] = func
2117
+ return func
2118
+ return decorator
2119
+
2120
+ def _create_thread(self, handler, *args):
2121
+ """Helper method to create and start a thread"""
2122
+ thread = threading.Thread(target=handler, args=args, daemon=True)
2123
+ thread.start()
2124
+ self._threads.append(thread)
2125
+
2126
+ def _handle_message(self, message, update):
2127
+ """Handle different types of messages"""
2128
+ msg_data = update.get('message', {})
2129
+
2130
+ if 'new_chat_members' in msg_data and hasattr(self, '_member_join_handler'):
2131
+ chat, user = msg_data['chat'], msg_data['new_chat_members'][0]
2132
+ self._create_thread(
2133
+ self._member_join_handler,
2134
+ message,
2135
+ Chat(self, {"ok": True, "result": chat}),
2136
+ User(self, {"ok": True, "result": user})
2137
+ )
2138
+ return
2139
+
2140
+ if 'left_chat_member' in msg_data and hasattr(self, '_member_leave_handler'):
2141
+ chat, user = msg_data['chat'], msg_data['left_chat_member']
2142
+ self._create_thread(
2143
+ self._member_leave_handler,
2144
+ message,
2145
+ Chat(self, {"ok": True, "result": chat}),
2146
+ User(self, {"ok": True, "result": user})
2147
+ )
2148
+ return
2149
+
2150
+ if 'text' in msg_data and hasattr(self, '_text_handlers'):
2151
+ text = msg_data['text']
2152
+ for command, handler in self._text_handlers.items():
2153
+ if text.startswith(command):
2154
+ conds = conditions(self, message.author, message, None, message.chat)
2155
+ params = inspect.signature(handler).parameters
2156
+ args = (message, conds) if len(params) > 1 else (message,)
2157
+ self._create_thread(handler, *args)
2158
+ return
2159
+
2160
+ if self._message_handler:
2161
+ conds = conditions(self, message.author, message, None, message.chat)
2162
+ params = inspect.signature(self._message_handler).parameters
2163
+ args = ((message, update, conds) if len(params) > 2 else
2164
+ (message, update) if len(params) > 1 else (message,))
2165
+ self._create_thread(self._message_handler, *args)
2166
+
2167
+ def _handle_update(self, update):
2168
+ if hasattr(self, '_update_handler'):
2169
+ self._create_thread(self._update_handler, update)
2170
+
2171
+ # Handle message and edited message
2172
+ message_types = {
2173
+ 'message': (Message, self._handle_message),
2174
+ 'edited_message': (Message, self._message_edit_handler)
2175
+ }
2176
+
2177
+ for update_type, (cls, handler) in message_types.items():
2178
+ if update_type in update:
2179
+ message = cls(self, {'ok': True, 'result': update[update_type]})
2180
+ handler(message, update)
2181
+ return
2182
+
2183
+ if 'callback_query' in update and self._callback_handler:
2184
+ obj = CallbackQuery(self, {'ok': True, 'result': update['callback_query']})
2185
+ params = inspect.signature(self._callback_handler).parameters
2186
+ conds = conditions(self, obj.author, None, obj, obj.chat)
2187
+ args = (obj, update, conds) if len(params) > 2 else (obj, update)
2188
+ self._create_thread(self._callback_handler, *args)
2189
+
2190
+ def _handle_tick_events(self, current_time):
2191
+ """Handle periodic tick events"""
2192
+ if hasattr(self, '_tick_handlers'):
2193
+ for handler, info in self._tick_handlers.items():
2194
+ if current_time - info['last_run'] >= info['interval']:
2195
+ self._create_thread(handler)
2196
+ info['last_run'] = current_time
2197
+
2198
+ def run(self, debug=False):
2199
+ """Start p-olling for new messages"""
2200
+ try:
2201
+ self.get_me()
2202
+ except BaseException:
2203
+ raise BaleTokenNotFoundError("token not found")
2204
+
2205
+ self._polling = True
2206
+ offset = 0
2207
+ past_updates = set()
2208
+ source_file = inspect.getfile(self.__class__)
2209
+ last_modified = os.path.getmtime(source_file)
2210
+
2211
+ if self.auto_log_start_message:
2212
+ print(f"-+-+-+ [logged in as @{self.get_me().username}] +-+-+-")
2213
+ if hasattr(self, '_ready_handler'):
2214
+ self._ready_handler()
2215
+
2216
+ while self._polling:
2217
+ try:
2218
+ if debug:
2219
+ current_modified = os.path.getmtime(source_file)
2220
+ if current_modified > last_modified:
2221
+ last_modified = current_modified
2222
+ print("Source file changed, restarting...")
2223
+ python = sys.executable
2224
+ os.execl(python, python, *sys.argv)
2225
+
2226
+ updates = self.get_updates(offset=offset, timeout=30)
2227
+ for update in updates:
2228
+ update_id = update['update_id']
2229
+ if update_id not in past_updates:
2230
+ self._handle_update(update)
2231
+ offset = update_id + 1
2232
+ past_updates.add(update_id)
2233
+ if len(past_updates) > 100:
2234
+ past_updates = set(sorted(list(past_updates))[-50:])
2235
+
2236
+ current_time = time.time()
2237
+ self._handle_tick_events(current_time)
2238
+ self._threads = [t for t in self._threads if t.is_alive()]
2239
+ time.sleep(0.1)
2240
+ except Exception:
2241
+ print(f"Error in polling: {traceback.format_exc()}")
2242
+ time.sleep(1)
2243
+
2244
+ def _check_source_file_changed(self, source_file, last_modified):
2245
+ try:
2246
+ current_mtime = os.path.getmtime(source_file)
2247
+ return current_mtime != last_modified
2248
+ except (FileNotFoundError, OSError) as e:
2249
+ print(f"Error checking file modification time: {e}")
2250
+ return False
2251
+
2252
+ def get_updates(self, offset: Optional[int] = None,
2253
+ limit: Optional[int] = None,
2254
+ timeout: Optional[int] = None) -> List[Dict[str, Any]]:
2255
+ params = {k: v for k, v in locals().items() if k != 'self' and v is not None}
2256
+ response = self._make_request('GET', 'getUpdates', params=params)
2257
+ return response.get('result', [])
2258
+
2259
+ def safe_close(self):
2260
+ """Close the client and stop polling"""
2261
+ self._polling = False
2262
+ for thread in self._threads:
2263
+ thread.join(timeout=1.0)
2264
+ self._threads.clear()
2265
+ if hasattr(self, '_close_handler'):
2266
+ self._close_handler()
2267
+
2268
+ def create_ref_link(self, data: str):
2269
+ return f"https://ble.ir/{self.get_me().username}?start={data}"