bendbandbot 1.0.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 bendband
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ include README.md
2
+ include LICENSE
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.4
2
+ Name: bendbandbot
3
+ Version: 1.0.0
4
+ Summary: Проста бібліотека для створення Telegram ботів для навчання
5
+ Home-page: https://github.com/bendband/bendbandbot
6
+ Author: bendband
7
+ Author-email: contact@bendband.net
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/bendband/bendbandbot
10
+ Project-URL: Documentation, https://bendband.net/bot-course
11
+ Keywords: telegram,bot,education,learning,bendband
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: Topic :: Education
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Requires-Python: >=3.8
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: python-telegram-bot<22.0,>=21.0
21
+ Dynamic: author-email
22
+ Dynamic: home-page
23
+ Dynamic: license-file
24
+ Dynamic: requires-python
25
+
26
+ # BendBandBot
27
+
28
+ Проста бібліотека для створення Telegram ботів, спеціально розроблена для навчання школярів програмуванню.
29
+
30
+ ## Особливості
31
+
32
+ - ✅ **Просто** - без декораторів, async/await, складних конструкцій
33
+ - ✅ **Зрозуміло** - коментарі українською, зрозумілі назви методів
34
+ - ✅ **Для початківців** - підходить для учнів 6-9 класів
35
+ - ✅ **Два режими** - прості команди з текстом або функції для складнішої логіки
36
+
37
+ ## Встановлення
38
+
39
+ ```bash
40
+ pip install bendbandbot
41
+ ```
42
+
43
+ ## Швидкий старт
44
+
45
+ ```python
46
+ from simple_bot import SimpleBot
47
+
48
+ # Створюємо бота
49
+ bot = SimpleBot("ВАШ_ТОКЕН_ВІД_BOTFATHER")
50
+
51
+ # Додаємо команди (простий спосіб)
52
+ bot.on_command("start", "Привіт! 👋")
53
+ bot.on_command("help", "Я простий бот!")
54
+
55
+ # Запускаємо
56
+ bot.start()
57
+ ```
58
+
59
+ ## Приклад з функціями
60
+
61
+ ```python
62
+ from simple_bot import SimpleBot
63
+
64
+ bot = SimpleBot("ВАШ_ТОКЕН")
65
+
66
+ def greeting(message):
67
+ name = bot.get_name(message)
68
+ bot.send(message, f"Привіт, {name}! 😊")
69
+
70
+ bot.on_command("start", greeting)
71
+ bot.start()
72
+ ```
73
+
74
+ ## Документація
75
+
76
+ Повний курс з 14 уроків: [bendband.net/bot-course](https://bendband.net/bot-course)
77
+
78
+ ## API
79
+
80
+ ### Створення бота
81
+ ```python
82
+ bot = SimpleBot(token: str)
83
+ ```
84
+
85
+ ### Команди
86
+ ```python
87
+ # Простий спосіб - тільки текст
88
+ bot.on_command("start", "Привіт!")
89
+
90
+ # Складніший - з функцією
91
+ def hello(message):
92
+ bot.send(message, "Привіт!")
93
+ bot.on_command("start", hello)
94
+ ```
95
+
96
+ ### Отримання даних
97
+ ```python
98
+ text = bot.get_text(message) # Текст повідомлення
99
+ name = bot.get_name(message) # Ім'я користувача
100
+ ```
101
+
102
+ ### Надсилання
103
+ ```python
104
+ bot.send(message, "Текст")
105
+ bot.send_photo(message, "photo.jpg", "Підпис")
106
+ ```
107
+
108
+ ### Обробка повідомлень
109
+ ```python
110
+ def echo(message):
111
+ text = bot.get_text(message)
112
+ bot.send(message, text)
113
+
114
+ bot.on_message(echo)
115
+ ```
116
+
117
+ ## Приклади
118
+
119
+ ### Калькулятор
120
+ ```python
121
+ def calculate(message):
122
+ text = bot.get_text(message)
123
+ parts = text.split()
124
+
125
+ if len(parts) == 3:
126
+ num1 = float(parts[0])
127
+ op = parts[1]
128
+ num2 = float(parts[2])
129
+
130
+ if op == "+":
131
+ result = num1 + num2
132
+ elif op == "-":
133
+ result = num1 - num2
134
+ elif op == "*":
135
+ result = num1 * num2
136
+ elif op == "/":
137
+ result = num1 / num2 if num2 != 0 else "Помилка"
138
+
139
+ bot.send(message, f"= {result}")
140
+
141
+ bot.on_message(calculate)
142
+ ```
143
+
144
+ ### Випадковий вибір
145
+ ```python
146
+ import random
147
+
148
+ jokes = ["Жарт 1", "Жарт 2", "Жарт 3"]
149
+
150
+ def joke(message):
151
+ bot.send(message, random.choice(jokes))
152
+
153
+ bot.on_command("joke", joke)
154
+ ```
155
+
156
+ ## Ліцензія
157
+
158
+ MIT License - вільно для навчальних цілей
159
+
160
+ ## Автор
161
+
162
+ Створено **bendband** для навчання школярів програмуванню
163
+
164
+ 🌐 https://bendband.net
@@ -0,0 +1,139 @@
1
+ # BendBandBot
2
+
3
+ Проста бібліотека для створення Telegram ботів, спеціально розроблена для навчання школярів програмуванню.
4
+
5
+ ## Особливості
6
+
7
+ - ✅ **Просто** - без декораторів, async/await, складних конструкцій
8
+ - ✅ **Зрозуміло** - коментарі українською, зрозумілі назви методів
9
+ - ✅ **Для початківців** - підходить для учнів 6-9 класів
10
+ - ✅ **Два режими** - прості команди з текстом або функції для складнішої логіки
11
+
12
+ ## Встановлення
13
+
14
+ ```bash
15
+ pip install bendbandbot
16
+ ```
17
+
18
+ ## Швидкий старт
19
+
20
+ ```python
21
+ from simple_bot import SimpleBot
22
+
23
+ # Створюємо бота
24
+ bot = SimpleBot("ВАШ_ТОКЕН_ВІД_BOTFATHER")
25
+
26
+ # Додаємо команди (простий спосіб)
27
+ bot.on_command("start", "Привіт! 👋")
28
+ bot.on_command("help", "Я простий бот!")
29
+
30
+ # Запускаємо
31
+ bot.start()
32
+ ```
33
+
34
+ ## Приклад з функціями
35
+
36
+ ```python
37
+ from simple_bot import SimpleBot
38
+
39
+ bot = SimpleBot("ВАШ_ТОКЕН")
40
+
41
+ def greeting(message):
42
+ name = bot.get_name(message)
43
+ bot.send(message, f"Привіт, {name}! 😊")
44
+
45
+ bot.on_command("start", greeting)
46
+ bot.start()
47
+ ```
48
+
49
+ ## Документація
50
+
51
+ Повний курс з 14 уроків: [bendband.net/bot-course](https://bendband.net/bot-course)
52
+
53
+ ## API
54
+
55
+ ### Створення бота
56
+ ```python
57
+ bot = SimpleBot(token: str)
58
+ ```
59
+
60
+ ### Команди
61
+ ```python
62
+ # Простий спосіб - тільки текст
63
+ bot.on_command("start", "Привіт!")
64
+
65
+ # Складніший - з функцією
66
+ def hello(message):
67
+ bot.send(message, "Привіт!")
68
+ bot.on_command("start", hello)
69
+ ```
70
+
71
+ ### Отримання даних
72
+ ```python
73
+ text = bot.get_text(message) # Текст повідомлення
74
+ name = bot.get_name(message) # Ім'я користувача
75
+ ```
76
+
77
+ ### Надсилання
78
+ ```python
79
+ bot.send(message, "Текст")
80
+ bot.send_photo(message, "photo.jpg", "Підпис")
81
+ ```
82
+
83
+ ### Обробка повідомлень
84
+ ```python
85
+ def echo(message):
86
+ text = bot.get_text(message)
87
+ bot.send(message, text)
88
+
89
+ bot.on_message(echo)
90
+ ```
91
+
92
+ ## Приклади
93
+
94
+ ### Калькулятор
95
+ ```python
96
+ def calculate(message):
97
+ text = bot.get_text(message)
98
+ parts = text.split()
99
+
100
+ if len(parts) == 3:
101
+ num1 = float(parts[0])
102
+ op = parts[1]
103
+ num2 = float(parts[2])
104
+
105
+ if op == "+":
106
+ result = num1 + num2
107
+ elif op == "-":
108
+ result = num1 - num2
109
+ elif op == "*":
110
+ result = num1 * num2
111
+ elif op == "/":
112
+ result = num1 / num2 if num2 != 0 else "Помилка"
113
+
114
+ bot.send(message, f"= {result}")
115
+
116
+ bot.on_message(calculate)
117
+ ```
118
+
119
+ ### Випадковий вибір
120
+ ```python
121
+ import random
122
+
123
+ jokes = ["Жарт 1", "Жарт 2", "Жарт 3"]
124
+
125
+ def joke(message):
126
+ bot.send(message, random.choice(jokes))
127
+
128
+ bot.on_command("joke", joke)
129
+ ```
130
+
131
+ ## Ліцензія
132
+
133
+ MIT License - вільно для навчальних цілей
134
+
135
+ ## Автор
136
+
137
+ Створено **bendband** для навчання школярів програмуванню
138
+
139
+ 🌐 https://bendband.net
@@ -0,0 +1,164 @@
1
+ Metadata-Version: 2.4
2
+ Name: bendbandbot
3
+ Version: 1.0.0
4
+ Summary: Проста бібліотека для створення Telegram ботів для навчання
5
+ Home-page: https://github.com/bendband/bendbandbot
6
+ Author: bendband
7
+ Author-email: contact@bendband.net
8
+ License: MIT
9
+ Project-URL: Homepage, https://github.com/bendband/bendbandbot
10
+ Project-URL: Documentation, https://bendband.net/bot-course
11
+ Keywords: telegram,bot,education,learning,bendband
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: Intended Audience :: Education
14
+ Classifier: Topic :: Education
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Requires-Python: >=3.8
18
+ Description-Content-Type: text/markdown
19
+ License-File: LICENSE
20
+ Requires-Dist: python-telegram-bot<22.0,>=21.0
21
+ Dynamic: author-email
22
+ Dynamic: home-page
23
+ Dynamic: license-file
24
+ Dynamic: requires-python
25
+
26
+ # BendBandBot
27
+
28
+ Проста бібліотека для створення Telegram ботів, спеціально розроблена для навчання школярів програмуванню.
29
+
30
+ ## Особливості
31
+
32
+ - ✅ **Просто** - без декораторів, async/await, складних конструкцій
33
+ - ✅ **Зрозуміло** - коментарі українською, зрозумілі назви методів
34
+ - ✅ **Для початківців** - підходить для учнів 6-9 класів
35
+ - ✅ **Два режими** - прості команди з текстом або функції для складнішої логіки
36
+
37
+ ## Встановлення
38
+
39
+ ```bash
40
+ pip install bendbandbot
41
+ ```
42
+
43
+ ## Швидкий старт
44
+
45
+ ```python
46
+ from simple_bot import SimpleBot
47
+
48
+ # Створюємо бота
49
+ bot = SimpleBot("ВАШ_ТОКЕН_ВІД_BOTFATHER")
50
+
51
+ # Додаємо команди (простий спосіб)
52
+ bot.on_command("start", "Привіт! 👋")
53
+ bot.on_command("help", "Я простий бот!")
54
+
55
+ # Запускаємо
56
+ bot.start()
57
+ ```
58
+
59
+ ## Приклад з функціями
60
+
61
+ ```python
62
+ from simple_bot import SimpleBot
63
+
64
+ bot = SimpleBot("ВАШ_ТОКЕН")
65
+
66
+ def greeting(message):
67
+ name = bot.get_name(message)
68
+ bot.send(message, f"Привіт, {name}! 😊")
69
+
70
+ bot.on_command("start", greeting)
71
+ bot.start()
72
+ ```
73
+
74
+ ## Документація
75
+
76
+ Повний курс з 14 уроків: [bendband.net/bot-course](https://bendband.net/bot-course)
77
+
78
+ ## API
79
+
80
+ ### Створення бота
81
+ ```python
82
+ bot = SimpleBot(token: str)
83
+ ```
84
+
85
+ ### Команди
86
+ ```python
87
+ # Простий спосіб - тільки текст
88
+ bot.on_command("start", "Привіт!")
89
+
90
+ # Складніший - з функцією
91
+ def hello(message):
92
+ bot.send(message, "Привіт!")
93
+ bot.on_command("start", hello)
94
+ ```
95
+
96
+ ### Отримання даних
97
+ ```python
98
+ text = bot.get_text(message) # Текст повідомлення
99
+ name = bot.get_name(message) # Ім'я користувача
100
+ ```
101
+
102
+ ### Надсилання
103
+ ```python
104
+ bot.send(message, "Текст")
105
+ bot.send_photo(message, "photo.jpg", "Підпис")
106
+ ```
107
+
108
+ ### Обробка повідомлень
109
+ ```python
110
+ def echo(message):
111
+ text = bot.get_text(message)
112
+ bot.send(message, text)
113
+
114
+ bot.on_message(echo)
115
+ ```
116
+
117
+ ## Приклади
118
+
119
+ ### Калькулятор
120
+ ```python
121
+ def calculate(message):
122
+ text = bot.get_text(message)
123
+ parts = text.split()
124
+
125
+ if len(parts) == 3:
126
+ num1 = float(parts[0])
127
+ op = parts[1]
128
+ num2 = float(parts[2])
129
+
130
+ if op == "+":
131
+ result = num1 + num2
132
+ elif op == "-":
133
+ result = num1 - num2
134
+ elif op == "*":
135
+ result = num1 * num2
136
+ elif op == "/":
137
+ result = num1 / num2 if num2 != 0 else "Помилка"
138
+
139
+ bot.send(message, f"= {result}")
140
+
141
+ bot.on_message(calculate)
142
+ ```
143
+
144
+ ### Випадковий вибір
145
+ ```python
146
+ import random
147
+
148
+ jokes = ["Жарт 1", "Жарт 2", "Жарт 3"]
149
+
150
+ def joke(message):
151
+ bot.send(message, random.choice(jokes))
152
+
153
+ bot.on_command("joke", joke)
154
+ ```
155
+
156
+ ## Ліцензія
157
+
158
+ MIT License - вільно для навчальних цілей
159
+
160
+ ## Автор
161
+
162
+ Створено **bendband** для навчання школярів програмуванню
163
+
164
+ 🌐 https://bendband.net
@@ -0,0 +1,11 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ README.md
4
+ pyproject.toml
5
+ setup.py
6
+ bendbandbot.egg-info/PKG-INFO
7
+ bendbandbot.egg-info/SOURCES.txt
8
+ bendbandbot.egg-info/dependency_links.txt
9
+ bendbandbot.egg-info/requires.txt
10
+ bendbandbot.egg-info/top_level.txt
11
+ simple_bot/__init__.py
@@ -0,0 +1 @@
1
+ python-telegram-bot<22.0,>=21.0
@@ -0,0 +1 @@
1
+ simple_bot
@@ -0,0 +1,27 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "bendbandbot"
7
+ version = "1.0.0"
8
+ description = "Проста бібліотека для створення Telegram ботів для навчання"
9
+ readme = "README.md"
10
+ authors = [{name = "bendband"}]
11
+ license = {text = "MIT"}
12
+ classifiers = [
13
+ "Development Status :: 5 - Production/Stable",
14
+ "Intended Audience :: Education",
15
+ "Topic :: Education",
16
+ "License :: OSI Approved :: MIT License",
17
+ "Programming Language :: Python :: 3",
18
+ ]
19
+ keywords = ["telegram", "bot", "education", "learning", "bendband"]
20
+ dependencies = [
21
+ "python-telegram-bot>=21.0,<22.0",
22
+ ]
23
+ requires-python = ">=3.8"
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/bendband/bendbandbot"
27
+ Documentation = "https://bendband.net/bot-course"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,33 @@
1
+ from setuptools import setup, find_packages
2
+
3
+ with open("README.md", "r", encoding="utf-8") as fh:
4
+ long_description = fh.read()
5
+
6
+ setup(
7
+ name="bendbandbot",
8
+ version="1.0.0",
9
+ author="bendband",
10
+ author_email="contact@bendband.net",
11
+ description="Проста бібліотека для створення Telegram ботів для навчання",
12
+ long_description=long_description,
13
+ long_description_content_type="text/markdown",
14
+ url="https://github.com/bendband/bendbandbot",
15
+ packages=find_packages(),
16
+ classifiers=[
17
+ "Development Status :: 5 - Production/Stable",
18
+ "Intended Audience :: Education",
19
+ "Topic :: Education",
20
+ "License :: OSI Approved :: MIT License",
21
+ "Programming Language :: Python :: 3",
22
+ "Programming Language :: Python :: 3.8",
23
+ "Programming Language :: Python :: 3.9",
24
+ "Programming Language :: Python :: 3.10",
25
+ "Programming Language :: Python :: 3.11",
26
+ "Programming Language :: Python :: 3.12",
27
+ ],
28
+ python_requires=">=3.8",
29
+ install_requires=[
30
+ "python-telegram-bot>=21.0,<22.0",
31
+ ],
32
+ keywords="telegram bot education learning школа навчання bendband",
33
+ )
@@ -0,0 +1,292 @@
1
+ """
2
+ Проста бібліотека для створення Telegram ботів
3
+ Спеціально для школярів - без складних конструкцій!
4
+
5
+ Simple library for creating Telegram bots
6
+ Specially for students - no complex constructs!
7
+ """
8
+
9
+ from telegram import Update
10
+ from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
11
+ import asyncio
12
+ from typing import Callable, Optional
13
+ import traceback
14
+ import sys
15
+
16
+
17
+ class SimpleBot:
18
+ """
19
+ Простий Telegram бот для навчання
20
+
21
+ Приклад використання:
22
+ bot = SimpleBot("YOUR_TOKEN")
23
+
24
+ bot.on_command("start", "Hello!")
25
+ bot.start()
26
+ """
27
+
28
+ def __init__(self, token: str):
29
+ """
30
+ Створює нового бота
31
+
32
+ token: токен від @BotFather в Telegram
33
+ """
34
+ if not token or token == "YOUR_TOKEN" or token == "ВАШ_ТОКЕН":
35
+ print("""
36
+ ❌ ПОМИЛКА: Ти не вказав токен бота!
37
+
38
+ 📝 Як отримати токен:
39
+ 1. Відкрий Telegram
40
+ 2. Знайди @BotFather
41
+ 3. Напиши йому: /newbot
42
+ 4. Дай ім'я своєму боту
43
+ 5. Скопіюй токен (довгий рядок типу 1234567890:ABCdef...)
44
+
45
+ 💡 Потім вставте його в код:
46
+ bot = SimpleBot("1234567890:ABCdef...")
47
+ """)
48
+ sys.exit(1)
49
+
50
+ self._token = token
51
+ self._app = None
52
+ self._command_handlers = {}
53
+ self._message_handlers = []
54
+ self._error_handler = None
55
+
56
+ def on_command(self, command: str, function_or_text):
57
+ """
58
+ Що робити коли користувач надсилає команду
59
+
60
+ command: назва команди без / (наприклад: "start", "help")
61
+ function_or_text: або функція, або просто текст для відправки
62
+
63
+ Приклад 1 (дуже просто - тільки текст):
64
+ bot.on_command("start", "Привіт! 👋")
65
+ bot.on_command("help", "Я можу тобі допомогти!")
66
+
67
+ Приклад 2 (з функцією):
68
+ def hello(message):
69
+ bot.send(message, "Hello!")
70
+ bot.on_command("start", hello)
71
+ """
72
+ if command.startswith('/'):
73
+ command = command[1:]
74
+
75
+ # Якщо це рядок, створюємо просту функцію яка його надсилає
76
+ if isinstance(function_or_text, str):
77
+ text = function_or_text
78
+ def simple_handler(message):
79
+ self.send(message, text)
80
+ self._command_handlers[command] = simple_handler
81
+ else:
82
+ # Це функція, реєструємо її
83
+ self._command_handlers[command] = function_or_text
84
+
85
+ def on_message(self, function):
86
+ """
87
+ Що робити коли користувач надсилає звичайне повідомлення
88
+
89
+ function: яку функцію викликати. Отримує message як параметр
90
+
91
+ Приклад:
92
+ def echo(message):
93
+ text = bot.get_text(message)
94
+ bot.send(message, f"Ти написав: {text}")
95
+
96
+ bot.on_message(echo)
97
+ """
98
+ self._message_handlers.append(function)
99
+
100
+ def on_error(self, function):
101
+ """
102
+ Що робити якщо виникла помилка
103
+
104
+ function: функція для обробки помилки. Отримує текст помилки
105
+
106
+ Приклад:
107
+ def handle_error(error):
108
+ print(f"Щось пішло не так: {error}")
109
+
110
+ bot.on_error(handle_error)
111
+ """
112
+ self._error_handler = function
113
+
114
+ def send(self, message, text: str):
115
+ """
116
+ Надіслати відповідь користувачу
117
+
118
+ message: повідомлення від користувача
119
+ text: що надіслати
120
+
121
+ Приклад:
122
+ bot.send(message, "Привіт!")
123
+ """
124
+ try:
125
+ chat_id = self._get_chat_id(message)
126
+ loop = asyncio.get_event_loop()
127
+ if loop.is_running():
128
+ asyncio.create_task(
129
+ self._app.bot.send_message(chat_id=chat_id, text=text)
130
+ )
131
+ else:
132
+ loop.run_until_complete(
133
+ self._app.bot.send_message(chat_id=chat_id, text=text)
134
+ )
135
+ except Exception as e:
136
+ self._handle_error(f"Помилка при надсиланні: {e}")
137
+
138
+ def send_photo(self, message, photo_path: str, caption: str = ""):
139
+ """
140
+ Надіслати фото користувачу
141
+
142
+ message: повідомлення від користувача
143
+ photo_path: шлях до файлу з фото
144
+ caption: текст під фото (не обов'язково)
145
+
146
+ Приклад:
147
+ bot.send_photo(message, "cat.jpg", "Ось кіт!")
148
+ """
149
+ try:
150
+ chat_id = self._get_chat_id(message)
151
+ loop = asyncio.get_event_loop()
152
+
153
+ async def _send():
154
+ with open(photo_path, 'rb') as photo:
155
+ await self._app.bot.send_photo(
156
+ chat_id=chat_id,
157
+ photo=photo,
158
+ caption=caption
159
+ )
160
+
161
+ if loop.is_running():
162
+ asyncio.create_task(_send())
163
+ else:
164
+ loop.run_until_complete(_send())
165
+ except Exception as e:
166
+ self._handle_error(f"Помилка при надсиланні фото: {e}")
167
+
168
+ def get_text(self, message) -> str:
169
+ """
170
+ Отримати текст з повідомлення користувача
171
+
172
+ message: повідомлення від користувача
173
+
174
+ Повертає: текст повідомлення
175
+
176
+ Приклад:
177
+ text = bot.get_text(message)
178
+ print(f"Користувач написав: {text}")
179
+ """
180
+ if hasattr(message, 'message') and message.message:
181
+ return message.message.text or ""
182
+ return ""
183
+
184
+ def get_name(self, message) -> str:
185
+ """
186
+ Отримати ім'я користувача
187
+
188
+ message: повідомлення від користувача
189
+
190
+ Повертає: ім'я користувача
191
+ """
192
+ if hasattr(message, 'message') and message.message:
193
+ user = message.message.from_user
194
+ return user.first_name or user.username or "Анонім"
195
+ return "Анонім"
196
+
197
+ def _get_chat_id(self, message):
198
+ """Внутрішня функція для отримання chat_id"""
199
+ if hasattr(message, 'message') and message.message:
200
+ return message.message.chat_id
201
+ elif hasattr(message, 'chat_id'):
202
+ return message.chat_id
203
+ else:
204
+ raise ValueError("Неможливо знайти chat_id")
205
+
206
+ def _handle_error(self, error_text: str):
207
+ """Внутрішня функція для обробки помилок"""
208
+ print(f"❌ ПОМИЛКА: {error_text}")
209
+ print("─" * 50)
210
+
211
+ if self._error_handler:
212
+ try:
213
+ self._error_handler(error_text)
214
+ except Exception as e:
215
+ print(f"Помилка в обробнику помилок: {e}")
216
+
217
+ def _create_command_handler(self, command: str):
218
+ """Внутрішня функція для створення обробника команди"""
219
+ function = self._command_handlers[command]
220
+
221
+ async def handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
222
+ try:
223
+ # Викликаємо функцію користувача
224
+ result = function(update)
225
+ # Якщо це coroutine, await його
226
+ if asyncio.iscoroutine(result):
227
+ await result
228
+ except Exception as e:
229
+ error = f"Помилка в команді /{command}:\n{traceback.format_exc()}"
230
+ self._handle_error(error)
231
+
232
+ return handler
233
+
234
+ def _create_message_handler(self, function: Callable):
235
+ """Внутрішня функція для створення обробника повідомлень"""
236
+ async def handler(update: Update, context: ContextTypes.DEFAULT_TYPE):
237
+ try:
238
+ result = function(update)
239
+ if asyncio.iscoroutine(result):
240
+ await result
241
+ except Exception as e:
242
+ error = f"Помилка при обробці повідомлення:\n{traceback.format_exc()}"
243
+ self._handle_error(error)
244
+
245
+ return handler
246
+
247
+ def start(self):
248
+ """
249
+ Запустити бота
250
+
251
+ Після виклику цієї функції бот почне працювати.
252
+ Програма буде чекати повідомлень від користувачів.
253
+
254
+ Приклад:
255
+ bot.start()
256
+ """
257
+ print("🤖 Запускаю бота...")
258
+ print("─" * 50)
259
+
260
+ try:
261
+ # Створюємо додаток
262
+ self._app = Application.builder().token(self._token).build()
263
+
264
+ # Додаємо обробники команд
265
+ for command, function in self._command_handlers.items():
266
+ handler = self._create_command_handler(command)
267
+ self._app.add_handler(CommandHandler(command, handler))
268
+ print(f"✅ Команда /{command} готова")
269
+
270
+ # Додаємо обробники повідомлень
271
+ for function in self._message_handlers:
272
+ handler = self._create_message_handler(function)
273
+ self._app.add_handler(
274
+ MessageHandler(filters.TEXT & ~filters.COMMAND, handler)
275
+ )
276
+ print(f"✅ Обробник повідомлень готовий")
277
+
278
+ print("─" * 50)
279
+ print("🎉 Бот працює! Натисни Ctrl+C щоб зупинити")
280
+ print("─" * 50)
281
+
282
+ # Запускаємо
283
+ self._app.run_polling(allowed_updates=Update.ALL_TYPES)
284
+
285
+ except Exception as e:
286
+ error = f"Критична помилка при запуску:\n{traceback.format_exc()}"
287
+ self._handle_error(error)
288
+ print("\n💡 Підказки:")
289
+ print("1. Перевір чи правильний токен від @BotFather")
290
+ print("2. Перевір підключення до інтернету")
291
+ print("3. Переконайся що бібліотека python-telegram-bot встановлена")
292
+ print(" Встанови командою: pip install python-telegram-bot")