alan5543 commited on
Commit
b2f507e
·
1 Parent(s): 143a8e7
Files changed (2) hide show
  1. app.py +44 -101
  2. requirements.txt +2 -1
app.py CHANGED
@@ -1,94 +1,5 @@
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
@@ -96,6 +7,7 @@ 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()
@@ -105,6 +17,10 @@ TELEGRAM_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID")
105
 
106
  bot = Bot(token=TELEGRAM_BOT_TOKEN)
107
 
 
 
 
 
108
  class MessageData(BaseModel):
109
  name: str
110
  email: str
@@ -118,6 +34,27 @@ async def health_check():
118
  "timestamp": datetime.now(timezone.utc).isoformat() + " UTC"
119
  }
120
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
  @app.post("/send-message")
122
  async def send_message(data: MessageData):
123
  try:
@@ -145,17 +82,23 @@ async def send_message(data: MessageData):
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__":
 
1
+ import socket
2
+ import httpx
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  from fastapi import FastAPI, HTTPException
4
  from telegram import Bot
5
  from telegram.error import TelegramError
 
7
  from datetime import datetime, timezone
8
  import os
9
  from dotenv import load_dotenv
10
+ import logging
11
 
12
  app = FastAPI()
13
  load_dotenv()
 
17
 
18
  bot = Bot(token=TELEGRAM_BOT_TOKEN)
19
 
20
+ # Set up logging
21
+ logging.basicConfig(level=logging.DEBUG)
22
+ logger = logging.getLogger(__name__)
23
+
24
  class MessageData(BaseModel):
25
  name: str
26
  email: str
 
34
  "timestamp": datetime.now(timezone.utc).isoformat() + " UTC"
35
  }
36
 
37
+ @app.get("/test-dns")
38
+ async def test_dns():
39
+ try:
40
+ ip = socket.gethostbyname("api.telegram.org")
41
+ logger.info(f"DNS resolved: api.telegram.org -> {ip}")
42
+ return {"status": "success", "ip": ip}
43
+ except socket.gaierror as e:
44
+ logger.error(f"DNS resolution failed: {str(e)}")
45
+ return {"status": "error", "details": str(e)}
46
+
47
+ @app.get("/test-network")
48
+ async def test_network():
49
+ try:
50
+ async with httpx.AsyncClient(timeout=30.0) as client:
51
+ response = await client.get("https://api.ipify.org?format=json")
52
+ logger.info(f"Network test successful: {response.json()}")
53
+ return {"status": "success", "data": response.json()}
54
+ except httpx.HTTPError as e:
55
+ logger.error(f"Network test failed: {str(e)}")
56
+ return {"status": "error", "details": str(e)}
57
+
58
  @app.post("/send-message")
59
  async def send_message(data: MessageData):
60
  try:
 
82
  f"{message}"
83
  )
84
 
85
+ logger.debug(f"Sending message to chat_id: {TELEGRAM_CHAT_ID}")
86
+ async with httpx.AsyncClient(timeout=30.0) as client:
87
+ bot = Bot(token=TELEGRAM_BOT_TOKEN, client=client)
88
+ try:
89
+ await bot.send_message(
90
+ chat_id=TELEGRAM_CHAT_ID,
91
+ text=telegram_message,
92
+ parse_mode="Markdown",
93
+ disable_notification=True
94
+ )
95
+ logger.info("Message sent successfully")
96
+ return {"success": True, "message": "Message sent to Telegram"}
97
+ except TelegramError as e:
98
+ logger.error(f"TelegramError: {str(e)}")
99
+ raise HTTPException(status_code=500, detail=f"Failed to send message: {str(e)}")
100
  except Exception as e:
101
+ logger.error(f"Unexpected error: {str(e)}")
102
  raise HTTPException(status_code=500, detail=f"Server error: {str(e)}")
103
 
104
  if __name__ == "__main__":
requirements.txt CHANGED
@@ -2,4 +2,5 @@ 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
 
 
2
  uvicorn==0.32.0
3
  python-telegram-bot==21.5
4
  pydantic==2.9.2
5
+ python-dotenv==1.0.1
6
+ httpx==0.27.2