Моды TeleX

Мод — один файл .module. Внутри может быть что угодно: тема, HTML-виджет, JS, CSS. Любой экран приложения можно изменить или дополнить.

ДокументацияИнструкция для нейросетейСкачать официальные моды

Мод — расширение, которое работает внутри приложения с полным доступом к его API (песочницы нет сознательно). Поэтому установщик показывает предупреждение, а поле manifest.verified зарезервировано под будущую проверку модов. Моды ставятся в Настройки → Моды (или из «Настроек чатов» → «Моды тем»): из файла .module, по ссылке https://… или вставкой текста.

Файл .module

Мод — файл с расширением .module. Это обычный текст, внутри может быть что угодно: HTML, JS, CSS, тема, JSON-данные. Поддерживаются две формы.

1. JSON-пакет — несколько частей в одном файле:

{
  "manifest": { "id": "my-mod", "name": "Мой мод", "version": "1.0.0", "author": "me",
                "description": "коротко", "about": "подробно\nв несколько строк",
                "icon": "clock", "preview": ["https://…/1.png", "data:image/png;base64,…"], "tags": ["theme"],
                "settings": [ { "key": "seconds", "type": "switch", "title": "Секунды", "default": false } ] },
  "parts": [
    { "type": "theme", "data": { … } },
    { "type": "css",   "code": "…" },
    { "type": "html",  "code": "<div>…</div><script>…</script>" },
    { "type": "js",    "code": "export default function (tx) { … }" },
    { "type": "json",  "name": "table", "data": { … } }
  ]
}

2. Один исходник с аннотацией — первая строка-комментарий с @manifest {json}, остальное — тело. Тело, начинающееся с <, — HTML (скрипты внутри выполняются), JSON с ключами темы — тема, иначе — JS-модуль. Примеры: // @manifest {…}, <!-- @manifest {…} -->.

3. Один большой файл с секциями — после строки @manifest каждая часть начинается строкой-комментарием @part js|css|html|theme|json|text [имя] (// @part css, /* @part js */, <!-- @part html -->). Так в одном файле умещаются стили, разметка и код.

id — латиница/цифры/._-, 2–41 символ. Размер — до 1,5 МБ. Мод только из theme/css не исполняет код, поэтому ставится без предупреждения о полном доступе.

Языки

Любой текст манифеста — name, description, about, title/sub/подписи options в настройках — можно задать либо строкой, либо по языкам: { "ru": "…", "en": "…", "es": "…", "pt": "…", "uk": "…" }. Берётся язык приложения, иначе английский. В коде: tx.L({ ru: '…', en: '…' }). Официальные моды переведены на все 5 языков.

Иконка

icon — эмодзи или картинка: data:image/svg+xml;base64,…, https://… либо путь внутри приложения (mods/icons/<id>.svg у официальных). Лучше SVG 96×96 со скруглённым квадратом и градиентом — как у официальных модов (app/static/mods/icons/).

Карточка и страница мода

description — короткое описание на карточке, about — подробное (на странице мода), preview — картинка или список картинок (https:// или data:image/…; без них рисуется превью темы или icon на градиенте), tags, author, version.

Настройки мода

manifest.settings — схема: { key, type: "switch" | "text" | "number" | "select" | "color", title, sub?, default, min?, max?, options? }. Страница мода рисует для них элементы сама. В коде: tx.config.get(key), tx.config.set(key, v), tx.config.on(key | '*', fn); для собственного блока на странице — tx.config.render((box) => { … }). В HTML-частях объект доступен как TeleXMods['<id>'].

Тема (theme-часть)

полечто делает
varsCSS-переменные: { "all": {}, "dark": {}, "light": {} }, например --tx-bg, --tx-accent, --tx-bubble-out, --tx-surface, --tx-text (список — app/static/css/tx/tokens.css)
cssпроизвольный CSS
wallpapers[]обои в выбор: { id, name, kind: "fill" | "pattern", colors: ["#rrggbb"…], rotation, intensity, url? } (как у обоев Telegram: 1–4 цвета; intensity < 0 — тёмный фон; url паттерна — svg)
colorThemes[]цветовая тема в карусели «Настроек чатов»: { id, emoji, accent?, out: { dark: [цвета], light: [цвета] }, wallpapers: { dark, light } } — у темы свои обои для дня и ночи
applyid цветовой темы, которую выбрать сразу после установки

API кода (tx)

export default function (tx) { … } (в HTML-частях — TeleXMods['<id>']).

чтозачем
tx.themesetVars(vars, mode), addCss(css), addColorTheme(theme), addWallpaper(wp), setWallpaper(id), select(themeId), mode()
tx.uiwatch(selector, fn) — fn(el) для существующих и будущих элементов; inject(selector, html, where) — вставить разметку в любой экран; root()
tx.extaddMenu(point, provider), addHook(name, fn), on(event, fn) — см. «Точки расширения»
tx.settingsaddRow({ title, sub, icon, color, run }), addPage({ id, title, sub, icon, render(box) }) — свой экран в настройках
tx.configнастройки мода: get, set, on(key | '*', fn), render(fn(box))
tx.storageget(k), set(k, v) — произвольные данные мода
tx.onStop(fn)своя очистка (таймеры, узлы) при выключении мода
tx.dataчасти json/text из пакета, по name
tx.S, tx.apiсостояние приложения (S.posts, S.channels, S.user) и весь доступ к Telegram
tx.t, tx.toast, tx.confirm, tx.escapeHtmlперевод, всплывашка, диалог, экранирование

Точки расширения (tx.ext)

Так как это веб-приложение, мод может и напрямую менять DOM любого экрана (tx.ui.watch) — это и есть «внедрить что угодно». Всё, что мод добавил (стили, переменные, темы, обои, меню, наблюдатели, HTML, вставки), снимается при выключении или удалении.

Скин: переделать весь интерфейс одними переменными

Слой css/tx/skin.css выключен, пока на <html> нет класса tx-skin. Мод включает его вызовом tx.theme.setSkin(tokens, mode) (или частью темы skin), и все основные поверхности приложения начинают рисоваться из токенов --sk-* — в дневном и ночном режиме. Знать имена классов не нужно.

токенчто красит
--sk-card-bg -border -shadow -filter -radiusкарточки: группы настроек, пузыри постов и сообщений
--sk-bubble-in --sk-bubble-out --sk-bubble-radiusвходящие / исходящие пузыри
--sk-bar-bg -border -shadow -filter -radiusнижняя панель, поиск, вкладки, «пилюли» шапки, поле ввода
--sk-menu-bg -border -shadow -filter -radiusконтекстные меню, полоса реакций
--sk-dialog-bg --sk-dialog-radiusдиалоги
--sk-button-bg --sk-button-text --sk-button-radiusкнопки
--sk-chip-bg --sk-chip-radiusреакции, плашка активной вкладки, теги
--sk-highlightсветлая кромка сверху у всех поверхностей (внутренняя тень)
--sk-overlay, --sk-separator, --sk-field-bgзатемнение под меню/диалогами, разделители, поля ввода

Акцентный цвет всего приложения — tx.theme.setAccent('#0a84ff', '#007aff') (второй — для дня) или поле accent/accentDay в части темы. Базовые токены цвета (--tx-bg, --tx-surface, --tx-text, --tx-accent* …) — в css/tx/tokens.css.

Поверхности, которые можно менять напрямую

Если токенов мало — стилизуйте классы (мод-CSS подключается последним и перебивает стили приложения при равной специфичности): .tx-dock (нижняя панель), .tx-glass (пилюли шапки), .tx-search-main, .tx-tabs, .tx-bubble / .tx-bubble.is-out (пост, сообщение), .tx-group / .tx-row (настройки), .tx-menu, .tx-ctx-reactions, .tx-dialog, .tx-btn, .tx-reaction, .tx-mainbar (верхняя панель ленты), .tx-titlebar, .tx-mod-card. Экраны: #screen-wall, #screen-settings, #screen-profile, #screen-thread, #screen-channel.

Куда что вставлять (слоты)

tx.ui.add(слот, { id, title?, icon?, run?, html?, el?, render?(host, ctx), position? }) — вставка в именованное место интерфейса; снимается при выключении мода.

слотгдечто вставлять
dockнижняя панелькнопка-вкладка
topbarверхняя панель ленты (рядом с «TeleX» и меню)кнопка или виджет
searchвнутри поля поискакнопка (фильтр, голос…)
tabsвкладки ленты (Все · Медиа · …)ещё одна вкладка
fabплавающая круглая кнопкакнопка
post.headerрядом с названием канала в постезначок, бейдж
post.footerпод текстом постаблок (статистика, перевод, заметка)
post.actionsрядом с кнопкой «поделиться»кнопка

Остальное: пункт в меню поста — tx.ext.addMenu('post', …); строка/страница в настройках — tx.settings.addRow/addPage; свой экран — tx.ui.openScreen; текст постов — хук postText; реакция на каждый пост — tx.ui.onPost; внешний вид — tx.theme.*. Пример со всеми слотами: mods-examples/slots-demo.module.

Виды модов

Тема (без кода) · виджет (часы, погода, счётчик) · кнопка-инструмент · улучшение постов · фильтр (скрыть по словам/каналам) · своя страница (статистика, блокнот).

Новые экраны и кнопки

Жизненный цикл

Мод запускается при старте приложения, если включён. Всё, что он зарегистрировал через tx, снимается при выключении/удалении; свои таймеры и слушатели снимайте в tx.onStop. Официальные моды из каталога обновляются сами при выходе новой версии (настройки мода сохраняются). Обновление чужого мода — переустановка файла с тем же id.

Мод с помощью нейросети

В Настройки → Моды внизу: «Скопировать промпт для нейросети» → вставьте его в нейросеть и допишите, какой мод нужен → скопируйте ответ → «Вставить мод из буфера». Промпт содержит всю спецификацию и жёсткие правила вывода (только файл, без пояснений).

Публикация для всех (сообщество)

Положите <id>.module в community/mods/ через Pull Request — после проверки CI мод появится в приложении у всех (Настройки → Моды → Сообщество). Правила — в community/README.md.

Свой мод в каталоге

1. Положите файл <id>.module в app/static/mods/ и SVG-иконку в app/static/mods/icons/<id>.svg. 2. Добавьте запись в app/static/mods/catalog.json: { id, file, name, version, author, icon, description, tags } (name/description — по языкам). 3. Поднимите version, когда меняете мод — у пользователей он обновится сам. Мод из каталога получает значок проверенного.

Советы

Примеры — mods-examples/. Для нейросетей — docs/mods-for-agents.md.

ИИ в модах (tx.ai)

В TeleX есть встроенный ИИ. Мод может пользоваться им без собственного ключа: в манифесте указывается "permissions": ["ai"], а в коде вызывается tx.ai. Пользователь один раз вставляет бесплатный ключ Groq (Настройки → Ключ Groq), а при установке мода видит, что мод использует ИИ.

ВызовЧто делает
tx.ai.available()true, если в манифесте есть право ai и ключ сохранён
await tx.ai.ask('запрос', { system, json, maxTokens, temperature })один вопрос → строка
await tx.ai.chat([{ role: 'user', content: '…' }, …], opts)диалог → строка (объект при json: true)
tx.lang()язык приложения: ru, en, es, pt, uk

Лимиты: не больше 12 запросов в минуту на мод, до 12 000 символов в сообщении, до 2 000 токенов ответа, последние 24 сообщения. Модель маленькая и быстрая — просите короткие ответы и не отправляйте секреты. Ошибки приходят исключением (e.message читаем для человека, e.code — no-key, limit или key): ловите их через .catch и показывайте сообщение. Мод может подключить и свой ИИ-сервис с собственным ключом (поле settings типа text), но лучше использовать tx.ai.

Готовые примеры — официальные моды «ИИ-чат» и «Переводчик постов» (app/static/mods/ai-chat.module, ai-translate.module).

Проверка модов ИИ перед установкой

Если добавлен ключ Groq, при установке мод проверяется ИИ: он ищет опасный код (отправка данных наружу, eval, чтение сессии) и то, что ломает интерфейс (элементы поверх статус-бара, скрытие панелей, глобальные селекторы). Результат — «проблем не найдено», «есть замечания» или «опасный код» — виден в окне установки. Это подсказка, а не гарантия: ставьте только моды, которым доверяете. Проверку можно отключить в Настройки → Ключ Groq.

Новые возможности API

Что нужноКак
пост уже отрисован (замерить высоту, свернуть)tx.ui.onPostRendered((el, post, { height }) => …) — приходит через два кадра после появления карточки
текст постаtx.ui.onPostText((textEl, post, card) => …) или слот post.text (position: 'start' — перед текстом)
смена темыtx.theme.on('change', (palette) => …), tx.theme.palette() — актуальные цвета (для канваса)
пункт меню поста с галочкой и подменюtx.ext.addMenu('post', ({ post }) => [{ label, icon, run, checked, items }])
тост с кнопкой «Отмена»tx.toast('Скрыто', { action: 'Отмена', run: () => … })
горячие клавишиtx.keys.add('mod+shift+c', fn) — снимаются вместе с модом, не срабатывают при вводе текста
погода / частицы / фоновая анимацияtx.ambient.add({ id, draw(ctx, w, h, dtMs, palette) }) — один общий холст и один цикл (≤ 30 кадров/с) на все моды. Свой полноэкранный canvas и свой requestAnimationFrame создавать не нужно
медиа постаtx.media.of(post) → [{ type, url, thumb, duration, size }], tx.media.urls(post)
список каналов в настройках модаполе { "type": "channels" } (массив id) или { "type": "select", "optionsFrom": "channels" } (один id)
конфликты"conflicts": ["id-другого-мода"] в манифесте — при установке показывается предупреждение
наборы модовpresets в mods/catalog.json — одна кнопка ставит сразу несколько официальных модов («Зимний набор», «ИИ», «Читатель»)

Примеры: официальные моды «Снегопад» (tx.ambient), «Читать позже» (меню с галочкой, тост с «Отмена», страница в настройках), «Свернуть длинные посты» (onPostText).

Каталог модов (публикация без GitHub)

Во вкладке «Создать» у каждого вашего мода есть кнопка «Опубликовать»: мод попадает в общий каталог, его видят все пользователи, могут искать, ставить лайки, оценивать звёздами и устанавливать одним нажатием. Обновление — та же кнопка («Обновить»). Автор определяется секретом, который хранится на вашем устройстве, поэтому чужой мод перезаписать нельзя; убрать мод из каталога можно на его странице.

Сервер (server/) сразу отклоняет файлы, которые читают сессию Telegram или секреты приложения, отмечает eval, удалённые скрипты и сетевые запросы наружу, а после трёх жалоб скрывает мод. Моды из каталога никогда не получают метку «проверен» — её дают только официальным модам проекта. Разворачивание сервера: server/README.md.

Для нейросетей (инструкция агенту)

> NO EMOJI. Ever. Not in names, descriptions, buttons, toasts, dialogs, empty states, icon fields or code comments shown to the user. TeleX looks like Telegram: use the app's icon font (<i class="icon icon-send"></i>, names such as ai, language, copy, favorite, favorite-filled, warning, tools, key-filled, more, close, settings, article, stars-filled, darkmode, brush, info-filled, check-bold) or inline SVG with currentColor. The manifest icon is an icon-font name (e.g. "icon": "ai"), a 96×96 SVG (data:image/svg+xml;base64,…) or an https image — never an emoji.

Goal: you are asked to "make a mod/theme/widget for TeleX". Produce one file with the extension .module that the user installs in *Settings → Mods* (file, link or pasted text). No build step, no dependencies, no sandbox: the file runs inside the web app with full access.

Where to put what (pick the slot, do not guess selectors)

The user wants…Use
a button in the bottom bar (the dock)tx.ui.add('dock', { id, icon, title, run })
a button in the top bar of the feed (next to the TeleX title / menu)tx.ui.add('topbar', { id, icon, title, run })
something inside the search field (filter, voice…)tx.ui.add('search', { id, icon, run })
an extra feed tab (All · Media · Popular · Favorites · Yours)tx.ui.add('tabs', { id, title, run })
a round floating buttontx.ui.add('fab', { id, icon, run })
a badge by the channel name on every posttx.ui.add('post.header', { id, html })
a block under the post text (stats, translate, notes)tx.ui.add('post.footer', { id, render(el, { post }) {…} })
a block right before/after the post text (position: 'start' = before)tx.ui.add('post.text', { id, render(el, { post }) {…} })
a button beside the share button of a posttx.ui.add('post.actions', { id, icon, run({ post }) {…} })
an item in the post's context menutx.ext.addMenu('post', ({ post }) => [{ label, icon, run, checked?: bool | ({post}) => bool, items?: [submenu…] }]) — checked shows a tick, items opens a submenu with a Back row
a row or a whole page in Settingstx.settings.addRow(...) / tx.settings.addPage(...)
a full screen of its own (opened from any button)tx.ui.openScreen({ title, render(box) })
to change text of poststx.ext.addHook('postText', (html) => html)
to react to every post (hide, mark, count)tx.ui.onPost((el, post) => …)
to change the whole looktx.theme.setSkin(...), tx.theme.setAccent(...), tx.theme.addCss(...)
a floating widget on top of the appan html part (position: fixed)

ui.add spec: { id, title?, icon?, run?, html?, el?, render?(host, ctx), position?: 'start'|'end' }. icon is an icon-font name (preferred) or an SVG string — never an emoji. Buttons are built from icon/title/run; html/render give you the whole element. Every slot is removed automatically when the mod is turned off.

AI inside a mod (tx.ai, free, uses the user's own Groq key)

TeleX has a built-in AI. A mod can use it without its own API key: declare "permissions": ["ai"] in the manifest and call tx.ai. The user adds a free Groq key once (Settings → Groq key); the install dialog tells them that the mod uses AI.

Kinds that fit: a chat screen (ui.addDockItem + ui.openScreen), a "translate / summarise / explain" button on a post (post.actions → ask(post.text)), a post classifier or tone filter (ui.onPost + json: true, remember results in tx.storage, never one request per scrolled post), a writing helper. Full examples: app/static/mods/ai-chat.module, ai-translate.module.

// @manifest {"id":"ai-explain","name":"Explain","version":"1.0.0","icon":"lamp","description":"Explains a post in simple words","permissions":["ai"]}
// @part js
export default function (tx) {
  tx.ui.add('post.actions', { id: 'explain', icon: 'lamp', title: 'Explain', run: function (ctx) {
    if (!tx.ai.available()) { tx.toast('Settings → Groq key'); return; }
    tx.ai.ask(String(ctx.post && ctx.post.text || '').slice(0, 4000), { system: 'Explain the text in two simple sentences.', maxTokens: 300 })
      .then(function (a) { tx.ui.openScreen({ title: 'Explain', render: function (b) { b.textContent = a; } }); })
      .catch(function (e) { tx.toast(e.message); });
  } });
}

Kinds of mods (pick one, mix if needed)

1. Theme — theme part: colours, wallpapers, skin tokens. No code. 2. Widget — a small live element (clock, weather, counter): ui.add('topbar', { html }) or an html part, refresh with setInterval, clear it in tx.onStop. 3. Tool button — an icon that does one thing (dock/topbar/fab) and shows the result with tx.toast or tx.ui.openScreen. 4. Post enhancer — post.header/post.footer/post.actions, or ui.onPost + postText (translate, reading time, link previews, notes). 5. Filter — ui.onPost((el, post) => { if (…) el.style.display = 'none'; }) with settings for the words/channels to hide. 6. AI tool — permissions: ["ai"] + tx.ai.ask/chat (chat, translator, summariser, classifier). 7. Own page — ui.openScreen or settings.addPage (statistics, lists, a notebook stored in tx.storage).

Output contract

1. Write exactly one file, <id>.module, UTF-8 text. Do not wrap it in markdown fences when saving it to a file. 2. It must contain a manifest and one or more parts. Two accepted shapes:

A. JSON bundle (use this for anything with more than one part):

{
  "manifest": {
    "id": "my-mod",                 // required: [a-z0-9][a-z0-9._-]{1,40}
    "name": "My mod",               // required
    "version": "1.0.0", "author": "me",
    "description": "one line shown on the card",
    "about": "longer text\nshown on the mod page",
    "icon": "tools",                 // icon-font name (or an SVG data URL / https image); NEVER an emoji
    "preview": ["https://…/shot.png"],   // optional; https:// or data:image/…; a theme gets an auto preview
    "tags": ["theme"],
    "permissions": [],              // [] | ["ai"] — "ai" unlocks tx.ai (the user's Groq key)
    "settings": [ { "key": "size", "type": "number", "title": "Size", "default": 16, "min": 10, "max": 30 } ]
  },
  "parts": [
    { "type": "theme", "data": { } },
    { "type": "css",   "code": "…" },
    { "type": "html",  "code": "<div>…</div><script>const tx = TeleXMods['my-mod']; …</script>" },
    { "type": "js",    "code": "export default function (tx) { … }" },
    { "type": "json",  "name": "table", "data": { } }
  ]
}

B. Single annotated source — first line is a comment holding @manifest {one-line json}, the rest is the body: // @manifest {…} + JS module · <!-- @manifest {…} --> + HTML · /* @manifest {…} */ + JSON theme. Body starting with < = HTML, JSON with vars|colorThemes|wallpapers|css = theme, anything else = JS module (must export default function (tx)).

C. One big file with sections (best for an AI: one paste, many parts). After the @manifest line, start every part with a comment line @part js|css|html|theme|json|text [name] — e.g. // @part css, /* @part js */, <!-- @part html -->, // @part theme (JSON), // @part json table:

// @manifest {"id":"my-mod","name":{"ru":"…","en":"…"},"version":"1.0.0","description":{…}}
// @part css
.tx-dock { border-radius: 14px; }
// @part js
export default function (tx) { /* … */ }

Limits: total ≤ 1.5 MB. A mod made only of theme/css parts executes no code (the user gets a lighter confirmation).

Languages and icon (do this for every mod you publish)

Any manifest text (name, description, about, settings title/sub, options labels) may be a string or { "ru": "…", "en": "…", "es": "…", "pt": "…", "uk": "…" }. Provide all five when the mod is meant for others; the app picks its language, then English. In code use tx.L({ ru: '…', en: '…', … }). icon: an icon-font name, or an image — data:image/svg+xml;base64,… / https://… / mods/icons/<id>.svg (official mods). Prefer a 96×96 SVG: rounded square rx=22 with a two-colour gradient and a white stroke glyph (see app/static/mods/icons/*.svg).

Restyling the whole app (skin tokens)

tx.theme.setSkin({ '--sk-card-bg': '…', … }, 'all'|'dark'|'light') (or a theme part "skin": { "dark": {…}, "light": {…} }) turns on the skin layer (app/static/css/tx/skin.css): every main surface is then drawn from tokens — --sk-card-{bg,border,shadow,filter,radius}, --sk-bubble-{in,out,radius}, --sk-bar-{bg,border,shadow,filter,radius} (dock, pills, tabs, search), --sk-menu-{bg,border,shadow,filter,radius}, --sk-dialog-{bg,radius}, --sk-button-{bg,text,radius}, --sk-chip-{bg,radius}, --sk-highlight, --sk-overlay, --sk-separator, --sk-field-bg. Set both day and night. Accent of the whole app: tx.theme.setAccent(hex, dayHex?). For anything the tokens do not reach, add CSS (tx.theme.addCss) using the classes listed in docs/mods.md. New UI: tx.ui.openScreen({ title, render(box) }), tx.ui.addDockItem({ id, title, icon, run }), tx.settings.addPage, tx.ui.onPost((el, post) => …), tx.app.* (navigation). Official catalog: app/static/mods/catalog.json + <id>.module + icons/<id>.svg; bump version and installed copies update themselves.

Settings schema (manifest.settings[])

{ key, type, title, sub?, default, … } with type: switch (bool) · number (min,max,step) · select (options: ["a","b"] or [["value","Label"]]) · color (#rrggbb) · text. The mod page renders the controls. Read with tx.config.get(key); react with tx.config.on(key | '*', fn); for a custom block use tx.config.render((box) => { box.innerHTML = '…' }).

Theme part

{ "vars":  { "all": {}, "dark": { "--tx-bg": "#000" }, "light": { "--tx-bg": "#f0f0f5" } },
  "css": "…",
  "wallpapers":  [ { "id": "dusk", "name": "Dusk", "kind": "fill", "colors": ["#3a1c4a", "#e0643a"], "rotation": 45, "intensity": 0 } ],
  "colorThemes": [ { "id": "sunset", "emoji": "🌇", "accent": "orange",
                     "out": { "dark": ["#cf4339", "#e08a35"], "light": ["#e0483f", "#f09a3a"] },
                     "wallpapers": { "dark": { "kind": "fill", "colors": ["#2a1030", "#8a3a2a"] }, "light": { "kind": "fill", "colors": ["#ffd9b8", "#ffb48a"] } } } ],
  "apply": "sunset" }

Wallpaper: kind fill | pattern (url to an svg); 1–4 colors; rotation degrees (2 colours); intensity negative = dark background (pattern lit by the colours). accent: blue|violet|orange|cyan|green|pink|… (names in app/static/js/core/prefs.js ACCENTS). CSS variables: see app/static/css/tx/tokens.css.

More API (read this before hacking the DOM)

NeedUse
a post is laid out (measure heights, collapse)tx.ui.onPostRendered((el, post, { height }) => …) — fires two frames after the card is in the DOM; tx.ui.onPost fires immediately
the text element of every posttx.ui.onPostText((textEl, post, card) => …) (class post-text) or slot post.text — for collapse, highlight, translate, table of contents
theme changes / colours for a canvastx.theme.on('change', (palette) => …) and tx.theme.palette() → { mode, bg, surface, surface2, text, textSecondary, accent, accentFill, glass, separator, red, green } — never poll data-theme
a toast with an action (Undo)tx.toast('Hidden', { action: 'Undo', run: () => … }) (stays ~5.5 s)
keyboard shortcutstx.keys.add('mod+shift+c', (e) => …) — removed with the mod; plain keys never fire while the user types
weather / particles / any full-screen animationtx.ambient.add({ id, draw(ctx, w, h, dtMs, palette) {…} }) — ONE shared canvas under the app (z-index 2, no clicks) and ONE ≤ 30 fps loop for all mods; cleared for you; off in power-saving mode. Never create your own full-screen canvas or requestAnimationFrame loop.
a full-screen page with a Telegram-like headertx.ui.openScreen({ title, subtitle?, avatar?: svgOrImgHtml, actions?: [{ icon, title, run }], chat?: true, render(box, { footer, setSubtitle, close, el }) {…} }) — chat: true gives a chat layout: wallpaper background, scrolling box, a pinned footer for the composer; setSubtitle('typing…') updates the line under the title
emoji that arrive inside user content (AI answers, post text)tx.emoji.html(escapedHtml) renders them as Apple images. Do not put emoji in your own UI
media of a posttx.media.of(post) → [{ type, url, thumb, duration, size }], tx.media.urls(post) → [url] — never scrape the DOM
a list of channels in settingssetting { "key": "quiet", "type": "channels", "title": "…" } → array of channel ids (strings); { "type": "select", "optionsFrom": "channels" } → one id. Channels are in tx.S.channels (id, title)
mods that cannot work togethermanifest "conflicts": ["other-mod-id"] — the install dialog warns the user (check both mods: declare it in the newer one)
a ready-made set of mods (official catalog)presets in app/static/mods/catalog.json: { id, icon, name{}, description{}, mods: [ids] } — one button installs all

Code API — tx (argument of export default function (tx); in html parts: TeleXMods['<id>'])

tx.onStop(fn) registers your own cleanup (timers, nodes). Everything registered through tx is removed when the mod is disabled/deleted. Things you create *outside* tx (timers, global listeners, document.body nodes) are your responsibility — for HTML parts the root <div class="tx-mod-root"> is removed automatically, timers are not.

How to build any UI change

1. Find the markup you want to change in app/static/js/** (templates are template-literals) and the styles in app/static/css/tx/*.css. Class prefix tx-; screens: #screen-wall, #screen-settings, #screen-profile, #screen-thread, #screen-channel; dock .tx-dock. 2. Restyle with css/vars parts (no code). Add behaviour with tx.ui.watch(selector, fn). Add markup with tx.ui.inject. 3. The UI re-renders often — never rely on a node surviving; use watch, not a one-off querySelector. 4. Use theme variables (var(--tx-accent), var(--tx-surface), var(--tx-text)) so the mod works in day and night mode.

Checklist before you hand the file over

Working examples: mods-examples/sunset-theme.module (JSON bundle, theme) · clock-widget.module (HTML + settings) · copy-post-link.module (JS + menus). Full human documentation: docs/mods.md.

Rule 0: no emoji anywhere (UI text, buttons, toasts, names, descriptions, icon). Use the Telegram icon font (<i class="icon icon-NAME"></i>) or inline SVG. Emoji look cheap and break the Telegram feel.

This part explains *how to do it well and why*. A mod that ignores it can overlap the phone's status bar, cover the bottom bar, become unreadable in day mode or (worst case) make the app unusable. The app has an emergency switch (⋮ menu → "Disable all mods", and automatic safe mode after 2 failed starts), but a good mod never needs it.

1. The golden rules (why mods break the app)

1. Never use position: fixed / absolute with top: 0, top: 8px, left: 0; right: 0; height: 100% for something small. On a phone the app is edge-to-edge: the status bar (clock, battery) is drawn *over* the top of the page. Everything near top: 0 hides behind it or collides with it. The real height is var(--tx-safe-top) (≈ 24–48 px, 0 on desktop). The same at the bottom: the gesture bar is var(--tx-safe-bottom), and the app's own dock lives in the bottom ~72 px. → Prefer a slot (tx.ui.add('topbar'|'dock'|'fab'|'post.footer'…)): the app places it correctly on every device. → If you really need a floating element: top: calc(var(--tx-safe-top) + 64px) (below the title bar) or bottom: calc(var(--tx-dock-h) + 24px + var(--tx-safe-bottom)) (above the dock). 2. Never cover the whole screen with a transparent/translucent layer, never set pointer-events: auto on something full-screen, never put overflow: hidden on html/body/#app. A floating widget must be small and may carry pointer-events: none unless it is a button. 3. Never hide or restyle the elements the user needs to leave the screen (.tx-dock, .tx-mainbar, the ⋮ button, settings rows) with display: none or visibility: hidden. 4. Do not use hard-coded colours (#000, #fff, white) for text or surfaces. The app has day and night modes; use the variables from section 3. A white clock on a white day background is invisible. 5. Do not touch html, body, #app, .tx-screen layout properties (display, position, height, transform, filter, overflow, zoom). transform/filter on an ancestor breaks every position: fixed child (the dock jumps, the viewer shifts). backdrop-filter on a large element is expensive: ≤ 3 per screen, never on a scrolling list item. 6. Never write a global rule without a prefix. div { … }, button { … }, * { … }, .icon { … } restyle the whole app. Always scope: .tx-mod-<id> … for your own elements, or an exact app selector. 7. Clean up. Timers (setInterval), global listeners (window.addEventListener), observers: register them with tx.onStop(() => clearInterval(t)). Everything made through tx.ui.* / tx.theme.* is removed automatically. 8. Handle errors. Wrap network/JSON code in try/catch; a mod that throws at start is rejected and removed. Never block: no alert, no endless loops, no synchronous XHR. 9. Touch targets ≥ 40×40 px, text ≥ 13 px. Test at a width of 360 px. 10. One concern per mod. A weather widget must not also restyle the dock.

2. The layout of the app (so that you know where things are)

┌──────────────── phone ────────────────┐
│ status bar (OS)      ← var(--tx-safe-top) tall, drawn over the page; NOTHING of yours here
├───────────────────────────────────────┤
│ .tx-mainbar        56 px: stories stack · "TeleX" · search · ⋮     ← slot 'topbar' (end side)
│ #header-search-bar search field                                         ← slot 'search'
│ #feed-tabs         All · Media · Popular · Favorites                    ← slot 'tabs'
│ ┌ post card (.tx-bubble) ───────────┐
│ │ header: avatar · channel · time   │ ← slot 'post.header'
│ │ text, photo/video, buttons        │
│ │ footer: reactions · views · share │ ← slot 'post.footer' (below text) / 'post.actions' (by share)
│ └───────────────────────────────────┘
│ …scrolls…                                          [fab]  ← slot 'fab', ~(dock + 28 px) above the bottom
│   (  Feed   Settings   Profile  )  .tx-dock, 60 px + var(--tx-safe-bottom)   ← slot 'dock'
└───────────────────────────────────────┘

Column width on desktop: --tx-column-w = 680 px, centred. Screens: #screen-wall (feed), #screen-settings, #screen-profile, #screen-thread (comments), #screen-channel. Only one screen is visible at a time; the app sets data-view="wall|settings|…" on #app.

Stacking order (z-index) — stay *below* what must stay on top:

layerz-index
wallpaper0–1
app content .tx-app10
sticky header / tabs29–31
dock39–40
fab, floating buttons38–45
media viewer80
mod full-screen page (openScreen)150
dialogs / confirm200
stories viewer300
toast400

A widget that must float over the feed: z-index: 35 (above content and headers, below the dock). Never above 100 unless it is a dialog the user can close.

3. Colours and tokens (the real values)

Use var(--token) — the value changes with day/night mode, accent and wallpaper theme.

tokennight (default)dayuse for
--tx-bg#000000#f0f0f5page background
--tx-surface#1c1c1d#ffffffcards, settings groups
--tx-surface-2#262628#f2f2f6menus, inputs, secondary cards
--tx-bubble#212123#ffffffincoming post/message bubble
--tx-bubble-outgradient/#2b3e63gradientoutgoing bubble
--tx-glassrgba(34,34,36,.72)rgba(255,255,255,.8)translucent bars (use with backdrop-filter: var(--tx-glass-blur))
--tx-glass-borderrgba(255,255,255,.075)rgba(0,0,0,.08)1 px borders of glass
--tx-separatorrgba(255,255,255,.08)rgba(0,0,0,.09)divider lines
--tx-text#ffffff#000000main text
--tx-text-2#9d9da3#707579secondary text, subtitles
--tx-hint#6e6e74#9a9ea4hints, placeholders
--tx-accent#7595ff#3a6fe6links, active icons, accent text
--tx-accent-fill#5a83f3samefilled buttons, active tab
--tx-accent-softaccent @16 %accent @12 %soft highlight behind accent items
--tx-red / --tx-green#ff5b5b / #4fbf6a#e5484d / #2f9e44danger / success
--tx-bubble-radius17pxcorner radius of cards
--tx-safe-top, --tx-safe-bottomstatus bar / gesture bar heightinsets — always add them to fixed positions
--tx-dock-h64pxdock height
--tx-fontRoboto stackfont: font-family: var(--tx-font)

Accent presets (tx.theme.setAccent(fill, day)): blue #5a83f3/#3a6fe6 (default), classic #3e88f7, violet #8774e1, cyan #2fa9c7, green #4fae4e, orange #e88a35, pink #d9608f.

Rules for choosing colours

4. Skin tokens — restyle the whole app without selectors

When a mod wants a new *look* (glass, neon, paper, flat…), set skin tokens instead of writing CSS for dozens of classes. tx.theme.setSkin(tokens, 'all'|'dark'|'light') turns on the layer; every card, bar, menu, dialog and button then reads these tokens. Unset tokens keep the default.

grouptokensaffects
card--sk-card-bg, -border, -shadow, -filter, -radiussettings groups, post bubbles, profile cards
bubble--sk-bubble-in, --sk-bubble-out, --sk-bubble-radiusmessage/post bubbles
bar--sk-bar-bg, -border, -shadow, -filter, -radiusdock, header pills, tabs, search
menu--sk-menu-bg, -border, -shadow, -filter, -radiuscontext menu, reactions strip
dialog--sk-dialog-bg, --sk-dialog-radiusconfirm dialogs, sheets
button--sk-button-bg, --sk-button-text, --sk-button-radiusfilled buttons
chip--sk-chip-bg, --sk-chip-radiusreactions, small pills
misc--sk-highlight (inner top light), --sk-overlay (dim behind dialogs), --sk-separator, --sk-field-bg

Always give both modes — a skin that only looks right at night is a bug:

tx.theme.setSkin({ '--sk-card-bg': 'rgba(28,28,32,.55)', '--sk-card-filter': 'blur(18px) saturate(160%)', '--sk-card-border': 'rgba(255,255,255,.08)', '--sk-card-radius': '22px' }, 'dark');
tx.theme.setSkin({ '--sk-card-bg': 'rgba(255,255,255,.62)', '--sk-card-filter': 'blur(18px) saturate(160%)', '--sk-card-border': 'rgba(0,0,0,.06)', '--sk-card-radius': '22px' }, 'light');

If a mod has *setting*s that change a token (blur strength, radius, accent), re-apply in tx.config.on('*', apply).

5. Choosing the right kind of mod (and why)

IdeaKindWhy this and not another
New colours / wallpaper / looktheme part (vars, colorThemes, wallpapers, skin)no code → can't crash; shown in Settings → Chat settings
Small live info (clock, weather, counters)slot topbar or post.header with html/renderthe app positions it; no overlap with the status bar
A button that does one thingslot dock / topbar / fab with icon, title, runconsistent look, 40 px target, removed on disable
Extra info on every postpost.footer / post.header / post.actions or ui.onPostre-applied for posts loaded later (scrolling)
Hide / mark postsui.onPost + a setting with the wordsruns for every post, including new ones
Change post textext.addHook('postText', html => …)sync, before render; returns the new HTML
Own page (notes, stats, list)ui.openScreen (+ a dock or topbar button) or settings.addPagea screen over the app with a back arrow; never inject into other screens
AI feature (chat, translate, summarise)permissions: ["ai"] + tx.aibuilt-in, free, uses the user's key — no key handling in the mod
Per-mod optionsmanifest.settingsthe app renders the controls and persists the values
Snow, rain, stars, any full-screen animationtx.ambient.add(...)one shared canvas + one loop for all mods; a private canvas/RAF per mod kills weak phones
Floating widgetan html part — only with the safe-area rules of section 1last resort

6. Recipes (complete, copy-paste-safe)

All recipes are sectioned .module files. Keep your own file in the same shape.

6.1 Clock in the top bar (the correct way — no overlap with the status bar)

// @manifest {"id":"topbar-clock","name":{"ru":"Часы","en":"Clock","es":"Reloj","pt":"Relógio","uk":"Годинник"},"version":"1.0.0","author":"you","description":{"ru":"Часы в шапке ленты","en":"A clock in the feed header","es":"Un reloj en la cabecera","pt":"Um relógio no cabeçalho","uk":"Годинник у шапці стрічки"},"icon":"clock","tags":["widget"],"settings":[{"key":"h24","type":"switch","title":{"ru":"24-часовой формат","en":"24-hour format","es":"Formato 24 h","pt":"Formato 24 h","uk":"24-годинний формат"},"default":true}]}
// @part js
export default function (tx) {
  function fmt() {
    return new Date().toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: !tx.config.get('h24') });
  }
  tx.ui.add('topbar', {
    id: 'clock',
    html: '<span class="tx-mod-clock" style="font:500 15px var(--tx-font);color:var(--tx-text-2);padding:0 6px"></span>',
    render: function (host) {
      var span = host.querySelector('.tx-mod-clock') || host;
      var tick = function () { span.textContent = fmt(); };
      tick();
      var timer = setInterval(tick, 15000);
      tx.onStop(function () { clearInterval(timer); });
    },
  });
}

Why this is right: the slot puts the clock *inside* the 56 px bar that already sits below the status bar, uses theme colours, and stops its timer.

6.2 A tool button + a result dialog

// @manifest {"id":"post-counter","name":{"ru":"Счётчик постов","en":"Post counter","es":"Contador","pt":"Contador","uk":"Лічильник"},"version":"1.0.0","author":"you","description":{"ru":"Показывает, сколько постов загружено","en":"Shows how many posts are loaded","es":"Muestra cuántas publicaciones hay","pt":"Mostra quantas publicações há","uk":"Показує, скільки дописів завантажено"},"icon":"stats"}
// @part js
export default function (tx) {
  tx.ui.add('fab', {
    id: 'count', icon: 'stats', title: 'Posts',
    run: function () { tx.toast(String((tx.S.posts || []).length)); },
  });
}

6.3 Filter: hide posts containing words

// @manifest {"id":"word-filter","name":{"ru":"Фильтр слов","en":"Word filter","es":"Filtro","pt":"Filtro","uk":"Фільтр слів"},"version":"1.0.0","author":"you","description":{"ru":"Скрывает посты с заданными словами","en":"Hides posts with chosen words","es":"Oculta publicaciones","pt":"Oculta publicações","uk":"Ховає дописи"},"icon":"hand-stop","settings":[{"key":"words","type":"text","title":{"ru":"Слова через запятую","en":"Words, comma separated","es":"Palabras","pt":"Palavras","uk":"Слова через кому"},"default":""}]}
// @part js
export default function (tx) {
  function words() {
    return String(tx.config.get('words') || '').toLowerCase().split(',').map(function (w) { return w.trim(); }).filter(Boolean);
  }
  function check(el, post) {
    var text = String((post && (post.text || post.message)) || el.textContent || '').toLowerCase();
    el.style.display = words().some(function (w) { return text.indexOf(w) >= 0; }) ? 'none' : '';
  }
  tx.ui.onPost(check);
  tx.onStop(function () { document.querySelectorAll('.tx-bubble[style*="display: none"]').forEach(function (e) { e.style.display = ''; }); });
}

6.4 Post footer: reading time

// @manifest {"id":"read-time","name":{"ru":"Время чтения","en":"Reading time","es":"Tiempo de lectura","pt":"Tempo de leitura","uk":"Час читання"},"version":"1.0.0","author":"you","description":{"ru":"Время чтения под постом","en":"Reading time under a post","es":"Tiempo de lectura","pt":"Tempo de leitura","uk":"Час читання під дописом"},"icon":"timer"}
// @part js
export default function (tx) {
  tx.ui.add('post.footer', {
    id: 'rt',
    render: function (el, ctx) {
      var words = String((ctx.post && ctx.post.text) || '').split(/\s+/).filter(Boolean).length;
      if (words < 40) { el.style.display = 'none'; return; }
      el.style.cssText = 'font-size:12px;color:var(--tx-hint);padding:2px 0';
      el.textContent = '⏱ ' + Math.max(1, Math.round(words / 200)) + ' min';
    },
  });
}

6.5 Own page with saved data (notebook)

// @manifest {"id":"notebook","name":{"ru":"Блокнот","en":"Notebook","es":"Cuaderno","pt":"Caderno","uk":"Блокнот"},"version":"1.0.0","author":"you","description":{"ru":"Заметки в приложении","en":"Notes inside the app","es":"Notas","pt":"Notas","uk":"Нотатки"},"icon":"note"}
// @part js
export default function (tx) {
  tx.ui.addDockItem({
    id: 'notes', title: 'Notes', icon: 'note',
    run: function () {
      tx.ui.openScreen({
        title: 'Notes',
        render: function (box) {
          box.innerHTML = '<textarea class="tx-mod-notes" style="width:100%;min-height:50vh;box-sizing:border-box;padding:14px;border-radius:16px;border:1px solid var(--tx-separator);background:var(--tx-surface);color:var(--tx-text);font:16px var(--tx-font);resize:vertical"></textarea>';
          var ta = box.querySelector('textarea');
          ta.value = tx.storage.get('text') || '';
          ta.addEventListener('input', function () { tx.storage.set('text', ta.value); });
        },
      });
    },
  });
}

6.6 Theme with skin (glass look, day + night)

// @manifest {"id":"my-glass","name":{"ru":"Стекло","en":"Glass","es":"Cristal","pt":"Vidro","uk":"Скло"},"version":"1.0.0","author":"you","description":{"ru":"Полупрозрачные карточки","en":"Translucent cards","es":"Tarjetas translúcidas","pt":"Cartões translúcidos","uk":"Напівпрозорі картки"},"icon":"brush","tags":["theme"]}
// @part theme
{ "skin": {
    "dark":  { "--sk-card-bg": "rgba(28,28,32,.55)", "--sk-card-filter": "blur(18px) saturate(160%)", "--sk-card-border": "rgba(255,255,255,.08)", "--sk-bar-bg": "rgba(30,30,34,.6)" },
    "light": { "--sk-card-bg": "rgba(255,255,255,.62)", "--sk-card-filter": "blur(18px) saturate(160%)", "--sk-card-border": "rgba(0,0,0,.06)", "--sk-bar-bg": "rgba(255,255,255,.7)" }
  } }

6.7 A floating widget, only if a slot does not fit (safe-area aware)

// @manifest {"id":"float-note","name":"Floating note","version":"1.0.0","author":"you","description":"A small note card above the dock","icon":"pin"}
// @part html
<div class="tx-mod-float" style="position:fixed;z-index:35;left:12px;bottom:calc(var(--tx-dock-h) + 24px + var(--tx-safe-bottom));max-width:60vw;padding:8px 12px;border-radius:14px;background:var(--tx-glass);border:1px solid var(--tx-glass-border);backdrop-filter:var(--tx-glass-blur);color:var(--tx-text);font:14px var(--tx-font);pointer-events:none">Hello</div>

Note bottom includes the dock and the gesture inset, pointer-events:none lets taps through, theme colours, small size.

6.8 Make it look like Telegram (official-mod quality)

Official mods should feel native. Reuse the app's look instead of inventing one: bubbles use --tx-bubble / --tx-bubble-out with border-radius: 17px and a 6px corner on the last bubble of a group; glass bars use --tx-glass + --tx-glass-blur; primary buttons are round/pill with --tx-accent-fill; icons come from the icon font (<i class="icon icon-send">, icon-copy, icon-close, icon-more, icon-language, icon-favorite); no emoji at all (use icon-font glyphs; tx.emoji.html exists only to render emoji that arrive inside user content); lists use the .tx-group card look; add an empty state (big emoji + one sentence + a suggestion), a typing indicator (three bouncing dots) while waiting, a Telegram-style toast with Undo for destructive actions, and stream AI answers with tx.ai.stream. See mods-src/ai-chat.js for a complete example.

7. Pitfalls we have seen (do NOT repeat)

8. Self-review checklist (do it before answering)

1. Every element I add is inside a slot, or is position:fixed with safe-area maths and z-index ≤ 45, small, and does not cover the title bar, status bar or dock. 2. No selector without a .tx-mod-… prefix or an exact app class; no *, no bare tags. 3. All colours are var(--tx-…)/var(--sk-…), or have a day and a night variant. 4. Timers/listeners are cleaned in tx.onStop. 5. Errors are caught; no use of undocumented tx methods. 6. Manifest is complete (5 languages, icon, version, description); the file is valid (JSON parses / JS module has export default function (tx)). 7. The whole answer is ONE code block; no template literals. 8. Imagine the user installs it on a phone at 360 px width in day mode: is anything covered, cut off or invisible? If unsure, use a slot.