mirror of
https://gitlab.com/MoonTestUse1/AdministrationItDepartmens.git
synced 2025-08-14 00:25:46 +02:00
бот не вебхуках
This commit is contained in:
@@ -1,3 +1,3 @@
|
|||||||
TELEGRAM_BOT_TOKEN=7677506032:AAHduD5EePz3bE23DKlo35KoOp2_9lZuS34
|
TELEGRAM_BOT_TOKEN=7677506032:AAHduD5EePz3bE23DKlo35KoOp2_9lZuS34
|
||||||
TELEGRAM_CHAT_ID=5057752127
|
TELEGRAM_CHAT_ID=5057752127
|
||||||
DATABASE_URL=postgresql://support_user:support_password@postgres:5432/support_db
|
DATABASE_URL=postgresql://postgres:postgres123@postgres/support_db
|
||||||
@@ -3,6 +3,7 @@ from fastapi import FastAPI
|
|||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from . import models
|
from . import models
|
||||||
from .routers import admin, employees, requests, auth, statistics
|
from .routers import admin, employees, requests, auth, statistics
|
||||||
|
from .utils.telegram import router as telegram_router
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
@@ -21,3 +22,4 @@ app.include_router(admin.router, prefix="/api/admin", tags=["admin"])
|
|||||||
app.include_router(employees.router, prefix="/api/employees", tags=["employees"])
|
app.include_router(employees.router, prefix="/api/employees", tags=["employees"])
|
||||||
app.include_router(requests.router, prefix="/api/requests", tags=["requests"])
|
app.include_router(requests.router, prefix="/api/requests", tags=["requests"])
|
||||||
app.include_router(statistics.router, prefix="/api/statistics", tags=["statistics"])
|
app.include_router(statistics.router, prefix="/api/statistics", tags=["statistics"])
|
||||||
|
app.include_router(telegram_router)
|
||||||
@@ -1,90 +1,60 @@
|
|||||||
from aiogram import Bot
|
"""Telegram bot utils"""
|
||||||
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton
|
import os
|
||||||
import asyncio
|
from fastapi import APIRouter, Request
|
||||||
from datetime import datetime
|
from telebot import TeleBot
|
||||||
from logging import getLogger
|
from telebot.types import Update
|
||||||
from .constants import (
|
from ..models.request import RequestStatus
|
||||||
STATUS_LABELS, PRIORITY_LABELS, PRIORITY_EMOJI,
|
from ..database import SessionLocal
|
||||||
DEPARTMENT_LABELS, REQUEST_TYPE_LABELS, REQUEST_TYPE_EMOJI
|
from ..models.request import Request as DBRequest
|
||||||
)
|
|
||||||
|
|
||||||
# Initialize logger
|
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
||||||
logger = getLogger(__name__)
|
WEBHOOK_URL = "https://itformhelp.ru/telegram/webhook/"
|
||||||
|
WEBHOOK_PATH = "/telegram/webhook/"
|
||||||
|
|
||||||
# Initialize bot with token
|
bot = TeleBot(TELEGRAM_BOT_TOKEN)
|
||||||
bot = Bot(token="7677506032:AAHduD5EePz3bE23DKlo35KoOp2_9lZuS34")
|
router = APIRouter()
|
||||||
|
|
||||||
# Chat ID for notifications
|
@router.post(WEBHOOK_PATH)
|
||||||
CHAT_ID = "5057752127"
|
async def handle_webhook(request: Request):
|
||||||
|
"""Handle webhook from Telegram"""
|
||||||
|
json_string = await request.json()
|
||||||
|
update = Update.de_json(json_string)
|
||||||
|
bot.process_new_updates([update])
|
||||||
|
return {"ok": True}
|
||||||
|
|
||||||
def create_status_keyboard(request_id: int, current_status: str) -> InlineKeyboardMarkup:
|
def setup_webhook():
|
||||||
"""Create inline keyboard with status buttons"""
|
"""Setup webhook"""
|
||||||
status_transitions = {
|
bot.remove_webhook()
|
||||||
'new': ['in_progress'],
|
bot.set_webhook(url=WEBHOOK_URL)
|
||||||
'in_progress': ['resolved'],
|
|
||||||
'resolved': ['closed'],
|
|
||||||
'closed': []
|
|
||||||
}
|
|
||||||
|
|
||||||
buttons = []
|
@bot.message_handler(commands=['start'])
|
||||||
available_statuses = status_transitions.get(current_status, [])
|
def start(message):
|
||||||
|
"""Handle /start command"""
|
||||||
|
bot.reply_to(message, "Привет! Я бот технической поддержки. Я буду уведомлять вас о статусе ваших заявок.")
|
||||||
|
|
||||||
for status in available_statuses:
|
@bot.message_handler(func=lambda message: True)
|
||||||
callback_data = f"status_{request_id}_{status}"
|
def handle_message(message):
|
||||||
logger.debug(f"Creating button with callback_data: {callback_data}")
|
"""Handle all messages"""
|
||||||
buttons.append([
|
bot.reply_to(message, "Я получил ваше сообщение и обязательно обработаю его!")
|
||||||
InlineKeyboardButton(
|
|
||||||
text=STATUS_LABELS[status],
|
|
||||||
callback_data=callback_data
|
|
||||||
)
|
|
||||||
])
|
|
||||||
|
|
||||||
keyboard = InlineKeyboardMarkup(inline_keyboard=buttons)
|
def notify_status_change(request_id: int, new_status: RequestStatus):
|
||||||
logger.debug(f"Created keyboard: {keyboard}")
|
"""Notify user about request status change"""
|
||||||
return keyboard
|
|
||||||
|
|
||||||
def format_request_message(request_data: dict) -> str:
|
|
||||||
"""Format request data into a message"""
|
|
||||||
created_at = datetime.fromisoformat(request_data['created_at']).strftime('%d.%m.%Y %H:%M')
|
|
||||||
|
|
||||||
# Get translated values
|
|
||||||
department = DEPARTMENT_LABELS.get(request_data['department'], request_data['department'])
|
|
||||||
request_type = REQUEST_TYPE_LABELS.get(request_data['request_type'], request_data['request_type'])
|
|
||||||
priority = PRIORITY_LABELS.get(request_data['priority'], request_data['priority'])
|
|
||||||
status = STATUS_LABELS.get(request_data.get('status', 'new'), 'Неизвестно')
|
|
||||||
|
|
||||||
return (
|
|
||||||
f"📋 <b>Заявка #{request_data['id']}</b>\n\n"
|
|
||||||
f"👤 <b>Сотрудник:</b> {request_data['employee_last_name']} {request_data['employee_first_name']}\n"
|
|
||||||
f"🏢 <b>Отдел:</b> {department}\n"
|
|
||||||
f"🚪 <b>Кабинет:</b> {request_data['office']}\n"
|
|
||||||
f"{REQUEST_TYPE_EMOJI.get(request_data['request_type'], '📝')} <b>Тип заявки:</b> {request_type}\n"
|
|
||||||
f"{PRIORITY_EMOJI.get(request_data['priority'], '⚪')} <b>Приоритет:</b> {priority}\n\n"
|
|
||||||
f"📝 <b>Описание:</b>\n{request_data['description']}\n\n"
|
|
||||||
f"🕒 <b>Создана:</b> {created_at}\n"
|
|
||||||
f"📊 <b>Статус:</b> {status}"
|
|
||||||
)
|
|
||||||
|
|
||||||
async def send_request_notification(request_data: dict):
|
|
||||||
"""Send notification about request to Telegram"""
|
|
||||||
try:
|
try:
|
||||||
message = format_request_message(request_data)
|
db = SessionLocal()
|
||||||
keyboard = create_status_keyboard(request_data['id'], request_data.get('status', 'new'))
|
request = db.query(DBRequest).filter(DBRequest.id == request_id).first()
|
||||||
|
if request and request.employee and request.employee.telegram_id:
|
||||||
await bot.send_message(
|
status_messages = {
|
||||||
chat_id=CHAT_ID,
|
RequestStatus.NEW: "создана",
|
||||||
text=message,
|
RequestStatus.IN_PROGRESS: "взята в работу",
|
||||||
parse_mode="HTML",
|
RequestStatus.COMPLETED: "выполнена",
|
||||||
reply_markup=keyboard
|
RequestStatus.REJECTED: "отклонена"
|
||||||
)
|
}
|
||||||
|
message = f"Статус вашей заявки №{request.id} изменен на: {status_messages.get(new_status, new_status)}"
|
||||||
|
bot.send_message(request.employee.telegram_id, message)
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error sending Telegram notification: {e}", exc_info=True)
|
print(f"Error sending telegram notification: {e}")
|
||||||
raise
|
finally:
|
||||||
|
db.close()
|
||||||
|
|
||||||
def send_notification(request_data: dict):
|
# Инициализация вебхука при запуске
|
||||||
"""Wrapper to run async notification in sync context"""
|
setup_webhook()
|
||||||
try:
|
|
||||||
asyncio.run(send_request_notification(request_data))
|
|
||||||
except Exception as e:
|
|
||||||
logger.error(f"Failed to send notification: {e}", exc_info=True)
|
|
||||||
raise
|
|
||||||
@@ -25,6 +25,18 @@ server {
|
|||||||
root /usr/share/nginx/html;
|
root /usr/share/nginx/html;
|
||||||
index index.html;
|
index index.html;
|
||||||
|
|
||||||
|
# Telegram webhook proxy
|
||||||
|
location /telegram/webhook/ {
|
||||||
|
proxy_pass http://support-backend:8000/telegram/webhook/;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection 'upgrade';
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
}
|
||||||
|
|
||||||
# API proxy
|
# API proxy
|
||||||
location /api/ {
|
location /api/ {
|
||||||
proxy_pass http://support-backend:8000;
|
proxy_pass http://support-backend:8000;
|
||||||
|
|||||||
Reference in New Issue
Block a user