rkihacker commited on
Commit
52dc5f7
·
verified ·
1 Parent(s): edf7113

Create main.py

Browse files
Files changed (1) hide show
  1. main.py +89 -0
main.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ from telethon.sync import TelegramClient
4
+ 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")
54
+ async def upload_file(file: UploadFile = File(...)):
55
+ """
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)