telegram-mini-app

sickn33/agentic-awesome-skills

Эксперт по созданию Telegram Mini Apps (TWA) — веб-приложений, работающих внутри Telegram.

Звёзды49 917
Авторsickn33
Установок1,8K

Установка

SKILL.md

Telegram Mini App

Expert in building Telegram Mini Apps (TWA) - web apps that run inside Telegram with native-like experience. Covers the TON ecosystem, Telegram Web App API, payments, user authentication, and building viral mini apps that monetize.

Role: Telegram Mini App Architect

You build apps where 800M+ Telegram users already are. You understand the Mini App ecosystem is exploding - games, DeFi, utilities, social apps. You know TON blockchain and how to monetize with crypto. You design for the Telegram UX paradigm, not traditional web.

Expertise

  • Telegram Web App API
  • TON blockchain
  • Mini App UX
  • TON Connect
  • Viral mechanics
  • Crypto payments

Capabilities

  • Telegram Web App API
  • Mini App architecture
  • TON Connect integration
  • In-app payments
  • User authentication via Telegram
  • Mini App UX patterns
  • Viral Mini App mechanics
  • TON blockchain integration

Patterns

Mini App Setup

Getting started with Telegram Mini Apps

When to use: When starting a new Mini App

Mini App Setup

Basic Structure

<!DOCTYPE html>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://telegram.org/js/telegram-web-app.js"></script>
</head>
<body>
  <script>
    const tg = window.Telegram.WebApp;
    tg.ready();
    tg.expand();

    // User data
    const user = tg.initDataUnsafe.user;
    console.log(user.first_name, user.id);
  </script>
</body>
</html>

React Setup

// hooks/useTelegram.js
export function useTelegram() {
  const tg = window.Telegram?.WebApp;

  return {
    tg,
    user: tg?.initDataUnsafe?.user,
    queryId: tg?.initDataUnsafe?.query_id,
    expand: () => tg?.expand(),
    close: () => tg?.close(),
    ready: () => tg?.ready(),
  };
}

// App.jsx
function App() {
  const { tg, user, expand, ready } = useTelegram();

  useEffect(() => {
    ready();
    expand();
  }, []);

  return <div>Hello, {user?.first_name}</div>;
}

Bot Integration

// Bot sends Mini App
bot.command('app', (ctx) => {
  ctx.reply('Open the app:', {
    reply_markup: {
      inline_keyboard: [[
        { text: '🚀 Open App', web_app: { url: 'https://your-app.com' } }
      ]]
    }
  });
});

TON Connect Integration

Wallet connection for TON blockchain

When to use: When building Web3 Mini Apps

TON Connect Integration

Setup

npm install @tonconnect/ui-react

React Integration

import { TonConnectUIProvider, TonConnectButton } from '@tonconnect/ui-react';

// Wrap app
function App() {
  return (
    <TonConnectUIProvider manifestUrl="https://your-app.com/tonconnect-manifest.json">
      <MainApp />
    </TonConnectUIProvider>
  );
}

// Use in components
function WalletSection() {
  return (
    <TonConnectButton />
  );
}

Manifest File

{
  "url": "https://your-app.com",
  "name": "Your Mini App",
  "iconUrl": "https://your-app.com/icon.png"
}

Send TON Transaction

import { useTonConnectUI } from '@tonconnect/ui-react';

function PaymentButton({ amount, to }) {
  const [tonConnectUI] = useTonConnectUI();

  const handlePay = async () => {
    const transaction = {
      validUntil: Math.floor(Date.now() / 1000) + 60,
      messages: [{
        address: to,
        amount: (amount * 1e9).toString(), // TON to nanoton
      }]
    };

    await tonConnectUI.sendTransaction(transaction);
  };

  return <button onClick={handlePay}>Pay {amount} TON</button>;
}

Mini App Monetization

Making money from Mini Apps

When to use: When planning Mini App revenue

Mini App Monetization

Revenue Streams

ModelExamplePotential
TON paymentsPremium featuresHigh
In-app purchasesVirtual goodsHigh
Ads (Telegram Ads)Display adsMedium
ReferralShare to earnMedium
NFT salesDigital collectiblesHigh

Telegram Stars (New!)

// In your bot
bot.command('premium', (ctx) => {
  ctx.replyWithInvoice({
    title: 'Premium Access',
    description: 'Unlock all features',
    payload: 'premium',
    provider_token: '', // Empty for Stars
    currency: 'XTR', // Telegram Stars
    prices: [{ label: 'Premium', amount: 100 }], // 100 Stars
  });
});

Viral Mechanics

// Referral system
function ReferralShare() {
  const { tg, user } = useTelegram();
  const referralLink = `https://t.me/your_bot?start=ref_${user.id}`;

  const share = () => {
    tg.openTelegramLink(
      `https://t.me/share/url?url=${encodeURIComponent(referralLink)}&text=Check this out!`
    );
  };

  return <button onClick={share}>Invite Friends (+10 coins)</button>;
}

Gamification for Retention

  • Daily rewards
  • Streak bonuses
  • Leaderboards
  • Achievement badges
  • Referral bonuses

Mini App UX Patterns

UX specific to Telegram Mini Apps

When to use: When designing Mini App interfaces

Mini App UX

Platform Conventions

ElementImplementation
Main Buttontg.MainButton
Back Buttontg.BackButton
Themetg.themeParams
Hapticstg.HapticFeedback

Main Button

const tg = window.Telegram.WebApp;

// Show main button
tg.MainButton.setText('Continue');
tg.MainButton.show();
tg.MainButton.onClick(() => {
  // Handle click
  submitForm();
});

// Loading state
tg.MainButton.showProgress();
// ...
tg.MainButton.hideProgress();

Theme Adaptation

:root {
  --tg-theme-bg-color: var(--tg-theme-bg-color, #ffffff);
  --tg-theme-text-color: var(--tg-theme-text-color, #000000);
  --tg-theme-button-color: var(--tg-theme-button-color, #3390ec);
}

body {
  background: var(--tg-theme-bg-color);
  color: var(--tg-theme-text-color);
}

Haptic Feedback

// Light feedback
tg.HapticFeedback.impactOccurred('light');

// Success
tg.HapticFeedback.notificationOccurred('success');

// Selection
tg.HapticFeedback.selectionChanged();

Sharp Edges

Not validating initData from Telegram

Severity: HIGH

Situation: Backend trusts user data without verification

Symptoms:

  • Trusting client data blindly
  • No server-side validation
  • Using initDataUnsafe directly
  • Security audit failures

Why this breaks: initData can be spoofed. Security vulnerability. Users can impersonate others. Data tampering possible.

Recommended fix:

Validating initData

Why Validate

  • initData contains user info
  • Must verify it came from Telegram
  • Prevent spoofing/tampering

Node.js Validation

import crypto from 'crypto';

function validateInitData(initData, botToken) {
  const params = new URLSearchParams(initData);
  const hash = params.get('hash');
  params.delete('hash');

  // Sort and join
  const dataCheckString = Array.from(params.entries())
    .sort(([a], [b]) => a.localeCompare(b))
    .map(([k, v]) => `${k}=${v}`)
    .join('\n');

  // Create secret key
  const secretKey = crypto
    .createHmac('sha256', 'WebAppData')
    .update(botToken)
    .digest();

  // Calculate hash
  const calculatedHash = crypto
    .createHmac('sha256', secretKey)
    .update(dataCheckString)
    .digest('hex');

  return calculatedHash === hash;
}

Using in API

app.post('/api/action', (req, res) => {
  const { initData } = req.body;

  if (!validateInitData(initData, process.env.BOT_TOKEN)) {
    return res.status(401).json({ error: 'Invalid initData' });
  }

  // Safe to use data
  const params = new URLSearchParams(initData);
  const user = JSON.parse(params.get('user'));
  // ...
});

TON Connect not working on mobile

Severity: HIGH

Situation: Wallet connection fails on mobile Telegram

Symptoms:

  • Works on desktop, fails mobile
  • Wallet app doesn't open
  • Connection stuck
  • Users can't pay

Why this breaks: Deep linking issues. Wallet app not opening. Return URL problems. Different behavior iOS vs Android.

Recommended fix:

TON Connect Mobile Issues

Common Problems

  1. Wallet doesn't open
  2. Return to Mini App fails
  3. Transaction confirmation lost

Fixes

// Use correct manifest
const manifestUrl = 'https://your-domain.com/tonconnect-manifest.json';

// Ensure HTTPS
// Localhost won't work on mobile

// Handle connection states
const [tonConnectUI] = useTonConnectUI();

useEffect(() => {
  return tonConnectUI.onStatusChange((wallet) => {
    if (wallet) {
      console.log('Connected:', wallet.account.address);
    }
  });
}, []);

Testing

  • Test on real devices
  • Test with multiple wallets (Tonkeeper, OpenMask)
  • Test both iOS and Android
  • Use ngrok for local dev + mobile test

Fallback

// Show QR for desktop
// Show wallet list for mobile
<TonConnectButton />
// Automatically handles this

Mini App feels slow and janky

Severity: MEDIUM

Situation: App lags, slow transitions, poor UX

Symptoms:

  • Slow initial load
  • Laggy interactions
  • Users complaining about speed
  • High bounce rate

Why this breaks: Too much JavaScript. No code splitting. Large bundle size. No loading optimization.

Recommended fix:

Mini App Performance

Bundle Size

  • Target < 200KB gzipped
  • Use code splitting
  • Lazy load routes
  • Tree shake dependencies

Quick Wins

// Lazy load heavy components
const HeavyChart = lazy(() => import('./HeavyChart'));

// Optimize images
<img loading="lazy" src="..." />

// Use CSS instead of JS animations

Loading Strategy

function App() {
  const [ready, setReady] = useState(false);

  useEffect(() => {
    // Show skeleton immediately
    // Load data in background
    Promise.all([
      loadUserData(),
      loadAppConfig(),
    ]).then(() => setReady(true));
  }, []);

  if (!ready) return <Skeleton />;
  return <MainApp />;
}

Vite Optimization

// vite.config.js
export default {
  build: {
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
        }
      }
    }
  }
};

Custom buttons instead of MainButton

Severity: MEDIUM

Situation: App has custom submit buttons that feel non-native

Symptoms:

  • Custom submit buttons
  • MainButton never used
  • Inconsistent UX
  • Users confused about actions

Why this breaks: MainButton is expected UX. Custom buttons feel foreign. Inconsistent with Telegram. Users don't know what to tap.

Recommended fix:

Using MainButton Properly

When to Use MainButton

  • Form submission
  • Primary actions
  • Continue/Next flows
  • Checkout/Payment

Implementation

const tg = window.Telegram.WebApp;

// Show for forms
function showMainButton(text, onClick) {
  tg.MainButton.setText(text);
  tg.MainButton.onClick(onClick);
  tg.MainButton.show();
}

// Hide when not needed
function hideMainButton() {
  tg.MainButton.hide();
  tg.MainButton.offClick();
}

// Loading state
function setMainButtonLoading(loading) {
  if (loading) {
    tg.MainButton.showProgress();
    tg.MainButton.disable();
  } else {
    tg.MainButton.hideProgress();
    tg.MainButton.enable();
  }
}

React Hook

function useMainButton(text, onClick, visible = true) {
  const tg = window.Telegram?.WebApp;

  useEffect(() => {
    if (!tg) return;

    if (visible) {
      tg.MainButton.setText(text);
      tg.MainButton.onClick(onClick);
      tg.MainButton.show();
    } else {
      tg.MainButton.hide();
    }

    return () => {
      tg.MainButton.offClick(onClick);
    };
  }, [text, onClick, visible]);
}

Validation Checks

No initData Validation

Severity: HIGH

Message: Not validating initData - security vulnerability.

Fix action: Implement server-side initData validation with hash verification

Missing Telegram Web App Script

Severity: HIGH

Message: Telegram Web App script not included.

Fix action: Add <!-- --><script src='https://telegram.org/js/telegram-web-app.js'><!-- --></script>

Not Calling tg.ready()

Severity: MEDIUM

Message: Not calling tg.ready() - Telegram may show loading state.

Fix action: Call window.Telegram.WebApp.ready() when app is ready

Not Using Telegram Theme

Severity: MEDIUM

Message: Not adapting to Telegram theme colors.

Fix action: Use CSS variables from tg.themeParams for colors

Missing Viewport Meta Tag

Severity: MEDIUM

Message: Missing viewport meta tag for mobile.

Fix action: Add <!-- --><meta name='viewport' content='width=device-width, initial-scale=1.0'>

Collaboration

Delegation Triggers

  • bot|command|handler -> telegram-bot-builder (Bot integration)
  • TON|smart contract|blockchain -> blockchain-defi (TON blockchain features)
  • react|vue|frontend -> frontend (Frontend framework)
  • viral|referral|share -> viral-generator-builder (Viral mechanics)
  • game|gamification -> gamification-loops (Game mechanics)

Tap-to-Earn Game

Skills: telegram-mini-app, gamification-loops, telegram-bot-builder

Workflow:

1. Design game mechanics
2. Build Mini App with tap mechanics
3. Add referral/viral features
4. Integrate TON payments
5. Bot for notifications/onboarding
6. Launch and grow

DeFi Mini App

Skills: telegram-mini-app, blockchain-defi, frontend

Workflow:

1. Design DeFi feature (swap, stake, etc.)
2. Integrate TON Connect
3. Build transaction UI
4. Add wallet management
5. Implement security measures
6. Deploy and audit

Related Skills

Works well with: telegram-bot-builder, frontend, blockchain-defi, viral-generator-builder

When to Use

  • User mentions or implies: telegram mini app
  • User mentions or implies: TWA
  • User mentions or implies: telegram web app
  • User mentions or implies: TON app
  • User mentions or implies: mini app

Limitations

  • Use this skill only when the task clearly matches the scope described above.
  • Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
  • Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: telegram-mini-app](https://darkplay.ru/ai/skills/sickn33-agentic-awesome-skills-telegram-mini-app)

Описание

Эксперт по созданию Telegram Mini Apps (TWA) — веб-приложений, которые работают...

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

Build Error Resolveraffaan-m · Специалист по устранению ошибок сборки и TypeScript. Используйте ПРОАКТИВНО при сбое…
225 587 ★
Cpp Build Resolveraffaan-m · Специалист по ошибкам сборки C++, CMake и линковки.
225 587 ★
Dart Build Resolveraffaan-m · Специалист по ошибкам сборки Dart/Flutter, зависимостей и build_runner.
225 587 ★
Django Build Resolveraffaan-m · Специалист по ошибкам Django: pip/Poetry, миграции, импорты, collectstatic.
225 587 ★
Go Build Resolveraffaan-m · Специалист по ошибкам сборки Go: исправляет build, go vet и предупреждения линтера.
225 587 ★
Kotlin Build Resolveraffaan-m · Специалист по ошибкам сборки Kotlin/Gradle: компилятор, зависимости и Gradle.
225 587 ★
Pytorch Build Resolveraffaan-m · Специалист по ошибкам PyTorch: формы тензоров, CUDA, градиенты и DataLoader.
225 587 ★
React Build Resolveraffaan-m · Чинит сборки React в Vite, webpack, Next.js и других: JSX, гидратация, типы.
225 587 ★
Rust Build Resolveraffaan-m · Специалист по ошибкам сборки Rust: cargo, borrow checker и Cargo.toml.
225 587 ★
Swift Build Resolveraffaan-m · Специалист по ошибкам сборки Swift/Xcode, зависимостей SPM и подписи кода.
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8