-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTTAbot.py
More file actions
462 lines (382 loc) · 16.7 KB
/
Copy pathTTAbot.py
File metadata and controls
462 lines (382 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
import re
import requests
import logging
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
import asyncio
import os
from urllib.parse import urlparse
# Disable httpx logging
logging.getLogger("httpx").setLevel(logging.WARNING)
logging.getLogger("httpcore").setLevel(logging.WARNING)
# Bot token from environment variable
BOT_TOKEN = os.environ.get("BOT_TOKEN", "YOUR_BOT_TOKEN_HERE")
# Target chat configuration (set via environment variables)
TARGET_CHAT_ID = int(os.environ.get("TARGET_CHAT_ID", "-1001234567890"))
TARGET_CHAT_NAME = os.environ.get("TARGET_CHAT_NAME", "Target Group")
# File to store uploaded videos data
DATABASE_FILE = "uploaded_videos.txt"
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
logger = logging.getLogger(__name__)
def load_database():
"""Load the database of uploaded videos from TXT file"""
db = {}
if os.path.exists(DATABASE_FILE):
try:
with open(DATABASE_FILE, 'r', encoding='utf-8') as f:
for line in f:
line = line.strip()
if line and not line.startswith('#'):
parts = line.split('|')
if len(parts) >= 3:
media_id = parts[0].strip()
username = parts[1].strip()
message_link = parts[2].strip()
db[media_id] = {
"username": username,
"message_link": message_link
}
except Exception as e:
logger.error(f"Error loading database: {e}")
return db
def save_database(db):
"""Save the database of uploaded videos to TXT file"""
try:
with open(DATABASE_FILE, 'w', encoding='utf-8') as f:
f.write("# MediaID | Username | MessageLink\n")
f.write("# ================================\n")
for media_id, info in db.items():
f.write(f"{media_id}|{info['username']}|{info['message_link']}\n")
except Exception as e:
logger.error(f"Error saving database: {e}")
def add_video_to_db(media_id, username, message_link):
"""Add a video to the database"""
db = load_database()
db[media_id] = {
"username": username,
"message_link": message_link
}
save_database(db)
def get_video_from_db(media_id):
"""Get video info from database"""
db = load_database()
return db.get(media_id)
def resolve_short_url(url):
"""Resolve short URLs with timeout"""
try:
# (insert current headers here)
headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:152.0) Gecko/20100101 Firefox/152.0'}
response = requests.get(url, headers=headers, allow_redirects=False, timeout=15)
if response.status_code in [301, 302, 303, 307, 308] and 'Location' in response.headers:
return response.headers['Location']
response = requests.get(url, headers=headers, allow_redirects=True, timeout=15)
return response.url
except requests.exceptions.Timeout:
logger.error(f"Timeout resolving URL: {url}")
raise Exception("Request timed out while resolving link")
except Exception as e:
logger.error(f"Error resolving URL: {e}")
raise Exception(f"Failed to resolve link: {str(e)}")
def extract_username_from_html(html_content):
"""Extract uniqueId from page HTML."""
patterns = [
r'"uniqueId":"([^"]+)"',
r'"authorUniqueId":"([^"]+)"',
r'"authorName":"([^"]+)"',
r'"nickname":"([^"]+)"',
r'"username":"([^"]+)"'
]
for pattern in patterns:
match = re.search(pattern, html_content)
if match:
return match.group(1)
return None
def extract_video_id_from_html(html_content, url):
"""Extract video ID from page HTML."""
patterns = [
r'/video/(\d+)',
r'"videoId":"(\d+)"',
r'"id":"(\d+)"',
r'"vid":"([^"]+)"',
r'"item_id":"(\d+)"'
]
# First try from URL
match = re.search(r'/video/(\d+)', url)
if match:
return match.group(1)
# Then try from HTML
for pattern in patterns:
match = re.search(pattern, html_content)
if match:
return match.group(1)
return None
def extract_tiktok_info_fallback(url):
"""Fallback method to extract info by fetching HTML content"""
try:
logger.info(f"Using fallback extraction method for URL: {url}")
# (insert current headers here)
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:152.0) Gecko/20100101 Firefox/152.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Encoding': 'gzip, deflate, br',
'DNT': '1',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1'
}
response = requests.get(url, allow_redirects=True, timeout=15, headers=headers)
final_url = response.url
logger.info(f"Redirected to: {final_url}")
html_response = requests.get(final_url, timeout=15, headers=headers)
html_content = html_response.text
username = extract_username_from_html(html_content)
if not username:
# Try to extract from URL
username_match = re.search(r'@([^/]+)', final_url)
if username_match:
username = username_match.group(1)
else:
raise Exception("Could not find username in HTML or URL")
video_id = extract_video_id_from_html(html_content, final_url)
if not video_id:
raise Exception("Could not extract video ID")
clean_url = f"https://www.example.com/@{username}/video/{video_id}"
logger.info(f"Clean URL constructed: {clean_url}")
return username, video_id, clean_url
except Exception as e:
logger.error(f"Fallback extraction failed: {e}")
raise
def extract_info_from_url(url):
"""Extract username and media ID from URL with fallback method"""
url = url.strip()
try:
if 'example.com/t/' in url or 'vt.example.com' in url:
url = resolve_short_url(url)
url = url.split('?')[0]
# (insert current URL pattern here)
pattern = r'https?://(?:www\.)?example\.com/@([^/]+)/video/(\d+)'
match = re.match(pattern, url)
if match:
return match.group(1), match.group(2), url
logger.info("Standard pattern matching failed, trying fallback method")
return extract_tiktok_info_fallback(url)
except Exception as e:
logger.error(f"Error extracting info: {e}")
try:
logger.info("Attempting fallback method on original URL")
return extract_tiktok_info_fallback(url)
except Exception as fallback_error:
logger.error(f"Fallback also failed: {fallback_error}")
raise ValueError(f"Invalid URL format: {str(e)}")
def get_video_url_generic(media_id, username=None):
"""Generic method to get video URL - placeholder for different platforms"""
# This is a placeholder - implement actual video retrieval logic here
# For different platforms, you would use their respective APIs
try:
# Example API call structure
# (insert current API endpoint here)
api_url = "https://api.example.com/video/"
params = {
"id": media_id
}
# (insert current headers here)
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:152.0) Gecko/20100101 Firefox/152.0'
}
logger.info(f"Calling generic API for video: {media_id}")
response = requests.get(api_url, params=params, headers=headers, timeout=20)
data = response.json()
if data.get('success') and 'video_url' in data:
video_url = data['video_url']
logger.info(f"Found video URL from generic API")
return video_url
else:
logger.warning("No video URL found in API response")
except requests.exceptions.Timeout:
logger.error(f"Timeout with generic API")
except Exception as e:
logger.error(f"Error with generic API: {e}")
return None
async def send_video_with_fallback(context, chat_id, media_id, username, processing_msg):
"""Try to send video using multiple sources"""
video_sources = []
# 1. Try primary method
logger.info("Trying primary video source...")
video_url = get_video_url_generic(media_id, username)
if video_url:
video_sources.append(("Primary Source", video_url))
# 2. Try alternative methods
if not video_sources:
logger.info("Trying alternative sources...")
# Add more source attempts here
last_error = None
for source_name, video_url in video_sources:
try:
logger.info(f"Attempting to send video with {source_name}")
sent_message = await asyncio.wait_for(
context.bot.send_video(
chat_id=chat_id,
video=video_url,
caption=f"👤 Username: {username}\n🎬 Media ID: {media_id}",
supports_streaming=True,
write_timeout=120,
connect_timeout=120,
read_timeout=120
),
timeout=130
)
logger.info(f"Successfully sent video using {source_name}")
return sent_message, video_url
except asyncio.TimeoutError:
last_error = "Request timed out"
logger.warning(f"Timeout with {source_name}")
continue
except Exception as e:
last_error = str(e)
logger.warning(f"Failed with {source_name}: {e}")
continue
# If all attempts failed
raise Exception(f"All video sources failed. Last error: {last_error}")
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Start command"""
db = load_database()
await update.message.reply_text(
f"🎬 Video Bot\n\n"
f"Send me a video URL and I'll send it directly to:\n"
f"📱 {TARGET_CHAT_NAME}\n\n"
f"📊 Videos in database: {len(db)}\n\n"
f"Just paste any link and I'll handle the rest!"
)
async def get_chat_id(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Get the ID of the current chat"""
chat_id = update.effective_chat.id
chat_type = update.effective_chat.type
chat_name = update.effective_chat.title if update.effective_chat.title else "Private Chat"
await update.message.reply_text(
f"📱 Chat Information:\n"
f"Name: {chat_name}\n"
f"Type: {chat_type}\n"
f"ID: {chat_id}\n\n"
f"Current target group: {TARGET_CHAT_NAME} (ID: {TARGET_CHAT_ID})"
)
async def stats(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Show statistics of uploaded videos"""
db = load_database()
if not db:
await update.message.reply_text("📊 No videos have been uploaded yet.")
return
await update.message.reply_text(
f"📊 Upload Statistics\n\n"
f"Total videos uploaded: {len(db)}\n"
f"Target group: {TARGET_CHAT_NAME}\n\n"
f"Recent videos:\n"
+ "\n".join([f"• @{info['username']} - {media_id}" for media_id, info in list(db.items())[-5:]])
)
async def export_db(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Export the database as a text file"""
if not os.path.exists(DATABASE_FILE):
await update.message.reply_text("📊 No database file found.")
return
try:
with open(DATABASE_FILE, 'r', encoding='utf-8') as f:
content = f.read()
# Send as a text file
await update.message.reply_document(
document=open(DATABASE_FILE, 'rb'),
filename="uploaded_videos.txt",
caption="📊 Database export"
)
except Exception as e:
await update.message.reply_text(f"❌ Error exporting database: {e}")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE):
"""Handle URLs and send video to target chat"""
message_text = update.message.text
# Generic URL pattern - adjust for your specific platform
# (insert current URL pattern here)
url_pattern = r'https?://(?:www\.)?[^\s]+'
urls = re.findall(url_pattern, message_text)
if not urls:
await update.message.reply_text("Please send a valid video URL.")
return
processing_msg = await update.message.reply_text("🎬 Processing video...")
try:
username, media_id, original_url = await asyncio.wait_for(
asyncio.get_event_loop().run_in_executor(None, extract_info_from_url, urls[0]),
timeout=30
)
logger.info(f"Successfully extracted info - Username: {username}, Media ID: {media_id}")
existing_video = get_video_from_db(media_id)
if existing_video:
logger.info(f"Video {media_id} already exists, sending existing link")
await processing_msg.delete()
await update.message.reply_text(
f"📹 This video has already been uploaded!\n\n"
f"👤 Username: @{existing_video['username']}\n"
f"🎬 Media ID: {media_id}\n"
f"🔗 Existing message: {existing_video['message_link']}\n\n"
f"💡 Tip: Use the link above to view the video in the group."
)
return
sent_message, used_url = await send_video_with_fallback(
context, TARGET_CHAT_ID, media_id, username, processing_msg
)
chat_id_for_link = str(TARGET_CHAT_ID)[4:]
message_link = f"https://t.me/c/{chat_id_for_link}/{sent_message.message_id}"
add_video_to_db(media_id, username, message_link)
await processing_msg.delete()
await update.message.reply_text(
f"✅ Video uploaded successfully!\n\n"
f"🔗 View message: {message_link}\n\n"
f"👤 Username: {username}\n"
f"🎬 Media ID: {media_id}"
)
except asyncio.TimeoutError:
logger.error("Timeout processing video")
await processing_msg.edit_text(
f"❌ Could not process this video.\n\n"
f"Error: Request timed out. Please try again."
)
except Exception as e:
logger.error(f"Error: {e}")
error_message = str(e)
if "Timed out" in error_message or "timeout" in error_message.lower():
error_message = "Request timed out. Please try again."
elif "Invalid URL" in error_message:
error_message = "Could not extract video information. Please make sure the link is valid and try again."
else:
error_message = f"Could not process video: {error_message}"
await processing_msg.edit_text(
f"❌ Could not process this video.\n\n"
f"Error: {error_message}"
)
def main():
"""Start bot"""
try:
app = Application.builder().token(BOT_TOKEN).build()
app.add_handler(CommandHandler("start", start))
app.add_handler(CommandHandler("getchatid", get_chat_id))
app.add_handler(CommandHandler("stats", stats))
app.add_handler(CommandHandler("export", export_db))
app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND & filters.ChatType.PRIVATE, handle_message))
db = load_database()
print("🤖 Bot is starting...")
print(f"📱 Target group: {TARGET_CHAT_NAME}")
print(f"📱 Chat ID: {TARGET_CHAT_ID}")
print(f"📊 Loaded {len(db)} videos from database")
print("\n✅ Bot is ready!")
print("Send a video URL in private chat to test.")
print("Press Ctrl+C to stop")
app.run_polling(drop_pending_updates=True)
except Exception as e:
print(f"❌ Error starting bot: {e}")
print("\nTroubleshooting:")
print("1. Set BOT_TOKEN environment variable")
print("2. Make sure the bot is a member of the target group")
print("3. Check that the bot has permission to send messages")
print("4. Verify the chat ID is correct")
if __name__ == "__main__":
main()