rkihacker commited on
Commit
eb586a3
·
verified ·
1 Parent(s): ff2d189

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +26 -36
main.py CHANGED
@@ -5,49 +5,38 @@ from telethon.sessions import StringSession
5
  from fastapi import FastAPI, UploadFile, File, HTTPException
6
  from fastapi.responses import FileResponse
7
  import uvicorn
8
- import socks
9
 
10
- # Configuration from environment variables
 
11
  SESSION_STRING = os.environ.get('SESSION_STRING')
12
- API_ID = os.environ.get('API_ID') # You need to get your API_ID from my.telegram.org
13
- API_HASH = os.environ.get('API_HASH') # You need to get your API_HASH from my.telegram.org
14
- PROXY_IP = os.environ.get('PROXY_IP')
15
- PROXY_PORT = os.environ.get('PROXY_PORT')
16
- PROXY_TYPE = os.environ.get('PROXY_TYPE', 'socks5').lower() # Default to socks5
17
 
18
  # The Telegram channel you want to upload files to
19
  TARGET_CHANNEL = 'https://t.me/TestNAI01'
20
 
21
  # Directory to store uploaded files temporarily
22
  UPLOAD_DIR = "uploads"
 
23
  os.makedirs(UPLOAD_DIR, exist_ok=True)
24
 
25
  app = FastAPI()
26
 
27
- def get_proxy():
28
- """Returns proxy settings if configured."""
29
- if PROXY_IP and PROXY_PORT:
30
- proxy_type_map = {
31
- 'socks4': socks.SOCKS4,
32
- 'socks5': socks.SOCKS5,
33
- 'http': socks.HTTP,
34
- }
35
- return (proxy_type_map.get(PROXY_TYPE, socks.SOCKS5), PROXY_IP, int(PROXY_PORT))
36
- return None
37
-
38
  async def upload_to_telegram(file_path: str):
39
  """
40
  Uploads a file to the specified Telegram channel using a session string.
41
  """
42
- if not SESSION_STRING or not API_ID or not API_HASH:
43
- raise ValueError("SESSION_STRING, API_ID, and API_HASH must be set in environment variables.")
44
-
45
- proxy = get_proxy()
46
 
47
- async with TelegramClient(StringSession(SESSION_STRING), API_ID, API_HASH, proxy=proxy) as client:
 
48
  try:
49
  await client.send_file(TARGET_CHANNEL, file_path)
50
  except Exception as e:
 
51
  raise HTTPException(status_code=500, detail=f"Failed to upload to Telegram: {e}")
52
 
53
  @app.post("/v1/upload")
@@ -56,34 +45,35 @@ async def upload_file(file: UploadFile = File(...)):
56
  Receives a file and uploads it to the Telegram channel.
57
  """
58
  file_location = os.path.join(UPLOAD_DIR, file.filename)
59
- with open(file_location, "wb+") as file_object:
60
- file_object.write(file.file.read())
61
-
62
  try:
 
 
 
 
 
63
  await upload_to_telegram(file_location)
64
  return {"message": f"File '{file.filename}' uploaded successfully to Telegram."}
65
  finally:
66
- # Clean up the local file after uploading
67
  if os.path.exists(file_location):
68
  os.remove(file_location)
69
 
70
  @app.get("/v1/download/{filename}")
71
  async def download_file(filename: str):
72
  """
73
- Serves a file for download.
74
- Note: This endpoint serves files from the local 'uploads' directory.
75
- For a production system, you would need a more robust way to retrieve files,
76
- possibly by storing a mapping of filenames to Telegram message IDs.
77
  """
78
  file_path = os.path.join(UPLOAD_DIR, filename)
79
  if os.path.exists(file_path):
80
  return FileResponse(file_path)
81
- raise HTTPException(status_code=404, detail="File not found. This is a simple server; for production, a proper file retrieval from Telegram would be needed.")
82
 
83
  if __name__ == "__main__":
84
- # This block is for local testing without Docker
85
- # To run with Docker, the CMD in the Dockerfile will be used
86
  if not all([SESSION_STRING, API_ID, API_HASH]):
87
- print("Error: SESSION_STRING, API_ID, and API_HASH environment variables must be set.")
88
  else:
89
- uvicorn.run(app, host="0.0.0.0", port=8000)
 
5
  from fastapi import FastAPI, UploadFile, File, HTTPException
6
  from fastapi.responses import FileResponse
7
  import uvicorn
 
8
 
9
+ # --- Configuration from environment variables ---
10
+ # Your Telegram session string
11
  SESSION_STRING = os.environ.get('SESSION_STRING')
12
+
13
+ # You MUST get your own API ID and HASH from my.telegram.org
14
+ API_ID = os.environ.get('API_ID')
15
+ API_HASH = os.environ.get('API_HASH')
 
16
 
17
  # The Telegram channel you want to upload files to
18
  TARGET_CHANNEL = 'https://t.me/TestNAI01'
19
 
20
  # Directory to store uploaded files temporarily
21
  UPLOAD_DIR = "uploads"
22
+ # This line ensures the directory exists. It will now succeed due to Dockerfile permissions.
23
  os.makedirs(UPLOAD_DIR, exist_ok=True)
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 without proxy settings
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
+ # Provide a more specific error message if upload fails
40
  raise HTTPException(status_code=500, detail=f"Failed to upload to Telegram: {e}")
41
 
42
  @app.post("/v1/upload")
 
45
  Receives a file and uploads it to the Telegram channel.
46
  """
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 from the local 'uploads' directory.
65
+ NOTE: This is a basic implementation. For a production system, you would need a
66
+ more robust method to retrieve files, perhaps by downloading them from Telegram
67
+ on-demand instead of storing them locally.
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 on this server.")
73
 
74
  if __name__ == "__main__":
75
+ # This block allows running the script directly for local testing (without Docker)
 
76
  if not all([SESSION_STRING, API_ID, API_HASH]):
77
+ print("FATAL ERROR: The environment variables SESSION_STRING, API_ID, and API_HASH must be set.")
78
  else:
79
+ uvicorn.run(app, host="0.0.0.0", port=8000)```