Spaces:
Paused
Paused
alan5543
commited on
Commit
·
143a8e7
1
Parent(s):
f90762d
update
Browse files- app.py +130 -57
- requirements.txt +5 -4
app.py
CHANGED
|
@@ -1,14 +1,103 @@
|
|
| 1 |
-
from flask import Flask, request, jsonify
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
from telegram import Bot
|
| 3 |
from telegram.error import TelegramError
|
| 4 |
-
from
|
| 5 |
-
|
| 6 |
-
# Change this import
|
| 7 |
-
from datetime import datetime, timezone # instead of just datetime
|
| 8 |
import os
|
| 9 |
-
import
|
| 10 |
|
| 11 |
-
app =
|
| 12 |
load_dotenv()
|
| 13 |
|
| 14 |
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
|
@@ -16,54 +105,32 @@ TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
|
|
| 16 |
|
| 17 |
bot = Bot(token=TELEGRAM_BOT_TOKEN)
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
text=message,
|
| 24 |
-
parse_mode="Markdown",
|
| 25 |
-
disable_notification=True
|
| 26 |
-
)
|
| 27 |
-
return {"ok": True}
|
| 28 |
-
except TelegramError as e:
|
| 29 |
-
return {"ok": False, "error": str(e)}
|
| 30 |
-
|
| 31 |
-
def send_telegram_message(message):
|
| 32 |
-
# Run async function in Flask's synchronous context
|
| 33 |
-
loop = asyncio.new_event_loop()
|
| 34 |
-
asyncio.set_event_loop(loop)
|
| 35 |
-
result = loop.run_until_complete(send_telegram_message_async(message))
|
| 36 |
-
loop.close()
|
| 37 |
-
return result
|
| 38 |
-
|
| 39 |
-
@app.route('/', methods=['GET'])
|
| 40 |
-
def health_check():
|
| 41 |
-
return jsonify(
|
| 42 |
-
{
|
| 43 |
-
"status": "healthy",
|
| 44 |
-
"message": "Telegram backend is running",
|
| 45 |
-
"timestamp": datetime.now(timezone.utc).isoformat() + " UTC"
|
| 46 |
-
}
|
| 47 |
-
)
|
| 48 |
-
|
| 49 |
-
@app.route('/send-message', methods=['POST'])
|
| 50 |
-
def send_message():
|
| 51 |
-
try:
|
| 52 |
-
data = request.get_json()
|
| 53 |
-
required_fields = ['name', 'email', 'message']
|
| 54 |
-
if not all(field in data for field in required_fields):
|
| 55 |
-
return jsonify({"error": "Missing required fields: name, email, message"}), 400
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
|
| 61 |
if not all([name, email, message]):
|
| 62 |
-
|
| 63 |
if len(message) > 4096:
|
| 64 |
-
|
| 65 |
if '@' not in email or '.' not in email.split('@')[1]:
|
| 66 |
-
|
| 67 |
|
| 68 |
timestamp = datetime.now(timezone.utc).isoformat().split('.')[0] + " UTC"
|
| 69 |
telegram_message = (
|
|
@@ -78,13 +145,19 @@ def send_message():
|
|
| 78 |
f"{message}"
|
| 79 |
)
|
| 80 |
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 86 |
except Exception as e:
|
| 87 |
-
|
| 88 |
|
| 89 |
if __name__ == "__main__":
|
| 90 |
-
|
|
|
|
|
|
| 1 |
+
# from flask import Flask, request, jsonify
|
| 2 |
+
# from telegram import Bot
|
| 3 |
+
# from telegram.error import TelegramError
|
| 4 |
+
# from dotenv import load_dotenv
|
| 5 |
+
|
| 6 |
+
# # Change this import
|
| 7 |
+
# from datetime import datetime, timezone # instead of just datetime
|
| 8 |
+
# import os
|
| 9 |
+
# import asyncio
|
| 10 |
+
|
| 11 |
+
# app = Flask(__name__)
|
| 12 |
+
# load_dotenv()
|
| 13 |
+
|
| 14 |
+
# TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
| 15 |
+
# TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
|
| 16 |
+
|
| 17 |
+
# bot = Bot(token=TELEGRAM_BOT_TOKEN)
|
| 18 |
+
|
| 19 |
+
# async def send_telegram_message_async(message):
|
| 20 |
+
# try:
|
| 21 |
+
# await bot.send_message(
|
| 22 |
+
# chat_id=TELEGRAM_CHAT_ID,
|
| 23 |
+
# text=message,
|
| 24 |
+
# parse_mode="Markdown",
|
| 25 |
+
# disable_notification=True
|
| 26 |
+
# )
|
| 27 |
+
# return {"ok": True}
|
| 28 |
+
# except TelegramError as e:
|
| 29 |
+
# return {"ok": False, "error": str(e)}
|
| 30 |
+
|
| 31 |
+
# def send_telegram_message(message):
|
| 32 |
+
# # Run async function in Flask's synchronous context
|
| 33 |
+
# loop = asyncio.new_event_loop()
|
| 34 |
+
# asyncio.set_event_loop(loop)
|
| 35 |
+
# result = loop.run_until_complete(send_telegram_message_async(message))
|
| 36 |
+
# loop.close()
|
| 37 |
+
# return result
|
| 38 |
+
|
| 39 |
+
# @app.route('/', methods=['GET'])
|
| 40 |
+
# def health_check():
|
| 41 |
+
# return jsonify(
|
| 42 |
+
# {
|
| 43 |
+
# "status": "healthy",
|
| 44 |
+
# "message": "Telegram backend is running",
|
| 45 |
+
# "timestamp": datetime.now(timezone.utc).isoformat() + " UTC"
|
| 46 |
+
# }
|
| 47 |
+
# )
|
| 48 |
+
|
| 49 |
+
# @app.route('/send-message', methods=['POST'])
|
| 50 |
+
# def send_message():
|
| 51 |
+
# try:
|
| 52 |
+
# data = request.get_json()
|
| 53 |
+
# required_fields = ['name', 'email', 'message']
|
| 54 |
+
# if not all(field in data for field in required_fields):
|
| 55 |
+
# return jsonify({"error": "Missing required fields: name, email, message"}), 400
|
| 56 |
+
|
| 57 |
+
# name = data['name'].strip()
|
| 58 |
+
# email = data['email'].strip()
|
| 59 |
+
# message = data['message'].strip()
|
| 60 |
+
|
| 61 |
+
# if not all([name, email, message]):
|
| 62 |
+
# return jsonify({"error": "All fields must not be empty"}), 400
|
| 63 |
+
# if len(message) > 4096:
|
| 64 |
+
# return jsonify({"error": "Message exceeds 4096 character limit"}), 400
|
| 65 |
+
# if '@' not in email or '.' not in email.split('@')[1]:
|
| 66 |
+
# return jsonify({"error": "Invalid email format"}), 400
|
| 67 |
+
|
| 68 |
+
# timestamp = datetime.now(timezone.utc).isoformat().split('.')[0] + " UTC"
|
| 69 |
+
# telegram_message = (
|
| 70 |
+
# f"*New Message*\n"
|
| 71 |
+
# f"_Received on: {timestamp}_\n"
|
| 72 |
+
# f"---\n"
|
| 73 |
+
# f"*Sender Details:*\n"
|
| 74 |
+
# f"- *Name:* {name}\n"
|
| 75 |
+
# f"- *Email:* {email}\n"
|
| 76 |
+
# f"---\n"
|
| 77 |
+
# f"*Message:*\n"
|
| 78 |
+
# f"{message}"
|
| 79 |
+
# )
|
| 80 |
+
|
| 81 |
+
# result = send_telegram_message(telegram_message)
|
| 82 |
+
# if result.get("ok"):
|
| 83 |
+
# return jsonify({"success": True, "message": "Message sent to Telegram"}), 200
|
| 84 |
+
# else:
|
| 85 |
+
# return jsonify({"error": "Failed to send message", "details": result.get("error", "Unknown error")}), 500
|
| 86 |
+
# except Exception as e:
|
| 87 |
+
# return jsonify({"error": f"Server error: {str(e)}"}), 500
|
| 88 |
+
|
| 89 |
+
# if __name__ == "__main__":
|
| 90 |
+
# app.run(host="0.0.0.0", port=7860)
|
| 91 |
+
|
| 92 |
+
from fastapi import FastAPI, HTTPException
|
| 93 |
from telegram import Bot
|
| 94 |
from telegram.error import TelegramError
|
| 95 |
+
from pydantic import BaseModel
|
| 96 |
+
from datetime import datetime, timezone
|
|
|
|
|
|
|
| 97 |
import os
|
| 98 |
+
from dotenv import load_dotenv
|
| 99 |
|
| 100 |
+
app = FastAPI()
|
| 101 |
load_dotenv()
|
| 102 |
|
| 103 |
TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN")
|
|
|
|
| 105 |
|
| 106 |
bot = Bot(token=TELEGRAM_BOT_TOKEN)
|
| 107 |
|
| 108 |
+
class MessageData(BaseModel):
|
| 109 |
+
name: str
|
| 110 |
+
email: str
|
| 111 |
+
message: str
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
+
@app.get("/health")
|
| 114 |
+
async def health_check():
|
| 115 |
+
return {
|
| 116 |
+
"status": "healthy",
|
| 117 |
+
"message": "Telegram backend is running",
|
| 118 |
+
"timestamp": datetime.now(timezone.utc).isoformat() + " UTC"
|
| 119 |
+
}
|
| 120 |
+
|
| 121 |
+
@app.post("/send-message")
|
| 122 |
+
async def send_message(data: MessageData):
|
| 123 |
+
try:
|
| 124 |
+
name = data.name.strip()
|
| 125 |
+
email = data.email.strip()
|
| 126 |
+
message = data.message.strip()
|
| 127 |
|
| 128 |
if not all([name, email, message]):
|
| 129 |
+
raise HTTPException(status_code=400, detail="All fields must not be empty")
|
| 130 |
if len(message) > 4096:
|
| 131 |
+
raise HTTPException(status_code=400, detail="Message exceeds 4096 character limit")
|
| 132 |
if '@' not in email or '.' not in email.split('@')[1]:
|
| 133 |
+
raise HTTPException(status_code=400, detail="Invalid email format")
|
| 134 |
|
| 135 |
timestamp = datetime.now(timezone.utc).isoformat().split('.')[0] + " UTC"
|
| 136 |
telegram_message = (
|
|
|
|
| 145 |
f"{message}"
|
| 146 |
)
|
| 147 |
|
| 148 |
+
try:
|
| 149 |
+
await bot.send_message(
|
| 150 |
+
chat_id=TELEGRAM_CHAT_ID,
|
| 151 |
+
text=telegram_message,
|
| 152 |
+
parse_mode="Markdown",
|
| 153 |
+
disable_notification=True
|
| 154 |
+
)
|
| 155 |
+
return {"success": True, "message": "Message sent to Telegram"}
|
| 156 |
+
except TelegramError as e:
|
| 157 |
+
raise HTTPException(status_code=500, detail=f"Failed to send message: {str(e)}")
|
| 158 |
except Exception as e:
|
| 159 |
+
raise HTTPException(status_code=500, detail=f"Server error: {str(e)}")
|
| 160 |
|
| 161 |
if __name__ == "__main__":
|
| 162 |
+
import uvicorn
|
| 163 |
+
uvicorn.run(app, host="0.0.0.0", port=7860)
|
requirements.txt
CHANGED
|
@@ -1,4 +1,5 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
python-
|
| 4 |
-
|
|
|
|
|
|
| 1 |
+
fastapi==0.115.2
|
| 2 |
+
uvicorn==0.32.0
|
| 3 |
+
python-telegram-bot==21.5
|
| 4 |
+
pydantic==2.9.2
|
| 5 |
+
python-dotenv==1.0.1
|