| import os, requests |
| from fastapi import FastAPI, Request, HTTPException |
| from aiogram import Bot, Dispatcher, types |
| from database import Database |
| from scoring import analyze_full_submission |
|
|
| BOT_TOKEN = os.environ.get('BOT_TOKEN') |
| if not BOT_TOKEN: |
| raise SystemExit('BOT_TOKEN environment variable not set in Space settings') |
|
|
| WEBHOOK_URL = os.environ.get('WEBHOOK_URL') |
|
|
| app = FastAPI() |
| bot = Bot(BOT_TOKEN) |
| dp = Dispatcher() |
| db = Database('cefr_bot.db') |
|
|
| @dp.message() |
| async def handle_all_messages(msg: types.Message): |
| text = (msg.text or '').strip() |
| if not text: |
| await msg.answer('Please send your writing text (or an image).') |
| return |
| submission = {'task1_1': text, 'task1_2': '', 'task2': ''} |
| result = await analyze_full_submission(submission) |
| await msg.answer(f"Total: {result['total']}/75 → Level: {result['level']}\n\nFeedback:\n{result['feedback']}") |
|
|
| @app.post('/webhook') |
| async def webhook(request: Request): |
| try: |
| data = await request.json() |
| except Exception: |
| raise HTTPException(status_code=400, detail='Invalid JSON') |
| update = types.Update(**data) |
| await dp.feed_update(bot, update) |
| return {'ok': True} |
|
|
| @app.on_event('startup') |
| async def startup_event(): |
| if WEBHOOK_URL: |
| try: |
| set_url = f"https://api.telegram.org/bot{BOT_TOKEN}/setWebhook?url={WEBHOOK_URL}" |
| resp = requests.get(set_url, timeout=15) |
| print('setWebhook response:', resp.text) |
| except Exception as e: |
| print('Failed to set webhook:', e) |
| else: |
| print('WEBHOOK_URL not set — set it in Space settings to https://mkingboi-cefrmefr.hf.space/webhook') |
|
|
| if __name__ == '__main__': |
| import uvicorn |
| uvicorn.run(app, host='0.0.0.0', port=7860) |