Skip to content

rlchandani/Telegram-Bot

Repository files navigation

πŸ€– AI Telegram Bot - Stock & Weather Cards

A powerful Telegram bot that generates beautiful, visual cards for real-time stock quotes and weather information. Built with Firebase Cloud Functions, GrammY, and server-side image generation.

Node.js Firebase TypeScript License


πŸ“Έ Screenshots

Single Stock Card

Query a single stock with $AAPL to get a detailed card:

Single Stock Card

Features displayed:

  • Current price with daily change percentage
  • Year-to-Date (YTD) performance
  • YTD vs SPY comparison (S&P 500 benchmark)

Multi-Stock Card

Query multiple stocks at once with $AAPL $MSFT $GOOG:

Multi-Stock Card

Features displayed:

  • Up to 10 stocks in a single card
  • Alphabetically sorted by ticker
  • Compact view with price, change %, YTD, and YTD vs SPY

🌧️ Weather Cards

Get real-time weather with Weather City:

Daytime vs Nighttime The card automatically adapts its theme and units based on location and time of day.

Daytime (Tokyo - Metric) Nighttime (New York - Imperial)
Weather Day Weather Night

Features:

  • Smart Theme: Light mode for day, Dark mode for night
  • Auto-Units: Imperial (F, mph) for US, Metric (C, km/h) for others
  • Hourly Forecast: Next 6 hours trends
  • Detailed Metrics: Feels like, Wind, Humidity, Visibility

✨ Features

πŸ“ˆ Stock Quotes

  • Real-time prices via Yahoo Finance API
  • Single stock queries: $AAPL, $TSLA, $GOOG
  • Multi-stock queries: $AAPL $MSFT $AMZN $NVDA (up to 10 stocks)
  • Alphabetical sorting for multi-stock cards
  • YTD Performance: Calculated using the close price of the first trading day of the year
  • SPY Comparison: Shows how the stock performs vs the S&P 500 benchmark
  • Color-coded values: Green for gains, red for losses

🌀️ Weather

  • City-based queries: Weather London, Weather New York
  • City-based queries: Weather London, Weather New York
  • Smart Units: Automatically uses Fahrenheit/Miles for US and Celsius/Kilometers for the rest of the world.
  • Dynamic Themes: Changes between Light (Day) and Dark (Night) modes based on local time.
  • Detailed Forecast: Hourly trend chart and key metrics.

πŸ›‘οΈ Dashboard & Administration

  • Web Dashboard: comprehensive management of groups, history, and status.
  • Group Management: View details, history, and ban/unban groups.
  • Strict Security: Bot only responds to registered, active, and unblocked groups.
  • Notifications: Automated alerts sent to groups upon ban/unblock.
  • Activity Stats: Track message and image generation counts per group.

🎨 Visual Cards

  • Server-side PNG generation using Satori + Resvg
  • Dark theme with professional styling
  • Custom Roboto font rendering
  • Dynamic sizing for multi-stock cards

πŸ—οΈ Architecture

AI-Telegram/
β”œβ”€β”€ firebase.json          # Firebase configuration (Functions + Hosting)
β”œβ”€β”€ firestore.indexes.json # Database indexes
β”œβ”€β”€ .github/
β”‚   └── workflows/         # CI/CD Workflows
β”œβ”€β”€ dashboard/             # Next.js Admin Dashboard
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ app/           # App Router
β”‚   β”‚   β”œβ”€β”€ components/    # Reusable UI components (Tables, Dialogs, etc.)
β”‚   β”‚   └── lib/           # API Client & Firebase Auth
β”œβ”€β”€ functions/
β”‚   β”œβ”€β”€ src/
β”‚   β”‚   β”œβ”€β”€ index.ts       # Firebase Functions entry point
β”‚   β”‚   β”œβ”€β”€ bot.ts         # GrammY bot handlers
β”‚   β”‚   β”œβ”€β”€ admin.ts       # Admin API backend
β”‚   β”‚   β”œβ”€β”€ generator/
β”‚   β”‚   β”‚   └── card.tsx   # React components for card generation
β”‚   β”‚   └── services/
β”‚   β”‚       β”œβ”€β”€ db.ts      # Firestore Database Service
β”‚   β”‚       β”œβ”€β”€ stock.ts   # Yahoo Finance integration
β”‚   β”‚       └── weather.ts # Weather API integration
β”‚   β”œβ”€β”€ set-admin.js       # Admin claim utility script
β”‚   β”œβ”€β”€ assets/
β”‚   β”‚   └── fonts/         # Roboto font files
β”‚   β”œβ”€β”€ package.json
β”‚   └── tsconfig.json
└── docs/
    └── screenshots/       # Documentation images

Tech Stack

Component Technology
Runtime Node.js 20
Cloud Functions Firebase Functions (2nd Gen)
Bot Framework GrammY
Stock Data Yahoo Finance API (yahoo-finance2)
Image Generation Satori (SVG) + Resvg (PNG)
Language TypeScript

πŸš€ Getting Started

Prerequisites

  • Node.js 20+
  • Firebase CLI (npm install -g firebase-tools)
  • A Telegram Bot Token (from @BotFather)

Installation

  1. Clone the repository

    git clone https://github.com/yourusername/AI-Telegram.git
    cd AI-Telegram
  2. Install dependencies

    cd functions
    npm install
  3. Configure environment variables

    Create functions/.env:

    TELEGRAM_BOT_TOKEN=your_telegram_bot_token_here
  4. Build the project

    npm run build

πŸ§ͺ Local Development & Testing

Start the Firebase Emulator

cd functions
npm run serve

This will:

  • Build the TypeScript code
  • Start the Firebase Functions emulator on http://127.0.0.1:5001
  • Watch for file changes

Set Up Webhook for Local Testing

You'll need to expose your local server to the internet. Use ngrok or a similar tunneling service:

# In a separate terminal
ngrok http 5001

Then set your Telegram webhook:

curl -X POST "https://api.telegram.org/bot<YOUR_TOKEN>/setWebhook" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://your-ngrok-url.ngrok.io/demo-test/us-central1/telegramWebhook"}'

Test Commands

Once the webhook is set, test in Telegram:

Command Description
/start Show welcome message and help
$AAPL Get Apple stock card
$AAPL $MSFT $GOOG Get multi-stock card
Weather London Get weather card for London
/start Activate bot interactions in current group (Admins only)
/stop Deactivate bot interactions in current group (Admins only)

πŸ“¦ Deployment

Deploy to Firebase

  1. Login to Firebase

    firebase login
  2. Select your project

    firebase use your-project-id
  3. Set environment secrets

    firebase functions:secrets:set TELEGRAM_BOT_TOKEN
  4. Deploy Functions & Dashboard

    Option A: GitHub Actions (Recommended)

    • Push to the antigravity branch.
    • The workflow firebase-deploy.yml will automatically build and deploy both Functions and Dashboard.
    • Ensure you set these Repository Secrets in GitHub:
      • TELEGRAM_BOT_TOKEN
      • GOOGLE_MAPS_API_KEY
      • FIREBASE_SERVICE_ACCOUNT_KEY (JSON content)
      • NEXT_PUBLIC_FIREBASE_API_KEY
      • NEXT_PUBLIC_FIREBASE_AUTH_DOMAIN
      • NEXT_PUBLIC_FIREBASE_PROJECT_ID

    Option B: Manual Deployment

    # Deploy everything
    firebase deploy
    
    # Deploy only functions
    firebase deploy --only functions
    
    # Deploy only dashboard
    firebase deploy --only hosting

πŸ” Granting Admin Access

To access the dashboard, your user account must have the admin custom claim.

  1. Generate Service Account Key:

    • Go to Firebase Console -> Project Settings -> Service accounts.
    • Generate new private key.
    • Save as functions/service-account.json.
  2. Run the Script:

    cd functions
    export GOOGLE_APPLICATION_CREDENTIALS="./service-account.json"
    node set-admin.js your-email@example.com
  3. Sign In: Log out and log back in to the dashboard to refresh your token.

Configure Production Webhook

After deployment, set the webhook to your production URL:

curl -X POST "https://api.telegram.org/bot<YOUR_TOKEN>/setWebhook" \
  -H "Content-Type: application/json" \
  -d '{"url": "https://us-central1-your-project.cloudfunctions.net/telegramWebhook"}'

πŸ“Š YTD Calculation Methodology

The bot calculates Year-to-Date performance using the correct Yahoo Finance methodology:

YTD % = ((Current Price - Year Start Price) / Year Start Price) Γ— 100

Year Start Price = Close price of the first trading day of the year (typically Jan 2nd)

This matches the official YTD values displayed on Yahoo Finance.


πŸ› οΈ Available Scripts

Script Description
npm run build Compile TypeScript to JavaScript
npm run build:watch Watch mode for development
npm run serve Build and start Firebase emulator
npm run deploy Deploy to Firebase
npm run logs View Firebase function logs

🀝 Contributing

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'feat: Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

πŸ“„ License

This project is licensed under the ISC License.


πŸ™ Acknowledgments


Made with ❀️ by iRedlof Team

About

Telegram Bot on Firebase (Google Cloud)

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors