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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import tempfile
|
| 5 |
+
import asyncio
|
| 6 |
+
from datetime import datetime, timedelta
|
| 7 |
+
from pySmartDL import SmartDL
|
| 8 |
+
from pydrive2.auth import GoogleAuth
|
| 9 |
+
from pydrive2.drive import GoogleDrive
|
| 10 |
+
from oauth2client.service_account import ServiceAccountCredentials
|
| 11 |
+
from telegram import Update
|
| 12 |
+
from telegram.ext import ApplicationBuilder, CommandHandler, MessageHandler, filters, ContextTypes
|
| 13 |
+
from apscheduler.schedulers.background import BackgroundScheduler
|
| 14 |
+
|
| 15 |
+
# Logging setup
|
| 16 |
+
logging.basicConfig(
|
| 17 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
| 18 |
+
level=logging.INFO
|
| 19 |
+
)
|
| 20 |
+
logger = logging.getLogger(__name__)
|
| 21 |
+
|
| 22 |
+
# Environment Variables
|
| 23 |
+
BOT_TOKEN = os.getenv("BOT_TOKEN")
|
| 24 |
+
GDRIVE_SERVICE_ACCOUNT_JSON = os.getenv("GDRIVE_SERVICE_ACCOUNT_JSON")
|
| 25 |
+
GDRIVE_FOLDER_ID = os.getenv("GDRIVE_FOLDER_ID")
|
| 26 |
+
AUTHORIZED_USER_ID = os.getenv("AUTHORIZED_USER_ID")
|
| 27 |
+
|
| 28 |
+
if AUTHORIZED_USER_ID:
|
| 29 |
+
AUTHORIZED_USER_ID = int(AUTHORIZED_USER_ID)
|
| 30 |
+
|
| 31 |
+
# Global Drive Client variable and processing lock
|
| 32 |
+
drive_client = None
|
| 33 |
+
processing_lock = asyncio.Lock()
|
| 34 |
+
|
| 35 |
+
# Google Drive Authentication
|
| 36 |
+
def get_gdrive_client():
|
| 37 |
+
global drive_client
|
| 38 |
+
if not GDRIVE_SERVICE_ACCOUNT_JSON:
|
| 39 |
+
logger.error("GDRIVE_SERVICE_ACCOUNT_JSON not found in environment variables.")
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
+
try:
|
| 43 |
+
# Save JSON to a temporary file
|
| 44 |
+
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.json') as temp_json:
|
| 45 |
+
temp_json.write(GDRIVE_SERVICE_ACCOUNT_JSON)
|
| 46 |
+
temp_json_path = temp_json.name
|
| 47 |
+
|
| 48 |
+
scope = ['https://www.googleapis.com/auth/drive']
|
| 49 |
+
gauth = GoogleAuth()
|
| 50 |
+
gauth.auth_method = 'service'
|
| 51 |
+
gauth.credentials = ServiceAccountCredentials.from_json_keyfile_name(temp_json_path, scope)
|
| 52 |
+
|
| 53 |
+
drive_client = GoogleDrive(gauth)
|
| 54 |
+
|
| 55 |
+
# Clean up the temporary file after initializing
|
| 56 |
+
os.unlink(temp_json_path)
|
| 57 |
+
return drive_client
|
| 58 |
+
except Exception as e:
|
| 59 |
+
logger.error(f"Error authenticating with Google Drive: {e}")
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
# Scheduler for automatic deletion
|
| 63 |
+
scheduler = BackgroundScheduler()
|
| 64 |
+
scheduler.start()
|
| 65 |
+
|
| 66 |
+
def delete_from_drive(file_id):
|
| 67 |
+
try:
|
| 68 |
+
global drive_client
|
| 69 |
+
if not drive_client:
|
| 70 |
+
drive_client = get_gdrive_client()
|
| 71 |
+
|
| 72 |
+
if drive_client:
|
| 73 |
+
file = drive_client.CreateFile({'id': file_id})
|
| 74 |
+
file.Delete()
|
| 75 |
+
logger.info(f"File {file_id} deleted successfully after 2 hours.")
|
| 76 |
+
except Exception as e:
|
| 77 |
+
logger.error(f"Error deleting file {file_id}: {e}")
|
| 78 |
+
|
| 79 |
+
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 80 |
+
if not AUTHORIZED_USER_ID or update.effective_user.id != AUTHORIZED_USER_ID:
|
| 81 |
+
return
|
| 82 |
+
await update.message.reply_text("Merhaba! Bana bir direkt indirme linki gönder, senin için Google Drive'a yükleyeyim.")
|
| 83 |
+
|
| 84 |
+
def download_file(url, dest):
|
| 85 |
+
obj = SmartDL(url, dest, progress_bar=False, timeout=30)
|
| 86 |
+
obj.start()
|
| 87 |
+
return obj
|
| 88 |
+
|
| 89 |
+
def upload_file(file_path, file_name):
|
| 90 |
+
global drive_client
|
| 91 |
+
if not drive_client:
|
| 92 |
+
drive_client = get_gdrive_client()
|
| 93 |
+
|
| 94 |
+
metadata = {'title': file_name}
|
| 95 |
+
if GDRIVE_FOLDER_ID:
|
| 96 |
+
metadata['parents'] = [{'id': GDRIVE_FOLDER_ID}]
|
| 97 |
+
|
| 98 |
+
gfile = drive_client.CreateFile(metadata)
|
| 99 |
+
gfile.SetContentFile(file_path)
|
| 100 |
+
gfile.Upload()
|
| 101 |
+
return gfile
|
| 102 |
+
|
| 103 |
+
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
|
| 104 |
+
if not AUTHORIZED_USER_ID or update.effective_user.id != AUTHORIZED_USER_ID:
|
| 105 |
+
logger.warning(f"Unauthorized access attempt by user {update.effective_user.id}")
|
| 106 |
+
return
|
| 107 |
+
|
| 108 |
+
url = update.message.text
|
| 109 |
+
if not url.startswith(("http://", "https://")):
|
| 110 |
+
await update.message.reply_text("Geçersiz link. Lütfen geçerli bir HTTP veya HTTPS linki gönder.")
|
| 111 |
+
return
|
| 112 |
+
|
| 113 |
+
async with processing_lock:
|
| 114 |
+
status_message = await update.message.reply_text("⏳ İşlem sıraya alındı ve başlatılıyor...")
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
# Download
|
| 118 |
+
dest = tempfile.gettempdir()
|
| 119 |
+
await status_message.edit_text("📥 Dosya sunucuya indiriliyor...")
|
| 120 |
+
|
| 121 |
+
obj = await asyncio.to_thread(download_file, url, dest)
|
| 122 |
+
|
| 123 |
+
if not obj.is_successful():
|
| 124 |
+
await status_message.edit_text("❌ İndirme başarısız oldu. Linkin doğruluğunu kontrol edin.")
|
| 125 |
+
return
|
| 126 |
+
|
| 127 |
+
file_path = obj.get_dest()
|
| 128 |
+
file_name = os.path.basename(file_path)
|
| 129 |
+
|
| 130 |
+
# Size check (Approx 5GB)
|
| 131 |
+
file_size = os.path.getsize(file_path)
|
| 132 |
+
if file_size > 5 * 1024 * 1024 * 1024:
|
| 133 |
+
await status_message.edit_text(f"⚠️ Dosya çok büyük ({file_size / (1024**3):.2f} GB). Maksimum limit 5GB.")
|
| 134 |
+
os.remove(file_path)
|
| 135 |
+
return
|
| 136 |
+
|
| 137 |
+
await status_message.edit_text(f"✅ İndirme tamamlandı: `{file_name}`\n📤 Google Drive'a yükleniyor...", parse_mode='Markdown')
|
| 138 |
+
|
| 139 |
+
# Upload to Google Drive
|
| 140 |
+
gfile = await asyncio.to_thread(upload_file, file_path, file_name)
|
| 141 |
+
|
| 142 |
+
file_id = gfile['id']
|
| 143 |
+
drive_link = gfile['alternateLink']
|
| 144 |
+
|
| 145 |
+
await status_message.edit_text(
|
| 146 |
+
f"🚀 Yükleme başarılı!\n\n"
|
| 147 |
+
f"📁 Dosya: `{file_name}`\n"
|
| 148 |
+
f"🔗 Link: {drive_link}\n\n"
|
| 149 |
+
f"⏱ Bu dosya 2 saat sonra otomatik olarak silinecektir.",
|
| 150 |
+
parse_mode='Markdown'
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
# Clean up local file
|
| 154 |
+
if os.path.exists(file_path):
|
| 155 |
+
os.remove(file_path)
|
| 156 |
+
|
| 157 |
+
# Schedule deletion
|
| 158 |
+
run_date = datetime.now() + timedelta(hours=2)
|
| 159 |
+
scheduler.add_job(delete_from_drive, 'date', run_date=run_date, args=[file_id])
|
| 160 |
+
|
| 161 |
+
except Exception as e:
|
| 162 |
+
logger.error(f"Error during processing: {e}")
|
| 163 |
+
await update.message.reply_text(f"❌ Bir hata oluştu: {str(e)}")
|
| 164 |
+
|
| 165 |
+
def main():
|
| 166 |
+
if not BOT_TOKEN:
|
| 167 |
+
logger.error("BOT_TOKEN not found!")
|
| 168 |
+
return
|
| 169 |
+
|
| 170 |
+
# Initialize Drive Client
|
| 171 |
+
get_gdrive_client()
|
| 172 |
+
|
| 173 |
+
application = ApplicationBuilder().token(BOT_TOKEN).build()
|
| 174 |
+
|
| 175 |
+
application.add_handler(CommandHandler("start", start))
|
| 176 |
+
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message))
|
| 177 |
+
|
| 178 |
+
logger.info("Bot started...")
|
| 179 |
+
application.run_polling()
|
| 180 |
+
|
| 181 |
+
if __name__ == '__main__':
|
| 182 |
+
main()
|