File size: 22,036 Bytes
f484b72
34906fb
3ab9daf
93f9679
22b65c1
218d0d7
f484b72
61aff4b
f484b72
 
 
 
 
 
63d7280
377ad42
 
f484b72
 
 
 
 
 
 
 
 
 
63d7280
 
f484b72
 
 
 
 
8f7a0ec
93f9679
f484b72
218d0d7
 
 
 
 
f484b72
 
 
 
 
9c64b2f
 
 
 
 
 
4c0f8e9
f484b72
d88f0bb
 
f484b72
bfc4e9f
f484b72
0fffae5
f484b72
 
 
 
 
bfc4e9f
 
0fffae5
 
21aa85f
0fffae5
f484b72
0fffae5
bfc4e9f
9a8fec6
f484b72
9a8fec6
 
 
 
 
 
 
 
 
6b01bf2
f484b72
0fffae5
 
 
 
 
 
21aa85f
0fffae5
 
 
21aa85f
 
 
 
0fffae5
 
 
 
 
21aa85f
 
 
 
 
 
0fffae5
 
21aa85f
0fffae5
edb561c
 
 
 
21aa85f
edb561c
21aa85f
5aa2b1c
 
edb561c
5aa2b1c
 
 
 
 
9530a11
46d346f
ac31600
 
 
 
 
 
 
 
6b01bf2
dca7f40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7bf0762
 
 
 
dc97221
 
0b8eb6d
 
 
 
 
 
3aa5b56
bfc4e9f
3aa5b56
0b8eb6d
3aa5b56
0b8eb6d
21aa85f
f977f4d
 
 
 
21aa85f
a08e689
f484b72
 
 
 
aa839da
 
 
 
 
 
f484b72
 
 
 
 
 
 
b910c1d
 
f484b72
b910c1d
 
f484b72
b910c1d
 
 
 
f484b72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9a26c4b
f484b72
637a4fe
f484b72
e7f3752
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
14f4d06
fe3f666
 
 
6779b5c
5c6e988
 
 
 
 
 
 
 
 
 
6779b5c
 
 
 
 
 
 
 
 
f484b72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1533000
edb561c
 
3eec2a4
 
 
 
 
edb561c
2c93717
 
8db20f1
 
 
 
2c93717
 
 
 
8db20f1
2c93717
8db20f1
2c93717
 
8db20f1
2c93717
34906fb
2c93717
 
8db20f1
2c93717
 
8db20f1
 
 
2c93717
8db20f1
8f7a0ec
8db20f1
2c93717
8db20f1
2a479c9
316a441
 
ec569c7
316a441
ec569c7
316a441
ec569c7
 
 
 
 
 
316a441
 
 
 
 
 
 
ec569c7
3ab8a29
22b65c1
 
 
af4acd4
 
3ab8a29
22b65c1
af4acd4
22b65c1
af4acd4
 
 
 
 
b59e8b4
af4acd4
dc36bc1
3ab8a29
 
 
 
2a479c9
22b65c1
2a479c9
 
ebe6c1f
9665da5
ebe6c1f
 
2a479c9
d3ae6b1
2a479c9
3ab8a29
af4acd4
2a479c9
 
 
 
 
5faf064
04ae7b6
f12aa90
 
 
 
 
 
e7f3752
f12aa90
fd39fb3
93f9679
4543651
78b6cb2
4543651
 
 
 
218d0d7
 
 
 
 
 
623d61b
218d0d7
 
4543651
2147902
20dc2e2
 
 
9a26c4b
4543651
 
b853c3b
4543651
78b6cb2
20dc2e2
585e3ba
4543651
2147902
9a26c4b
4543651
 
9a26c4b
585e3ba
4543651
6779b5c
585e3ba
 
fd39fb3
6779b5c
585e3ba
 
218d0d7
2147902
 
585e3ba
 
623d61b
 
f5f48c2
585e3ba
0f4d723
585e3ba
3ab9daf
585e3ba
93f9679
 
 
4543651
78b6cb2
e7f3752
 
dca7f40
1533000
 
 
 
4b6fe21
 
 
 
412dd7a
4b6fe21
412dd7a
 
 
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
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
from pyrogram import Client, filters
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, CallbackQuery, Message, InputMediaPhoto, InputMediaVideo
from pyrogram.enums import ParseMode
from pyrogram.errors import FloodWait
import yt_dlp
from database import MongoDB
from typing import Optional
from io import BytesIO
import threading
import asyncio
import os
import math
import aiohttp
import time
import logging
from tiktok import get_video_detail, musicaldown, get_content
from pathlib import Path
from datetime import datetime, timezone
import pytz
from dotenv import load_dotenv
import requests
from fastapi import HTTPException
try:
    import re2 as re
except ImportError:
    import re

logging.basicConfig(level=logging.DEBUG)

load_dotenv()

api_id = os.getenv("API_ID")
api_hash = os.getenv("API_HASH")
bot_token = os.getenv("BOT_TOKEN")
dev_id = os.getenv("DEV_ID")
CHANNEL_ID = os.getenv("CHANNEL_ID")
default_api_key = os.getenv("NGROK_API_KEY")
mongo_uri = os.getenv("MONGO_URI", "mongodb+srv://p64df1j:natusvincer@cluster0.bwukhbw.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0")
db_name = os.getenv("DB_NAME", "p64df1j")

db = MongoDB(mongo_uri, db_name)

bot = Client("my_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token)

user_ids = set()
notified_tunnels = set()
user_api_keys = {}

cookies_directory = "cookies"

os.makedirs(cookies_directory, exist_ok=True)  # Ensure the directory exists

# Global variable to store the path to the cookies file
cookies_file = None

cwd = Path.cwd()

def fetch_ngrok_data(user_id):
    api_key = db.get_api_key(user_id)
    if not api_key:
        return None, "Ngrok API key not found. Please set your Ngrok API key."
    headers = {
        "Authorization": f"Bearer {api_key}",
        "Ngrok-Version": "2"
    }
    try:
        response = requests.get(
            "https://api.ngrok.com/tunnels", headers=headers)
        if response.status_code == 403:
            return None, "Ngrok API key is invalid or does not have permission to access tunnels. Please set a valid API key."
        response.raise_for_status()
        return response.json().get("tunnels", []), None
    except requests.RequestException as e:
        return None, f"Error fetching Ngrok data: {str(e)}"

        
def get_ngrok_tunnels(user_id):
    tunnels, error = fetch_ngrok_data(user_id)
    if error:
        return [error]
    endpoints = [
        tunnel.get("public_url", "").replace("tcp://", "")
        for tunnel in tunnels if tunnel.get("proto") == "tcp"
    ]
    return endpoints if endpoints else ["No TCP endpoints available."]


def get_ngrok_runtime(user_id):
    tunnels, error = fetch_ngrok_data(user_id)
    if error:
        return None, error
    tcp_tunnel = next((tunnel for tunnel in tunnels if tunnel["proto"] == "tcp"), None)
    if not tcp_tunnel:
        return None, "❌ No active TCP tunnels found"
    try:
        start_time = datetime.fromisoformat(
            tcp_tunnel["started_at"].replace("Z", "+00:00")
        ).astimezone(timezone.utc)
        current_time = datetime.now(timezone.utc)
        elapsed_time = current_time - start_time
        elapsed_hours, remainder = divmod(elapsed_time.total_seconds(), 3600)
        elapsed_minutes, _ = divmod(remainder, 60)
        runtime_message = (
            f"🟢 Ngrok TCP tunnel running for {int(elapsed_hours)}h {int(elapsed_minutes)}m"
            if elapsed_hours > 0
            else f"🟢 Ngrok TCP tunnel running for {int(elapsed_minutes)} minutes"
        )
        return runtime_message, tcp_tunnel
    except Exception as e:
        return None, f"Error retrieving TCP endpoints: {str(e)}"

def create_ngrok_status_message(user_id, message_id):
    runtime_message, tcp_tunnel_or_error = get_ngrok_runtime(user_id)
    if runtime_message is None:
        status_message = tcp_tunnel_or_error
    else:
        status_message = runtime_message

    endpoints = get_ngrok_tunnels(user_id)
    endpoint_message = "\n".join(endpoints) if endpoints else "No TCP endpoints available."

    full_message = f"{status_message}\n\n<b>Endpoints:</b>\n<code>{endpoint_message}</code>"

    buttons = InlineKeyboardMarkup(
        [
            [
                InlineKeyboardButton("🔄 Refresh", callback_data=f"refresh_ngrok|{ user_id}|{message_id}"),
                InlineKeyboardButton("❌ Close", callback_data=f"close_ngrok|{user_id}|{message_id}")
            ],
            [InlineKeyboardButton("Set API", callback_data=f"set_api|{user_id}|{message_id}")]
        ]
    )
    return full_message, buttons

@bot.on_message(filters.command("start"))
async def start(client: Client, message: Message):
    user_id = message.from_user.id
    logging.debug(f"Received /start command from user {user_id}")

    text, buttons = create_ngrok_status_message(user_id, message.id)
    await message.reply(text, reply_markup=buttons)
    logging.debug("Reply sent with Ngrok status")

@bot.on_message(filters.command("id"))
async def id_handler(client: Client, message: Message):
    if len(message.text.split()) < 2:
        await message.reply("Usage: /id <channel_username_or_link>")
        return

    input_value = message.text.split(maxsplit=1)[1]
    if input_value.startswith('t.me/') or input_value.startswith('https://t.me/'):
        channel_username = '@' + input_value.split('/')[-1]
    elif input_value.startswith('@'):
        channel_username = input_value
    else:
        await message.reply("Please provide a valid channel username starting with '@' or a valid channel link starting with 't.me/' or 'https://t.me/'.")
        return

    progress_message = await message.reply("Fetching channel information...")
    try:
        chat = await client.get_chat(channel_username)
        response = f"*Username:* `{chat.username}`\n*Member count:* `{chat.members_count}`\n*Channel ID:* `{chat.id}`"

        if chat.photo:
            await progress_message.edit_text("Fetching profile photo...")
            photo_file_id = chat.photo.big_file_id
            photo_path = await client.download_media(photo_file_id, file_name=f"{chat.username}_profile_photo.jpg")
            await client.send_photo(message.chat.id, photo_path, caption=response)
        else:
            await progress_message.edit_text(response)
    except Exception as e:
        logging.error(f"An error occurred: {e}")
        await client.send_message(dev_id, f'[ ERROR MESSAGE ]\n\n• Username: @{message.from_user.username}\n• Channel: {channel_username}\n\n{str(e)}')
        await message.reply('Failed to fetch information. Please try again later.')
    finally:
        await progress_message.delete()
        
@bot.on_callback_query(filters.regex(r"^set_api\|(\d+)\|(\d+)$"))
async def set_api_callback(client: Client, callback_query: CallbackQuery):
    user_id = int(callback_query.matches[0].group(1))
    prompt_message = await callback_query.message.reply("Please send your Ngrok API key as a reply to this message.")
    await callback_query.answer()

    asyncio.create_task(delete_if_no_reply(user_id, prompt_message))

@bot.on_message(filters.reply)
async def capture_api_key(client: Client, message: Message):
    if message.reply_to_message and message.reply_to_message.text == "Please send your Ngrok API key as a reply to this message.":
        user_id = message.from_user.id
        api_key = message.text.strip()
        db.insert_api_key(user_id, api_key)
        await message.reply("Ngrok API key set successfully!")
        await message.reply_to_message.delete()

async def delete_if_no_reply(user_id: int, prompt_message: Message):
    await asyncio.sleep(5)
    if user_id not in user_api_keys:
        try:
            await prompt_message.delete()
        except Exception as e:
            print(f"Error deleting prompt message: {e}")

@bot.on_callback_query(filters.regex(r"^refresh_ngrok\|(\d+)\|(\d+)$"))
async def refresh_ngrok(client: Client, callback_query: CallbackQuery):
    user_id = int(callback_query.matches[0].group(1))

    text, buttons = create_ngrok_status_message(user_id, callback_query.message.id)

    try:
        await callback_query.message.edit_text(text, reply_markup=buttons)
    except Exception as e:
        print(f"Error while editing message: {e}")

    await callback_query.answer("Status updated!", show_alert=False)

@bot.on_callback_query(filters.regex(r"^close_ngrok\|(\d+)\|(\d+)$"))
async def close_ngrok(client: Client, callback_query: CallbackQuery):
    try:
        user_id, original_message_id = map(int, callback_query.data.split("|")[1:])
        
        # Delete the callback query message (the message containing buttons)
        await callback_query.message.delete()
        
        # Delete the original message that triggered the /start command
        await client.delete_messages(chat_id=callback_query.message.chat.id, message_ids=original_message_id)
        
        # Optionally send a confirmation to the user
        await callback_query.answer("Message closed!", show_alert=False)

    except Exception as e:
        print(f"Error while deleting message: {e}")

    await callback_query.answer("Message closed!", show_alert=False)

# Function to extract tweet IDs
def extract_tweet_ids(text: str) -> Optional[list[str]]:
    """Extract tweet IDs from message."""
    # For t.co links
    unshortened_links = ''
    for link in re.findall(r"t\.co\/[a-zA-Z0-9]+", text):
        try:
            unshortened_link = requests.get('https://' + link).url
            unshortened_links += '\n' + unshortened_link
        except:
            pass

    # Parse IDs from received text
    tweet_ids = re.findall(r"(?:twitter|x)\.com/.{1,15}/(?:web|status(?:es)?)/([0-9]{1,20})", text + unshortened_links)
    tweet_ids = list(dict.fromkeys(tweet_ids))
    return tweet_ids or None

# Function to scrape media
def scrape_media(tweet_id: int) -> list[dict]:
    r = requests.get(f'https://api.vxtwitter.com/Twitter/status/{tweet_id}')
    r.raise_for_status()
    try:
        return r.json()['media_extended']
    except requests.exceptions.JSONDecodeError:
        if match := re.search(r'<meta content="(.*?)" property="og:description" />', r.text):
            raise Exception(f'API returned error: {html.unescape(match.group(1))}')
        raise
      
async def simulate_download_progress(media_info: dict, message: Message):
    total_size = get_media_size(media_info['url'])

    try:
        if total_size > 0:
            for progress in range(0, 101, 10):
                progress_bar = get_progress_bar_string(progress)
                size_readable = format_size(total_size * (progress / 100))
                progress_text = f"{progress_bar} {progress}% ({size_readable})"
                await message.edit_text(f"Downloading: {progress_text}")
                await asyncio.sleep(0.5)
        else:
            for progress in range(0, 101, 10):
                progress_bar = get_progress_bar_string(progress)
                progress_text = f"{progress_bar} {progress}% (Size unknown)"
                await message.edit_text(f"Downloading: {progress_text}")
                await asyncio.sleep(0.5)
    except Exception as e:
        await message.edit_text(f"An error occurred during download progress: {str(e)}")

def get_media_size(url: str) -> int:
    response = requests.head(url)
    return int(response.headers.get('Content-Length', 0))

def get_progress_bar_string(pct) -> str:
    if isinstance(pct, int):
        pct = float(pct)
    elif not isinstance(pct, float):
        pct = float(pct.strip("%"))
    p = min(max(pct, 0), 100)
    cFull = int(p // 8)
    p_str = "■" * cFull
    p_str += "□" * (12 - cFull)
    return f"[{p_str}]"

def format_size(size: int) -> str:
    # Convert size to a human-readable format
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size < 1024:
            return f"{size:.2f} {unit}"
        size /= 1024
    return f"{size:.2f} TB"
    
# Function to reply with media
async def reply_media(client: Client, chat_id: int, tweet_media: list):
    """Reply to message with supported media."""
    photos = [media for media in tweet_media if media["type"] == "image"]
    gifs = [media for media in tweet_media if media["type"] == "gif"]
    videos = [media for media in tweet_media if media["type"] == "video"]

    message = await client.send_message(chat_id, "Starting download...")  # Send initial message

    if photos:
        await simulate_download_progress(photos[0], message)
        await client.send_photo(chat_id, photos[0]['url'])
    if gifs:
        await simulate_download_progress(gifs[0], message)
        await client.send_animation(chat_id, gifs[0]['url'])
    elif videos:
        await simulate_download_progress(videos[0], message)
        await client.send_video(chat_id, videos[0]['url'])

    await message.delete()  # Delete the progress message after completion

@bot.on_message(filters.command("Twitter"))
async def download_twitter_media(client: Client, message: Message):
    tweet_ids = extract_tweet_ids(message.text)
    if not tweet_ids:
        await message.reply_text("No tweet IDs found!")
        return

    for tweet_id in tweet_ids:
        try:
            tweet_media = scrape_media(tweet_id)
            await reply_media(client, message.chat.id, tweet_media)
        except Exception as e:
            await message.reply_text(f"Failed to scrape media: {e}")

@bot.on_message(filters.command("time"))
async def time(client: Client, message: Message):
  
    jakarta_tz = pytz.timezone('Asia/Jakarta')
    jakarta_time = datetime.now(jakarta_tz)
    time_str = jakarta_time.strftime('%Y-%m-%d %H:%M:%S')
    await message.reply(f"The current date and time in Asia/Jakarta is: {time_str}")

@bot.on_message(filters.command("threads"))
async def threads(client: Client, message: Message):
    if len(message.text.split()) < 2:
        await message.reply("Please provide a valid URL.")
        return

    url = message.text.split(maxsplit=1)[1]
    load = await message.reply('Loading, please wait.')
    try:
        response = requests.get(f'https://api.threadsphotodownloader.com/v2/media?url={url}')
        response.raise_for_status()
        data = response.json()
        
        if data['image_urls'] and not data['video_urls']:
            if len(data['image_urls']) == 1:
                await client.send_photo(message.chat.id, data['image_urls'][0])
            else:
                media_group = [InputMediaPhoto(url) for url in data['image_urls']]
                await client.send_media_group(message.chat.id, media_group)
        elif data['video_urls'] and not data['image_urls']:
            await client.send_video(message.chat.id, data['video_urls'][0]['download_url'])
        else:
            await load.edit_text('Failed to get data, make sure your link is valid!')
    except requests.exceptions.RequestException as e:
        logging.error(f"Request failed: {e}")
        await message.reply('Failed to download media, make sure your link is valid!')
    except Exception as e:
        logging.error(f"An error occurred: {e}")
        await client.send_message(dev_id, f'[ ERROR MESSAGE ]\n\n• Username: @{message.from_user.username}\n• Url: {url}\n\n{str(e)}')
        await message.reply('An unexpected error occurred. Please try again later.')
    finally:
        await load.delete()

@bot.on_message(filters.document | filters.video | filters.photo)
async def handle_media(client: Client, message: Message):
    user_id = message.from_user.id
    logging.debug(f"Received media from user {user_id}")

    if message.document and message.document.file_name == "cookies.txt":
        global cookies_file
        # Download the cookies file
        cookies_file = await message.download()
        await message.reply(f"Cookies file has been set: {cookies_file}")
        logging.debug(f"Cookies file has been set: {cookies_file}")
    else:
        # Download the media
        file_path = await message.download()
        logging.debug(f"Downloaded media to {file_path}")

        # Inform the user about the download location
        await message.reply(f"Your media has been downloaded to: {file_path}")
        logging.debug(f"Informed user {user_id} about the download location")

def download_video_to_buffer(url, cookies_file=None):
    ydl_opts = {
        'format': 'best',
        'quiet': True,
        'outtmpl': '-',
        'noplaylist': True,
        'cookiefile': cookies_file if cookies_file else None,
    }
    buffer = BytesIO()
    with yt_dlp.YoutubeDL(ydl_opts) as ydl:
        info_dict = ydl.extract_info(url, download=False)
        ydl.download([url])
        ydl.process_info(info_dict)
        buffer.write(ydl.urlopen(info_dict['url']).read())
    buffer.seek(0)
    buffer.name = "video.mp4"  # Set the name attribute for the buffer
    return buffer, info_dict['title']

@bot.on_message(filters.command("yt"))
async def yt(client: Client, message: Message):
    global cookies_file

    if len(message.text.split()) < 2:
        await message.reply("Please provide a valid URL.")
        return

    if not cookies_file:
        await message.reply("Cookies file not set. Please send the cookies file named 'cookies.txt'.")
        return

    url = message.text.split(maxsplit=1)[1]
    load = await message.reply('Downloading video please wait...')
    try:
        video_buffer, video_title = download_video_to_buffer(url, cookies_file)
        await client.send_video(message.chat.id, video_buffer, caption=video_title)
    except Exception as e:
        logging.error(f"An error occurred: {e}")
        await client.send_message(dev_id, f'[ ERROR MESSAGE ]\n\n• Username: @{message.from_user.username}\n• Url: {url}\n\n{str(e)}')
        await message.reply('An unexpected error occurred. Please try again later.')
    finally:
        await load.delete()
        
@bot.on_message(filters.text & filters.private)
async def handle_tiktok_link(client: Client, message: Message):
    tiktok_pattern = re.compile(r"(https?://(?:www\.)?(?:tiktok\.com|vt\.tiktok\.com)/\S+)")
    match = tiktok_pattern.search(message.text)
    if match:
        await process_tiktok_link(client, message, match.group(0))
        
async def process_tiktok_link(client: Client, message: Message, url: str):
    user_id = message.from_user.id
    target_id = CHANNEL_ID if CHANNEL_ID else user_id
    try:
        progress_message = await message.reply("Processing your request...", reply_to_message_id=message.id)

        video_detail = await get_video_detail(url)
        if video_detail:
            video_id, author_id, author_username, video_url, images, cookies = video_detail

            # Store chat details in the database
            chat_detail_id = db.insert_chat_detail({
                "user_id": user_id,
                "channel_id": CHANNEL_ID,
                "message_id": message.id,
                "cookies": cookies
            })

            if images:
                await progress_message.edit("Downloading image content...")
                media_group = []
                for image_info in images:
                    image_url = image_info['imageURL']['urlList'][0]
                    image_bytes, total_size = await get_content(image_url, cookies)
                    if image_bytes:
                        image_bytes.name = "image.jpg"
                        media_group.append(InputMediaPhoto(image_bytes))
                    else:
                        await message.reply(f"Failed to download image from URL {image_url}", reply_to_message_id=message.id)
                if media_group:
                    sent_messages = await client.send_media_group(target_id, media_group, reply_to_message_id=message.id)
            else:
                await progress_message.edit("Downloading video content...")
                video_bytes, total_size = await musicaldown(url)
                if video_bytes:
                    video_bytes.name = "video.mp4"
                    await simulate_download_progress({"url": video_url, "total_size": total_size}, progress_message)
                    sent_message = await client.send_video(target_id, video_bytes, reply_to_message_id=message.id)
                else:
                    await message.reply("Failed to download the video. Please check the URL and try again.", reply_to_message_id=message.id)
                    await progress_message.delete()
                    return
        else:
            await message.reply("Invalid TikTok URL. Please provide a valid URL.", reply_to_message_id=message.id)
            await progress_message.delete()
            return

        # Delete the progress message after sending the media
        await progress_message.delete()

        if CHANNEL_ID:
            # Ensure the bot meets the peer before interacting with it
            await client.get_chat(CHANNEL_ID)
            channel_message_link = f"https://t.me/c/{str(CHANNEL_ID)[4:]}/{sent_message.id}"
            await message.reply(
                f"""<b>File has been successfully uploaded to the channel</b>\n\n<b>Link:</b> <a href="{channel_message_link}">Click Here</a>""",
                reply_to_message_id=message.id,
                parse_mode=ParseMode.HTML
            )
    except FloodWait as e:
        await message.reply(f"Rate limit exceeded. Please wait for {e.x} seconds.", reply_to_message_id=message.id)
        await asyncio.sleep(e.x)
    except Exception as e:
        await message.reply(f"An error occurred: {str(e)}", reply_to_message_id=message.id)
        # Ensure the progress message is deleted even if an error occurs
        await progress_message.delete()
        
def run_bot():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    async def start_bot():
        await bot.start()
        await asyncio.Future()  # Run forever

    try:
        loop.run_until_complete(start_bot())
    finally:
        loop.run_until_complete(bot.stop())
        loop.close()