tornbot 0.1.0__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.
tornbot/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ from .tornbot import TornBot
2
+ from . import types
tornbot/apihelper.py ADDED
@@ -0,0 +1,17 @@
1
+ import requests
2
+
3
+ API_URL = "http://127.0.0.1:3000/api/bot{0}/{1}"
4
+
5
+ def send_message(token, chat_id, text):
6
+ method_url = API_URL.format(token, "sendMessage")
7
+ payload = {"chat_id": chat_id, "text": text}
8
+ response = requests.post(method_url, json=payload)
9
+ return response.json()
10
+
11
+ def get_updates(token, offset=None):
12
+ method_url = API_URL.format(token, "getUpdates")
13
+ payload = {}
14
+ if offset:
15
+ payload["offset"] = offset
16
+ response = requests.post(method_url, json=payload)
17
+ return response.json()
tornbot/tornbot.py ADDED
@@ -0,0 +1,99 @@
1
+ import logging
2
+ import time
3
+ from typing import Optional, List, Callable, Union
4
+
5
+ from . import apihelper
6
+ from . import types
7
+
8
+
9
+ class TornBot:
10
+ def __init__(self, token):
11
+ self.token = token
12
+ self.message_handlers = []
13
+ self.last_update_id = 0
14
+
15
+ def message_handler(
16
+ self,
17
+ commands: Optional[List[str]]=None,
18
+ regexp: Optional[str]=None,
19
+ func: Optional[Callable]=None,
20
+ content_types: Optional[List[str]]=None,
21
+ chat_types: Optional[List[str]]=None,
22
+ **kwargs):
23
+ def decorator(handler_func):
24
+ handler_dict = {
25
+ 'function': handler_func,
26
+ 'commands': commands,
27
+ 'filters': func
28
+ }
29
+ self.message_handlers.append(handler_dict)
30
+ return handler_func
31
+
32
+ return decorator
33
+
34
+ def send_message(
35
+ self, chat_id: Union[int, str], text: str,
36
+ parse_mode: Optional[str] = None,
37
+ entities: Optional[List] = None,
38
+ disable_web_page_preview: Optional[bool] = None, # deprecated, for backward compatibility
39
+ disable_notification: Optional[bool] = None,
40
+ protect_content: Optional[bool] = None,
41
+ reply_to_message_id: Optional[int] = None, # deprecated, for backward compatibility
42
+ allow_sending_without_reply: Optional[bool] = None, # deprecated, for backward compatibility
43
+ reply_markup: str = None,
44
+ timeout: Optional[int] = None,
45
+ message_thread_id: Optional[int] = None,
46
+ reply_parameters: Optional = None,
47
+ link_preview_options: Optional = None,
48
+ business_connection_id: Optional[str] = None,
49
+ message_effect_id: Optional[str] = None,
50
+ allow_paid_broadcast: Optional[bool] = None,
51
+ direct_messages_topic_id: Optional[int] = None,
52
+ suggested_post_parameters: Optional = None) -> types.Message:
53
+ result = apihelper.send_message(self.token, chat_id, text)
54
+ return result
55
+
56
+ def process_new_messages(self, messages):
57
+ for message in messages:
58
+ for handler in self.message_handlers:
59
+ is_match = False
60
+
61
+ if handler['commands']:
62
+ if message.text and any(message.text.startswith(f"/{cmd}") for cmd in handler['commands']):
63
+ is_match = True
64
+ elif handler['filters']:
65
+ if handler['filters'](message):
66
+ is_match = True
67
+ else:
68
+ is_match = True
69
+
70
+ if is_match:
71
+ handler['function'](message)
72
+ break
73
+
74
+ def get_updates(self, offset=None):
75
+ json_updates = apihelper.get_updates(self.token, offset)
76
+ updates = []
77
+ if json_updates.get('ok'):
78
+ for update in json_updates['result']:
79
+ if 'message' in update:
80
+ updates.append(types.Message.de_json(update['message']))
81
+ self.last_update_id = update['update_id']
82
+ return updates
83
+
84
+ def polling(self, non_stop: Optional[bool] = False, skip_pending: Optional[bool] = False,
85
+ interval: Optional[int] = 0,
86
+ timeout: Optional[int] = 20, long_polling_timeout: Optional[int] = 20,
87
+ logger_level: Optional[int] = logging.ERROR, allowed_updates: Optional[List[str]] = None,
88
+ none_stop: Optional[bool] = None, restart_on_change: Optional[bool] = False,
89
+ path_to_watch: Optional[str] = None):
90
+ while True:
91
+ try:
92
+ updates = self.get_updates(offset=self.last_update_id + 1)
93
+ if updates:
94
+ self.process_new_messages(updates)
95
+ time.sleep(interval)
96
+ except Exception:
97
+ if not none_stop:
98
+ break
99
+ time.sleep(5)
tornbot/types.py ADDED
@@ -0,0 +1,48 @@
1
+ class User:
2
+ def __init__(self, id, is_bot, first_name, username=None):
3
+ self.id = id
4
+ self.is_bot = is_bot
5
+ self.first_name = first_name
6
+ self.username = username
7
+
8
+ @classmethod
9
+ def de_json(cls, json_string):
10
+ if not json_string:
11
+ return None
12
+ return cls(
13
+ id=json_string.get('id'),
14
+ is_bot=json_string.get('is_bot'),
15
+ first_name=json_string.get('first_name'),
16
+ username=json_string.get('username')
17
+ )
18
+
19
+ class Chat:
20
+ def __init__(self, id, type):
21
+ self.id = id
22
+ self.type = type
23
+
24
+ @classmethod
25
+ def de_json(cls, json_string):
26
+ if not json_string:
27
+ return None
28
+ return cls(
29
+ id=json_string.get('id'),
30
+ type=json_string.get('type')
31
+ )
32
+
33
+ class Message:
34
+ def __init__(self, message_id, from_user, chat, text):
35
+ self.message_id = message_id
36
+ self.from_user = from_user
37
+ self.chat = chat
38
+ self.text = text
39
+
40
+ @classmethod
41
+ def de_json(cls, json_string):
42
+ if not json_string:
43
+ return None
44
+ message_id = json_string.get('message_id')
45
+ from_user = User.de_json(json_string.get('from'))
46
+ chat = Chat.de_json(json_string.get('chat'))
47
+ text = json_string.get('text')
48
+ return cls(message_id, from_user, chat, text)
@@ -0,0 +1,23 @@
1
+ Metadata-Version: 2.4
2
+ Name: tornbot
3
+ Version: 0.1.0
4
+ Summary: Защищенная коммуникационная платформа в рамках модели B2G
5
+ Home-page: https://github.com/SayGGGo/Tornado
6
+ Author: SayGG
7
+ Author-email: sayginaego.say@gmail.com
8
+ Classifier: Programming Language :: Python :: 3.12
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Requires-Python: >=3.10
11
+ Description-Content-Type: text/markdown
12
+ Dynamic: author
13
+ Dynamic: author-email
14
+ Dynamic: classifier
15
+ Dynamic: description
16
+ Dynamic: description-content-type
17
+ Dynamic: home-page
18
+ Dynamic: requires-python
19
+ Dynamic: summary
20
+
21
+ ## TornBot
22
+ ---
23
+ Библиотека TornBot, созданная на основне telebot, и позволяющая в пару действий перенести свой проект из Telegram в Tornado. API имеет почти такой-же функционал, что и библиотека для telegram, но если функция не будет поддерживаться — вы получите предупреждение в консоли.
@@ -0,0 +1,9 @@
1
+ tornbot/__init__.py,sha256=ZStBUwGtlmT3tq4aCJtEPjG41vrJePCgCQpZqnIZ1lE,49
2
+ tornbot/apihelper.py,sha256=liF8dZURHDbF1Y0GP0Psx96ku4o3n67QARMg3D9V2S8,547
3
+ tornbot/tornbot.py,sha256=e1g-mN6BxVBGfO-0GecntiONrlqi8qEBT4GI7i4csWg,4073
4
+ tornbot/types.py,sha256=oBIR1nkO5sbY1eFcz5UMf6v-JlHRPbbgFtJxi-J7p0s,1427
5
+ tornbot-0.1.0.dist-info/METADATA,sha256=CUS9FuhbdtFBSfkhGBrAj6dQwNey2xc14bCGY9M7MVg,1104
6
+ tornbot-0.1.0.dist-info/WHEEL,sha256=YCfwYGOYMi5Jhw2fU4yNgwErybb2IX5PEwBKV4ZbdBo,91
7
+ tornbot-0.1.0.dist-info/entry_points.txt,sha256=3z9AGMnIRxD4rskJtzWvmzejjgN1zQ273GKwMx_CY9A,41
8
+ tornbot-0.1.0.dist-info/top_level.txt,sha256=DrEpslQsTvKPMjam_2aRGky6TVIgOMq1i-PGG-u7eQ8,8
9
+ tornbot-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ tornbot-run = app:main
@@ -0,0 +1 @@
1
+ tornbot