├── .env.template ├── .github └── workflows │ └── pr-checks.yaml ├── .gitignore ├── CONTRIBUTING.md ├── Dockerfile ├── LICENSE ├── README.md ├── app ├── bot.py ├── main.py ├── settings.py ├── tiktok │ ├── __init__.py │ ├── api.py │ ├── client.py │ └── data.py └── utils.py ├── compose.yaml ├── logo.jpg ├── pyproject.toml └── requirements.txt /.env.template: -------------------------------------------------------------------------------- 1 | API_TOKEN=1234567890:qwertyuiopas-dfghjklzxcvbnmqwertyui 2 | ALLOWED_IDS=[9876543210,-1009876543210] 3 | REPLY_TO_MESSAGE=true 4 | WITH_CAPTIONS=false 5 | -------------------------------------------------------------------------------- /.github/workflows/pr-checks.yaml: -------------------------------------------------------------------------------- 1 | name: '✔️ PR Checks' 2 | on: 3 | pull_request: 4 | branches: 5 | - 'main' 6 | 7 | jobs: 8 | code-quality: 9 | name: '💎 Code-Quality' 10 | strategy: 11 | matrix: 12 | os: 13 | - ubuntu-latest 14 | python-version: 15 | - "3.11" 16 | runs-on: ${{ matrix.os }} 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v4 20 | 21 | - name: Set up Python ${{ matrix.python-version }} 22 | uses: actions/setup-python@v5 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | cache: 'pip' 26 | 27 | - name: Install dev dependencies 28 | run: pip install -e ".[dev]" 29 | 30 | - name: Lint checks with ruff 31 | run: ruff check app 32 | 33 | - name: Typing checks with mypy 34 | run: mypy app --pretty 35 | 36 | - name: Formatting checks with black 37 | run: black --check app 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | .idea/ 131 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | 3 | ## Suggest 4 | 5 | If you have idea/feature, you can [open an issue](https://github.com/captaincolonelfox/TeleTok/issues/new) 6 | or [start a discussion](https://github.com/captaincolonelfox/TeleTok/discussions) and I 7 | can try to implement it in my spare time 8 | 9 | ## Code 10 | 11 | Or you can implement it yourself and [open a pull request](https://github.com/captaincolonelfox/TeleTok/pulls), though 12 | maybe you want to [discuss](https://github.com/captaincolonelfox/TeleTok/discussions) the feature first 13 | 14 | ### Installing with dev dependencies 15 | 16 | ```shell 17 | pip install -e ".[dev]" 18 | ``` 19 | 20 | ### Checks before commit 21 | 22 | Run those checks before commit 23 | 24 | And test again, if you changed code to fix anything they find 25 | 26 | If you are not sure, if you should implement suggested fix or not: 27 | sometime we want to ignore some rules, not all of them are helpful, so just ask and we can discuss it 28 | 29 | - linter 30 | 31 | ```shell 32 | ruff check app 33 | ``` 34 | 35 | - typing 36 | 37 | ```shell 38 | mypy app 39 | ``` 40 | 41 | - formatter 42 | 43 | ```shell 44 | black --check app 45 | ``` 46 | 47 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.11.8-alpine 2 | 3 | WORKDIR /code 4 | 5 | COPY pyproject.toml requirements.txt ./ 6 | 7 | RUN pip install -r requirements.txt 8 | 9 | COPY app app 10 | 11 | CMD [ "python", "app/main.py" ] -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Igor 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![TeleTok](logo.jpg?raw=true)](https://t.me/TeleTockerBot) 2 | 3 | # [TeleTok](https://t.me/TeleTockerBot): Telegram bot for TikTok 4 | 5 | ## Description 6 | 7 | This bot will send you a video from a TikTok. Pretty simple. 8 | 9 | Just share a link to the chat (no need to mention the bot) 10 | 11 | ## Thanks to 12 | 13 | Built on top of [aiogram](https://github.com/aiogram/aiogram) 14 | 15 | # Installation 16 | 17 | ## Env 18 | 19 | (*REQUIRED*) 20 | 21 | - `API_TOKEN` - Bot token from BotFather 22 | 23 | (*OPTIONAL*) 24 | 25 | - `ALLOWED_IDS` - _JSON int list_. Gives access only to specific user/chat id (default: `[]` (empty list) = all 26 | users/chats) 27 | - `REPLY_TO_MESSAGE` - _JSON Boolean_. Whether the bot should reply to source message or not (default: `true`) 28 | - `WITH_CAPTIONS` - _JSON Boolean_. Whether the bot should include captions from TikTok in its message (default: `true`) 29 | 30 | ## Local 31 | 32 | ```bash 33 | $ python3 -m venv venv 34 | $ (venv) pip install -r requirements.txt 35 | $ (venv) echo "API_TOKEN=foo:bar" >> .env 36 | $ (venv) export $(cat .env) 37 | $ (venv) python app 38 | ``` 39 | 40 | ## Docker 41 | 42 | ```bash 43 | $ docker build -t teletok . 44 | $ docker run -e "API_TOKEN=foo:bar" teletok 45 | ``` 46 | 47 | ## Docker Compose 48 | 49 | ```bash 50 | $ echo "API_TOKEN=foo:bar" >> .env 51 | $ docker compose up -d --build 52 | ``` 53 | 54 | # License 55 | 56 | MIT 57 | 58 | -------------------------------------------------------------------------------- /app/bot.py: -------------------------------------------------------------------------------- 1 | from aiogram import Bot, Dispatcher, F 2 | from aiogram.types import BufferedInputFile, Message 3 | 4 | from settings import settings 5 | from tiktok.api import TikTokAPI 6 | 7 | dp = Dispatcher() 8 | 9 | filters = [ 10 | F.text.contains("tiktok.com"), 11 | (not settings.allowed_ids) 12 | | F.chat.id.in_(settings.allowed_ids) 13 | | F.from_user.id.in_(settings.allowed_ids), 14 | ] 15 | 16 | 17 | @dp.message(*filters) 18 | @dp.channel_post(*filters) 19 | async def handle_tiktok_request(message: Message, bot: Bot) -> None: 20 | entries = [ 21 | message.text[e.offset : e.offset + e.length] 22 | for e in message.entities or [] 23 | if message.text is not None 24 | ] 25 | 26 | urls = [ 27 | u if u.startswith("http") else f"https://{u}" 28 | for u in filter(lambda e: "tiktok.com" in e, entries) 29 | ] 30 | 31 | async for tiktok in TikTokAPI.download_tiktoks(urls): 32 | if not tiktok.video: 33 | continue 34 | 35 | video = BufferedInputFile(tiktok.video, filename="video.mp4") 36 | caption = tiktok.caption if settings.with_captions else None 37 | 38 | if settings.reply_to_message: 39 | await message.reply_video(video=video, caption=caption) 40 | else: 41 | await bot.send_video(chat_id=message.chat.id, video=video, caption=caption) 42 | -------------------------------------------------------------------------------- /app/main.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | 3 | from aiogram import Bot 4 | 5 | from bot import dp 6 | from settings import settings 7 | 8 | 9 | async def start() -> None: 10 | bot = Bot(token=settings.api_token) 11 | await dp.start_polling(bot) 12 | 13 | 14 | if __name__ == "__main__": 15 | asyncio.run(start()) 16 | -------------------------------------------------------------------------------- /app/settings.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | from dataclasses import dataclass 4 | 5 | 6 | @dataclass 7 | class Settings: 8 | api_token: str 9 | allowed_ids: list[int] 10 | reply_to_message: bool 11 | with_captions: bool 12 | 13 | 14 | def parse_env_list(key: str) -> list[int]: 15 | return list(map(int, json.loads(os.getenv(key, "[]")))) 16 | 17 | 18 | def parse_env_bool(key: str, default: str = "false") -> bool: 19 | return os.getenv(key, default).lower() in ("yes", "true", "1", "on") 20 | 21 | 22 | settings = Settings( 23 | api_token=os.getenv("API_TOKEN", ""), 24 | allowed_ids=parse_env_list("ALLOWED_IDS"), 25 | reply_to_message=parse_env_bool("REPLY_TO_MESSAGE", default="true"), 26 | with_captions=parse_env_bool("WITH_CAPTIONS", default="true"), 27 | ) 28 | -------------------------------------------------------------------------------- /app/tiktok/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/captaincolonelfox/TeleTok/c4d344d66b55db37d720c4ce7246821cdd37ff1f/app/tiktok/__init__.py -------------------------------------------------------------------------------- /app/tiktok/api.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from collections.abc import AsyncIterable 3 | 4 | from tiktok.client import AsyncTikTokClient 5 | from tiktok.data import Tiktok 6 | 7 | 8 | class TikTokAPI: 9 | @classmethod 10 | async def download_tiktoks(cls, urls: list[str]) -> AsyncIterable[Tiktok]: 11 | tasks = [cls.download_tiktok(url) for url in urls] 12 | for task in asyncio.as_completed(tasks): 13 | tiktok = await task 14 | yield tiktok 15 | 16 | @classmethod 17 | async def download_tiktok(cls, url: str) -> Tiktok: 18 | async with AsyncTikTokClient() as client: 19 | if (item := await client.get_page_data(url=url)) and item.video_url: 20 | video = await client.get_video(url=item.video_url) 21 | return Tiktok(url=url, description=item.description, video=video) 22 | return Tiktok() 23 | -------------------------------------------------------------------------------- /app/tiktok/client.py: -------------------------------------------------------------------------------- 1 | import json 2 | import random 3 | import string 4 | from datetime import UTC, datetime 5 | 6 | import httpx 7 | from bs4 import BeautifulSoup 8 | 9 | from tiktok.data import ItemStruct 10 | from utils import DifferentPageError, NoDataError, NoScriptError, retries 11 | 12 | 13 | class AsyncTikTokClient(httpx.AsyncClient): 14 | def __init__(self) -> None: 15 | super().__init__( 16 | headers={ 17 | "Referer": "https://www.tiktok.com/", 18 | "User-Agent": ( 19 | f"{''.join(random.choices(string.ascii_lowercase, k=random.randint(4, 10)))}-" 20 | f"{''.join(random.choices(string.ascii_lowercase, k=random.randint(3, 7)))}/" 21 | f"{random.randint(10, 300)} " 22 | f"({datetime.now(tz=UTC).replace(microsecond=0).timestamp()})" 23 | ), 24 | }, 25 | timeout=30, 26 | cookies={ 27 | "tt_webid_v2": f"{random.randint(10 ** 18, (10 ** 19) - 1)}", 28 | }, 29 | follow_redirects=True, 30 | ) 31 | 32 | @retries(times=3) 33 | async def get_page_data(self, url: str) -> ItemStruct: 34 | page = await self.get(url) 35 | page_id = page.url.path.rsplit("/", 1)[-1] 36 | 37 | soup = BeautifulSoup(page.text, "html.parser") 38 | 39 | if script := soup.select_one('script[id="__UNIVERSAL_DATA_FOR_REHYDRATION__"]'): 40 | script = json.loads(script.text) 41 | else: 42 | raise NoScriptError 43 | 44 | try: 45 | data = script["__DEFAULT_SCOPE__"]["webapp.video-detail"]["itemInfo"]["itemStruct"] 46 | except KeyError as ex: 47 | raise NoDataError from ex 48 | 49 | if data["id"] != page_id: 50 | raise DifferentPageError 51 | return ItemStruct.parse(data) 52 | 53 | async def get_video(self, url: str) -> bytes | None: 54 | resp = await self.get(url) 55 | if resp.is_error: 56 | return None 57 | return resp.content 58 | -------------------------------------------------------------------------------- /app/tiktok/data.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | 3 | 4 | @dataclass 5 | class Tiktok: 6 | url: str = "" 7 | description: str = "" 8 | video: bytes | None = None 9 | 10 | @property 11 | def caption(self) -> str: 12 | return f"{self.description}\n\n{self.url}" 13 | 14 | 15 | @dataclass 16 | class ItemStruct: 17 | page_id: str 18 | video_url: str 19 | description: str 20 | 21 | @classmethod 22 | def parse(cls, data: dict) -> "ItemStruct": 23 | return ItemStruct( 24 | page_id=data["id"], 25 | video_url=( 26 | (data["video"].get("playAddr", "") or data["video"].get("downloadAddr")) 27 | .encode() 28 | .decode("unicode_escape") 29 | ), 30 | description=data["desc"], 31 | ) 32 | -------------------------------------------------------------------------------- /app/utils.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import logging 3 | from collections.abc import Awaitable, Callable 4 | from functools import wraps 5 | from typing import ParamSpec, TypeVar 6 | 7 | 8 | class RetryingError(Exception): 9 | pass 10 | 11 | 12 | class NoScriptError(RetryingError): 13 | def __init__(self) -> None: 14 | super().__init__("no script") 15 | 16 | 17 | class NoDataError(RetryingError): 18 | def __init__(self) -> None: 19 | super().__init__("no data") 20 | 21 | 22 | class DifferentPageError(RetryingError): 23 | def __init__(self) -> None: 24 | super().__init__("tiktok_id is different from page_id") 25 | 26 | 27 | P = ParamSpec("P") 28 | T = TypeVar("T") 29 | 30 | Wrapper = Callable[P, Awaitable[T | None]] 31 | Decorator = Callable[[Callable[P, Awaitable[T]]], Wrapper] 32 | 33 | 34 | def retries(times: int) -> Decorator: 35 | def decorator(func: Callable[P, Awaitable[T]]) -> Wrapper: 36 | @wraps(func) 37 | async def wrapper(*args: P.args, **kwargs: P.kwargs) -> T | None: 38 | for _ in range(times): 39 | try: 40 | return await func(*args, **kwargs) 41 | except RetryingError: 42 | logging.exception("Retrying") 43 | await asyncio.sleep(0.5) 44 | return None 45 | 46 | return wrapper 47 | 48 | return decorator 49 | -------------------------------------------------------------------------------- /compose.yaml: -------------------------------------------------------------------------------- 1 | services: 2 | teletok: 3 | build: . 4 | env_file: 5 | - .env 6 | -------------------------------------------------------------------------------- /logo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/captaincolonelfox/TeleTok/c4d344d66b55db37d720c4ce7246821cdd37ff1f/logo.jpg -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [project] 2 | name = "teletok" 3 | version = "5.1.0" 4 | description = "Telegram bot that will download a video by a TikTok url" 5 | authors = [{ name = "Igor Popov", email = "lentrog@gmail.com" }] 6 | readme = "README.md" 7 | license = { file = "LICENSE" } 8 | requires-python = ">=3.11" 9 | 10 | dependencies = [ 11 | "httpx==0.27.0", 12 | "aiogram==3.4.1", 13 | "beautifulsoup4==4.12.3", 14 | ] 15 | 16 | [project.optional-dependencies] 17 | dev = [ 18 | "black~=24.3.0", 19 | "ruff~=0.3.5", 20 | "mypy~=1.9.0", 21 | ] 22 | 23 | [tool.black] 24 | target-version = ['py311'] 25 | line-length = 100 26 | 27 | 28 | [tool.mypy] 29 | mypy_path = ["app"] 30 | follow_imports = "silent" 31 | strict = true 32 | disallow_subclassing_any = false 33 | disallow_any_generics = false 34 | ignore_missing_imports = true 35 | 36 | 37 | [tool.ruff] 38 | line-length = 100 39 | target-version = "py311" 40 | src = ["app"] 41 | lint.ignore = ["D", "S311", "ANN10", "RUF001", "RUF012", "FIX", "TD002", "TD003"] 42 | lint.select = ["ALL"] 43 | 44 | 45 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | -e . --------------------------------------------------------------------------------