rkihacker commited on
Commit
ecb5535
·
verified ·
1 Parent(s): e8b509f

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +56 -27
main.py CHANGED
@@ -5,71 +5,100 @@ from telethon.sessions import StringSession
5
  from fastapi import FastAPI, UploadFile, File, HTTPException
6
  from fastapi.responses import FileResponse
7
  import uvicorn
8
- import tempfile # Import the tempfile module
9
 
10
  # --- Configuration from environment variables ---
11
- # Your Telegram session string
12
  SESSION_STRING = os.environ.get('SESSION_STRING')
13
-
14
- # You MUST get your own API ID and HASH from my.telegram.org
15
  API_ID = os.environ.get('API_ID')
16
  API_HASH = os.environ.get('API_HASH')
17
 
18
- # The Telegram channel you want to upload files to
19
  TARGET_CHANNEL = 'https://t.me/TestNAI01'
20
 
21
- # --- FIX: Use the system's temporary directory ---
22
- # This directory is guaranteed to be writable and avoids permission errors.
23
  UPLOAD_DIR = tempfile.gettempdir()
24
 
25
  app = FastAPI()
26
 
27
  async def upload_to_telegram(file_path: str):
28
  """
29
- Uploads a file to the specified Telegram channel using a session string.
30
  """
31
  if not all([SESSION_STRING, API_ID, API_HASH]):
32
  raise ValueError("SESSION_STRING, API_ID, and API_HASH must be set as environment variables.")
33
 
34
- # Initialize the client
35
  async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH) as client:
36
  try:
37
- await client.send_file(TARGET_CHANNEL, file_path)
 
 
 
 
 
38
  except Exception as e:
39
  raise HTTPException(status_code=500, detail=f"Failed to upload to Telegram: {e}")
40
 
41
  @app.post("/v1/upload")
42
  async def upload_file(file: UploadFile = File(...)):
43
  """
44
- Receives a file, saves it to the temp directory, and uploads it to the Telegram channel.
45
  """
46
- # Create a secure path in the temporary directory
47
  file_location = os.path.join(UPLOAD_DIR, file.filename)
48
  try:
49
- # Save the uploaded file temporarily
50
  with open(file_location, "wb+") as file_object:
51
  file_object.write(file.file.read())
52
 
53
- # Upload the file to Telegram
54
- await upload_to_telegram(file_location)
55
- return {"message": f"File '{file.filename}' uploaded successfully to Telegram."}
 
 
 
 
 
 
 
 
 
 
56
  finally:
57
- # Clean up the local file after uploading to save space
58
  if os.path.exists(file_location):
59
  os.remove(file_location)
60
 
61
- @app.get("/v1/download/{filename}")
62
- async def download_file(filename: str):
63
  """
64
- Serves a file for download.
65
- NOTE: This endpoint is for demonstration. It looks for files in the temp
66
- directory, but files uploaded in previous requests will have been deleted.
67
- A production system would need a proper way to retrieve files from Telegram.
68
  """
69
- file_path = os.path.join(UPLOAD_DIR, filename)
70
- if os.path.exists(file_path):
71
- return FileResponse(file_path)
72
- raise HTTPException(status_code=404, detail="File not found. Files are only stored temporarily during upload.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
73
 
74
  if __name__ == "__main__":
75
  if not all([SESSION_STRING, API_ID, API_HASH]):
 
5
  from fastapi import FastAPI, UploadFile, File, HTTPException
6
  from fastapi.responses import FileResponse
7
  import uvicorn
8
+ import tempfile
9
 
10
  # --- Configuration from environment variables ---
 
11
  SESSION_STRING = os.environ.get('SESSION_STRING')
 
 
12
  API_ID = os.environ.get('API_ID')
13
  API_HASH = os.environ.get('API_HASH')
14
 
15
+ # The Telegram channel to use as file storage
16
  TARGET_CHANNEL = 'https://t.me/TestNAI01'
17
 
18
+ # Use the system's temporary directory for transient files
 
19
  UPLOAD_DIR = tempfile.gettempdir()
20
 
21
  app = FastAPI()
22
 
23
  async def upload_to_telegram(file_path: str):
24
  """
25
+ Uploads a file to the Telegram channel and returns the message object.
26
  """
27
  if not all([SESSION_STRING, API_ID, API_HASH]):
28
  raise ValueError("SESSION_STRING, API_ID, and API_HASH must be set as environment variables.")
29
 
 
30
  async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH) as client:
31
  try:
32
+ # Send the file and wait for the message object to be returned
33
+ message = await client.send_file(TARGET_CHANNEL, file_path)
34
+ # Check if the upload was successful and returned a message with media
35
+ if not message or not message.media:
36
+ raise HTTPException(status_code=500, detail="File uploaded but failed to receive a valid message object from Telegram.")
37
+ return message
38
  except Exception as e:
39
  raise HTTPException(status_code=500, detail=f"Failed to upload to Telegram: {e}")
40
 
41
  @app.post("/v1/upload")
42
  async def upload_file(file: UploadFile = File(...)):
43
  """
44
+ Receives a file, uploads it to Telegram, and returns the Telegram message ID.
45
  """
 
46
  file_location = os.path.join(UPLOAD_DIR, file.filename)
47
  try:
 
48
  with open(file_location, "wb+") as file_object:
49
  file_object.write(file.file.read())
50
 
51
+ # Upload the file and get the message object
52
+ message = await upload_to_telegram(file_location)
53
+
54
+ # The message ID is the permanent identifier for the file
55
+ telegram_file_id = message.id
56
+ original_filename = message.file.name if message.file and message.file.name else file.filename
57
+
58
+ return {
59
+ "message": "File uploaded successfully to Telegram.",
60
+ "telegram_file_id": telegram_file_id,
61
+ "filename": original_filename,
62
+ "channel": TARGET_CHANNEL
63
+ }
64
  finally:
65
+ # Clean up the local temporary file
66
  if os.path.exists(file_location):
67
  os.remove(file_location)
68
 
69
+ @app.get("/v1/download/{message_id}")
70
+ async def download_file(message_id: int):
71
  """
72
+ Downloads a file from Telegram using its message ID.
 
 
 
73
  """
74
+ if not all([SESSION_STRING, API_ID, API_HASH]):
75
+ raise HTTPException(status_code=500, detail="Server is not configured with Telegram credentials.")
76
+
77
+ download_path = None
78
+ try:
79
+ async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH) as client:
80
+ # Get the specific message from the channel using the message_id
81
+ message = await client.get_messages(TARGET_CHANNEL, ids=message_id)
82
+
83
+ if not message or not message.media:
84
+ raise HTTPException(status_code=404, detail="Message not found or it contains no media.")
85
+
86
+ # Download the media to the temporary directory
87
+ # Telethon will return the path where the file was saved
88
+ download_path = await client.download_media(message, file=UPLOAD_DIR)
89
+
90
+ # Determine the filename to send to the user
91
+ response_filename = message.file.name if message.file and message.file.name else "downloaded_file"
92
+
93
+ # Return the file as a response
94
+ return FileResponse(download_path, media_type='application/octet-stream', filename=response_filename)
95
+
96
+ except Exception as e:
97
+ raise HTTPException(status_code=500, detail=f"Failed to download file from Telegram: {e}")
98
+ finally:
99
+ # Crucially, clean up the downloaded file from the server's temp storage
100
+ if download_path and os.path.exists(download_path):
101
+ os.remove(download_path)
102
 
103
  if __name__ == "__main__":
104
  if not all([SESSION_STRING, API_ID, API_HASH]):