genstava789 commited on
Commit
fd39fb3
·
1 Parent(s): f2f3a0a
Files changed (2) hide show
  1. bot.py +19 -84
  2. tiktok.py +78 -104
bot.py CHANGED
@@ -398,91 +398,26 @@ async def yt(client: Client, message: Message):
398
  finally:
399
  await load.delete()
400
 
401
- @bot.on_message(filters.command("tiktok"))
402
- async def tiktok_handler(client: Client, message: Message):
403
- userid = message.chat.id
404
- first_name = message.chat.first_name or ""
405
- last_name = message.chat.last_name
406
- username = message.chat.username
407
- text = message.text
408
- msgid = message.id
409
- print(f"{userid} {first_name} - {text}")
410
-
411
- tiktok_url = None
412
- if len(text.split("\n")) > 1:
413
- tiktok_url = text.split("\n")[0]
414
- if "tiktok" not in tiktok_url:
415
- retext = "The video link you sent may be wrong."
416
- await client.send_message(
417
- chat_id=userid, text=retext, reply_to_message_id=msgid
418
- )
419
- return
420
- else:
421
- tiktok_url = text
422
-
423
- video_id, author_id, author_username, video_url, images, cookies = (
424
- await get_video_detail(tiktok_url)
425
- )
426
- print(
427
- f"video id : {video_id}, author id : {author_id}, username : {author_username}"
428
- )
429
- print(f"video url : {video_url}")
430
- if video_id is None:
431
- retext = "The tiktok video you want to download doesn't exist, it might be deleted or a private video."
432
- await client.send_message(
433
- chat_id=userid, text=retext, reply_to_message_id=msgid
434
- )
435
- return
436
-
437
- link_length = len(tiktok_url)
438
- source_link = f"[Video Source]({tiktok_url})"
439
- retext = f"Successfully download the video\n"
440
- if link_length > 40:
441
- retext += f"\n{source_link}\n"
442
- retext += "\nPowered by @TiktokVideoDownloaderIDBot"
443
- keylist = [
444
- [
445
- InlineKeyboardButton(text="Source Video", url=tiktok_url),
446
- ],
447
- [
448
- InlineKeyboardButton(
449
- text="Follow Me", url="https://t.me/fawwazthoerif"
450
- ),
451
- InlineKeyboardButton(
452
- text="Donation", callback_data="donation"
453
- ),
454
- ],
455
- ]
456
- if link_length > 40:
457
- keylist.pop(0)
458
- rekey = InlineKeyboardMarkup(inline_keyboard=keylist)
459
-
460
- now = int(datetime.now(tz=timezone.utc).timestamp())
461
- output = cwd.joinpath(f"{video_id}.mp4")
462
- if video_url is None or len(video_url) <= 0:
463
- print("try download with musicaldown !")
464
- result = await musicaldown(url=tiktok_url, output=output)
465
  else:
466
- print("try download with main tiktok")
467
- result = await get_content(
468
- url=video_url, output=output, cookies=cookies
469
- )
470
-
471
- await client.delete_messages(chat_id=userid, message_ids=msgid)
472
- result = await client.send_video(
473
- chat_id=userid, video=output, caption=retext, reply_markup=rekey
474
- )
475
- video = result.video
476
- animation = result.animation
477
- if video is not None:
478
- file_id = result.video.file_id
479
- file_unique_id = result.video.file_unique_id
480
- if animation is not None:
481
- file_id = result.animation.file_id
482
- file_unique_id = result.animation.file_unique_id
483
-
484
- output.unlink(missing_ok=True)
485
- return
486
 
487
  def run_bot():
488
  loop = asyncio.new_event_loop()
 
398
  finally:
399
  await load.delete()
400
 
401
+ @bot.on_message(filters.command("download"))
402
+ async def download_tiktok(client: Client, message: Message):
403
+ user_id = message.from_user.id
404
+ url = message.text.split(maxsplit=1)[1]
405
+ logging.debug(f"Received /download command from user {user_id} with URL {url}")
406
+
407
+ video_detail = await get_video_detail(url)
408
+ if video_detail:
409
+ video_id, author_id, author_username, video_url, images, cookies = video_detail
410
+ output = f"{video_id}.mp4"
411
+ success = await musicaldown(url, output)
412
+ if success:
413
+ await client.send_video(user_id, output)
414
+ logging.debug(f"Video {output} sent to user {user_id}")
415
+ else:
416
+ await message.reply("Failed to download the video.")
417
+ logging.debug(f"Failed to download video from URL {url}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
418
  else:
419
+ await message.reply("Invalid TikTok URL.")
420
+ logging.debug(f"Invalid TikTok URL {url}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
421
 
422
  def run_bot():
423
  loop = asyncio.new_event_loop()
tiktok.py CHANGED
@@ -1,19 +1,13 @@
1
  import httpx
 
2
  import aiofiles
 
3
  import random
4
  import re
5
- import json
6
  from bs4 import BeautifulSoup as bs
7
  from pathlib import Path
8
-
9
- # Predefined list of user-agent strings
10
- USER_AGENTS = [
11
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36",
12
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.93 Safari/537.36",
13
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.82 Safari/537.36",
14
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.150 Safari/537.36",
15
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.141 Safari/537.36",
16
- ]
17
 
18
  async def musicaldown(url: str, output: str):
19
  """
@@ -21,68 +15,61 @@ async def musicaldown(url: str, output: str):
21
  output: output file name
22
  """
23
  try:
24
- headers = {"User-Agent": random.choice(USER_AGENTS)}
25
- async with httpx.AsyncClient(headers=headers) as ses:
26
- res = await ses.get("https://musicaldown.com/en")
27
- parsing = bs(res.text, "html.parser")
28
- allInput = parsing.findAll("input")
29
- data = {}
30
- for i in allInput:
31
- if i.get("id") == "link_url":
32
- data[i.get("name")] = url
33
- continue
34
 
35
- data[i.get("name")] = i.get("value")
36
 
37
- res = await ses.post(
38
- "https://musicaldown.com/download", data=data, follow_redirects=True
39
- )
40
- if res.text.find("Convert Video Now") >= 0:
41
- data = re.search(r"data: '(.*?)'", res.text).group(1)
42
- urlSlider = re.search(r"url: '(.*?)'", res.text).group(1)
43
- res = await ses.post(urlSlider, data={"data": data})
44
- if res.text.find('"success":true') >= 0:
45
- urlVideo = res.json()["url"]
46
- await get_content(urlVideo, output)
47
- return True
48
 
49
- return False
50
 
51
- parsing = bs(res.text, "html.parser")
52
- urls = parsing.findAll(
53
- "a", attrs={"class": "btn waves-effect waves-light orange download"}
54
- )
55
- if len(urls) <= 0:
56
- return False
57
 
58
- i = random.randint(0, 1)
59
- urlVideo = urls[i].get("href")
60
- await get_content(urlVideo, output)
61
- return True
62
 
63
  except Exception as e:
64
  print(f"musicaldown error : {e}")
65
  return False
66
 
67
- async def get_content(
68
- url: str, output: str = "video.mp4", cookies: httpx.Cookies = None
69
- ):
70
- try:
71
- async with httpx.AsyncClient() as client:
72
- result = await client.get(
73
- url,
74
- headers={
75
- "User-Agent": random.choice(USER_AGENTS)
76
- },
77
- cookies=cookies,
78
- )
79
- async with aiofiles.open(output, "wb") as w:
80
- async for content in result.aiter_bytes(chunk_size=1024):
81
- await w.write(content)
82
- return True
83
- except Exception as e:
84
- print(f"get_content error : {e}")
85
- return False
86
 
87
  async def get_video_detail(url: str):
88
  """
@@ -90,49 +77,36 @@ async def get_video_detail(url: str):
90
 
91
  return video_id / None
92
  """
93
- if not url.startswith(("http://", "https://")):
94
- url = "https://" + url
95
-
96
  path = Path(url)
97
  post_id = path.stem
98
  headers = {
99
- "User-Agent": random.choice(USER_AGENTS),
100
  }
101
- async with httpx.AsyncClient(headers=headers) as ses:
102
- if not post_id.isdigit():
103
- result = await ses.get(url, follow_redirects=False)
104
- if result.text.startswith('<a href="'):
105
- post_url = result.text.split('<a href="')[1].split("?")[0]
106
- post_id = Path(post_url).stem
107
- result = await ses.get(
108
- f"https://tiktok.com/@i/video/{post_id}", follow_redirects=True
109
- )
110
- cookies = result.cookies
111
- try:
112
- with open("/tmp/tiktok_get_result.html", "w", encoding="utf-8") as f:
113
- f.write(result.text)
114
- except Exception as e:
115
- print(f"Error writing to file: {e}")
116
- parser = bs(result.text, "html.parser")
117
- infotag = parser.find(
118
- "script", attrs={"id": "__UNIVERSAL_DATA_FOR_REHYDRATION__"})
119
- if infotag is None:
120
- return None
121
- infoload = json.loads(infotag.text)
122
- video_detail = infoload.get("__DEFAULT_SCOPE__", {}).get(
123
- "webapp.video-detail", {})
124
- video_id = video_detail.get("itemInfo", {}).get(
125
- "itemStruct", {}).get("id")
126
- author = video_detail.get("itemInfo", {}).get(
127
- "itemStruct", {}).get("author", {})
128
- video = video_detail.get("itemInfo", {}).get(
129
- "itemStruct", {}).get("video", {})
130
- image_post = (
131
- video_detail.get("itemInfo", {}).get(
132
- "itemStruct", {}).get("imagePost", {})
133
- )
134
- images = image_post.get("images")
135
- author_id = author.get("id")
136
- author_username = author.get("uniqueId")
137
- video_url = video.get("playAddr")
138
- return video_id, author_id, author_username, video_url, images, cookies
 
1
  import httpx
2
+
3
  import aiofiles
4
+
5
  import random
6
  import re
7
+ from fake_useragent import UserAgent
8
  from bs4 import BeautifulSoup as bs
9
  from pathlib import Path
10
+ import json
 
 
 
 
 
 
 
 
11
 
12
  async def musicaldown(url: str, output: str):
13
  """
 
15
  output: output file name
16
  """
17
  try:
18
+ headers = {"User-Agent": UserAgent().random}
19
+ ses = httpx.AsyncClient(headers=headers)
20
+ res = await ses.get("https://musicaldown.com/en")
21
+ parsing = bs(res.text, "html.parser")
22
+ allInput = parsing.findAll("input")
23
+ data = {}
24
+ for i in allInput:
25
+ if i.get("id") == "link_url":
26
+ data[i.get("name")] = url
27
+ continue
28
 
29
+ data[i.get("name")] = i.get("value")
30
 
31
+ res = await ses.post(
32
+ "https://musicaldown.com/download", data=data, follow_redirects=True
33
+ )
34
+ if res.text.find("Convert Video Now") >= 0:
35
+ data = re.search(r"data: '(.*?)'", res.text).group(1)
36
+ urlSlider = re.search(r"url: '(.*?)'", res.text).group(1)
37
+ res = await ses.post(urlSlider, data={"data": data})
38
+ if res.text.find('"success":true') >= 0:
39
+ urlVideo = res.json()["url"]
40
+ res = await get_content(urlVideo, output)
41
+ return True
42
 
43
+ return False
44
 
45
+ parsing = bs(res.text, "html.parser")
46
+ urls = parsing.findAll(
47
+ "a", attrs={"class": "btn waves-effect waves-light orange download"}
48
+ )
49
+ if len(urls) <= 0:
50
+ return False
51
 
52
+ i = random.randint(0, 1)
53
+ urlVideo = urls[i].get("href")
54
+ res = await get_content(urlVideo, output)
55
+ return True
56
 
57
  except Exception as e:
58
  print(f"musicaldown error : {e}")
59
  return False
60
 
61
+ async def get_content(url: str, output: str = "video.mp4", cookies: httpx.Cookies = None):
62
+ client = httpx.AsyncClient()
63
+ result = await client.get(
64
+ url,
65
+ headers={
66
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0"
67
+ },
68
+ cookies=cookies,
69
+ )
70
+ async with aiofiles.open(output, "wb") as w:
71
+ async for content in result.aiter_bytes(chunk_size=1024):
72
+ await w.write(content)
 
 
 
 
 
 
 
73
 
74
  async def get_video_detail(url: str):
75
  """
 
77
 
78
  return video_id / None
79
  """
 
 
 
80
  path = Path(url)
81
  post_id = path.stem
82
  headers = {
83
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36 Edg/129.0.0.0",
84
  }
85
+ ses = httpx.AsyncClient(headers=headers)
86
+ if not post_id.isdigit():
87
+ result = await ses.get(url, follow_redirects=False)
88
+ if result.text.startswith('<a href="'):
89
+ post_url = result.text.split('<a href="')[1].split("?")[0]
90
+ post_id = Path(post_url).stem
91
+ result = await ses.get(
92
+ f"https://tiktok.com/@i/video/{post_id}", follow_redirects=True
93
+ )
94
+ cookies = result.cookies
95
+ # print(cookie)
96
+ open("tiktok_get_result.html", "w", encoding="utf-8").write(result.text)
97
+ parser = bs(result.text, "html.parser")
98
+ infotag = parser.find("script", attrs={"id": "__UNIVERSAL_DATA_FOR_REHYDRATION__"})
99
+ if infotag is None:
100
+ return None
101
+ infoload = json.loads(infotag.text)
102
+ video_detail = infoload.get("__DEFAULT_SCOPE__", {}).get("webapp.video-detail", {})
103
+ video_id = video_detail.get("itemInfo", {}).get("itemStruct", {}).get("id")
104
+ author = video_detail.get("itemInfo", {}).get("itemStruct", {}).get("author", {})
105
+ video = video_detail.get("itemInfo", {}).get("itemStruct", {}).get("video", {})
106
+ image_post = video_detail.get("itemInfo", {}).get("itemStruct", {}).get("imagePost", {})
107
+ images = image_post.get("images")
108
+ author_id = author.get("id")
109
+ author_username = author.get("uniqueId")
110
+ video_url = video.get("playAddr")
111
+ return video_id, author_id, author_username, video_url, images, cookies
112
+