-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.py
More file actions
203 lines (161 loc) · 5.89 KB
/
api.py
File metadata and controls
203 lines (161 loc) · 5.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
from flask import Flask, request, jsonify
from telegram import Bot
import asyncio
import database as db
# Импортируем токен
try:
from config import BOT_TOKEN
except ImportError:
print("❌ ОШИБКА: Файл config.py не найден!")
exit(1)
app = Flask(__name__)
bot = Bot(token=BOT_TOKEN)
# ============= ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ =============
def run_async(coro):
"""Запускает асинхронную функцию в синхронном контексте"""
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
return loop.run_until_complete(coro)
finally:
loop.close()
# ============= API ЭНДПОИНТЫ =============
@app.route('/api/health', methods=['GET'])
def health_check():
"""Проверка работоспособности API"""
return jsonify({
'status': 'ok',
'message': 'HR Notification Bot API is running',
'version': '1.0.0'
}), 200
@app.route('/api/users', methods=['GET'])
def get_users():
"""Получить список всех пользователей"""
users = db.get_all_users_full()
users_list = []
for username, full_name, is_admin, created_at in users:
users_list.append({
'username': username,
'full_name': full_name,
'is_admin': bool(is_admin),
'created_at': created_at
})
return jsonify({
'status': 'success',
'count': len(users_list),
'users': users_list
}), 200
@app.route('/api/news', methods=['POST'])
def add_news():
"""Добавить новость"""
data = request.get_json()
if not data or 'text' not in data:
return jsonify({
'status': 'error',
'message': 'Missing "text" field in request body'
}), 400
news_text = data['text']
# Добавляем новость в базу
db.add_news(news_text)
return jsonify({
'status': 'success',
'message': 'News added successfully',
'news': news_text
}), 201
@app.route('/api/broadcast', methods=['POST'])
def broadcast_message():
"""Массовая рассылка всем пользователям"""
data = request.get_json()
if not data or 'message' not in data:
return jsonify({
'status': 'error',
'message': 'Missing "message" field in request body'
}), 400
message_text = data['message']
# Получаем всех пользователей
users = db.get_all_users()
if not users:
return jsonify({
'status': 'error',
'message': 'No users found in database'
}), 404
sent_count = 0
failed_count = 0
errors = []
# Отправляем сообщение каждому пользователю
for chat_id, username in users:
try:
run_async(bot.send_message(
chat_id=chat_id,
text=f"📢 *Сообщение от HR-отдела*\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n\n"
f"{message_text}",
parse_mode='Markdown'
))
sent_count += 1
except Exception as e:
failed_count += 1
errors.append({
'username': username,
'error': str(e)
})
return jsonify({
'status': 'success',
'message': 'Broadcast completed',
'sent': sent_count,
'failed': failed_count,
'total_users': len(users),
'errors': errors if errors else None
}), 200
@app.route('/api/send', methods=['POST'])
def send_to_user():
"""Отправить сообщение конкретному пользователю"""
data = request.get_json()
if not data or 'username' not in data or 'message' not in data:
return jsonify({
'status': 'error',
'message': 'Missing "username" or "message" field in request body'
}), 400
username = data['username']
message_text = data['message']
# Ищем пользователя в базе
user = db.get_user_by_username(username)
if not user:
return jsonify({
'status': 'error',
'message': f'User "{username}" not found in database'
}), 404
chat_id, _ = user
# Отправляем сообщение
try:
run_async(bot.send_message(
chat_id=chat_id,
text=f"💌 *Личное сообщение от HR-отдела*\n"
f"━━━━━━━━━━━━━━━━━━━━━━\n\n"
f"{message_text}",
parse_mode='Markdown'
))
return jsonify({
'status': 'success',
'message': f'Message sent to {username}',
'recipient': username
}), 200
except Exception as e:
return jsonify({
'status': 'error',
'message': f'Failed to send message: {str(e)}'
}), 500
# ============= ЗАПУСК API =============
if __name__ == '__main__':
print("🚀 Запуск HR Notification Bot API...")
print("📡 API доступен по адресу: http://localhost:5001")
print("\n📋 Доступные эндпоинты:")
print(" GET /api/health - Проверка работоспособности")
print(" GET /api/users - Список всех пользователей")
print(" POST /api/news - Добавить новость")
print(" POST /api/broadcast - Массовая рассылка")
print(" POST /api/send - Личное сообщение\n")
# Инициализируем базу данных
db.init_db()
# Запускаем Flask-сервер
app.run(host='0.0.0.0', port=5001, debug=False)