File size: 5,432 Bytes
3e66391
 
 
 
 
 
 
9ccc8ce
3e66391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0cd346e
3e66391
 
 
 
 
 
ca5cd1f
3e66391
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
401e7d5
67df2b3
3e66391
 
 
 
67df2b3
3e66391
ff20f30
401e7d5
9ccc8ce
401e7d5
9ccc8ce
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
import logging
from pyrogram import Client, filters, idle
from pyrogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton
from pyrogram.types import *
from RyuzakiLib import Tiktok
from config import TIKTOK_WEB as tt, API_ID, API_HASH, BOT_TOKEN, HUGGING_TOKEN
import hashlib
import asyncio

try:
    from aiohttp import ClientSession as aiohttp_client
except ImportError:
    aiohttp_client = None

logging.getLogger("pyrogram").setLevel(logging.WARNING)
logging.basicConfig(level=logging.INFO)

WELCOME_TEXT = """
Halo {}
Saya adalah bot untuk mengunduh video tiktok di telegram.

Saya dapat mengunduh video dengan tanda air atau tanpa tanda air dan mengunduh audio dari url. Kirimkan saja saya url tiktok.
"""

client = Client(
    "TTK-BOT",
    api_id=API_ID,
    api_hash=API_HASH,
    bot_token=BOT_TOKEN
)

link_storage = {}

def generate_callback_data(user_id, query):
    identifier = hashlib.md5(query.encode()).hexdigest()
    callback_data = f"audiodownload_{user_id}_{identifier}"
    link_storage[callback_data] = query
    return callback_data

async def async_searcher(
    url: str,
    post: bool = False,
    head: bool = False,
    headers: dict = None,
    evaluate=None,
    object: bool = False,
    re_json: bool = False,
    re_content: bool = False,
    *args,
    **kwargs,
):
    if aiohttp_client:
        async with aiohttp_client(headers=headers) as client:
            method = client.head if head else (client.post if post else client.get)
            data = await method(url, *args, **kwargs)
            if evaluate:
                return await evaluate(data)
            if re_json:
                return await data.json()
            if re_content:
                return await data.read()
            if head or object:
                return data
            return await data.text()
    else:
        raise DependencyMissingError("install 'aiohttp' to use this.")

async def hfv(api_url, timeout=10):
    try:
        headers = {
            "Authorization": f"Bearer {HUGGING_TOKEN}",
            "Content-Type": "application/json",
        }
        response = await async_searcher(api_url, headers=headers, re_json=True)
        stat = response.get("message", "ded")
        return await client.send_message(chat_id=1191668125, text=f"**TɪᴋTᴏᴋ Sᴇʀᴠᴇʀ Sᴛᴀᴛᴜs:** `{stat}`")
    except requests.exceptions.RequestException as e:
        logging.info("Error occurred:", e)
        return await client.send_message(chat_id=1191668125, text=f"**TɪᴋTᴏᴋ Sᴇʀᴠᴇʀ Sᴛᴀᴛᴜs:** `ded`")

async def periodic_hfv(api_url, interval_range):
    while True:
        result = await hfv(api_url)
        if result:
            logging.info("Call Complete")
        interval = random.randint(*interval_range)
        await asyncio.sleep(interval)

async def start_periodic_task():
    interval_range = (2 * 3600, 4 * 3600)  # Call the function every 2 to 4 hours
    api_url = "https://randydev-ttk-bot.hf.space/status"
    asyncio.create_task(periodic_hfv(api_url, interval_range))

@client.on_message(filters.command("start") & filters.private)
async def welcome_start(client: Client, message: Message):
    keyboard = InlineKeyboardMarkup(
        [
            [
                InlineKeyboardButton(
                    text="📢 Saluran Bot",
                    url="https://t.me/RendyProjects"
                )
            ]
        ]
    )
    await message.reply_text(
        WELCOME_TEXT.format(message.from_user.first_name),
        reply_markup=keyboard
    )

@client.on_callback_query(filters.regex("^audiodownload_"))
async def callback_button(client: Client, cb: CallbackQuery):
    try:
        data = cb.data
        user_id = cb.from_user.id
        query = link_storage.get(data)
        if query:
            response = Tiktok.download(tt, query)
            await client.send_audio(user_id, response[1])
            await cb.answer("Audio sent successfully!")
        else:
            await cb.answer("Invalid or expired link.", show_alert=True)
    except Exception as e:
        await cb.answer(f"Error: {str(e)}", show_alert=True)

@client.on_message(filters.text & filters.private)
async def tiktok_downloader(client: Client, message: Message):
    if message.text:
        query = message.text
        callback_data = generate_callback_data(message.from_user.id, query)
        keyboard = InlineKeyboardMarkup(
            [
                [
                    InlineKeyboardButton(
                        text="Audio Download",
                        callback_data=callback_data
                    )
                ]
            ]
        )
        try:
            dll = await message.reply_text("Processing....")
            await message.delete()
            response = await Tiktok.download(tt, query)
            await message.reply_video(response[0], reply_markup=keyboard)
            await dll.delete()
        except Exception as e:
            await dll.delete()
            await message.reply_text(f"Error: {str(e)}")

async def setup():
    try:
        await client.run()
        logging.info("Bot started successfully")
        await start_periodic_task()
        # Run the client
        await idle()
    except Exception as e:
        logging.info(f"Error in setup: {e}")

if __name__ == "__main__":
    try:
        asyncio.run(setup())
    except Exception as e:
        logging.info(str(e))