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\nEndpoints:\n{endpoint_message}" 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 ") 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'', 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"""File has been successfully uploaded to the channel\n\nLink: Click Here""", 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()