Skip to content

Latest commit

Β 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Crypto Hub Bot β€” High-On-Chain Ops πŸš€

Telegram channel automation + bot that publishes crypto market updates, on-chain alpha, mobile-money opportunities, and drives traffic to crypto.loopnet.tech.

Tech Stack: Node.js (Telegraf), MongoDB (Mongoose), node-cron, Gemini AI, Express
Timezone Support: Europe/London (with DST handling)
Tone: Hacker / High-energy / Mobile-first


πŸ“‹ Table of Contents

  1. Overview
  2. Quick Start
  3. Project Structure
  4. Environment Variables
  5. Bot Commands
  6. Scheduler & Channel Management
  7. Payment Integrations
  8. Gemini AI Usage
  9. API Endpoints
  10. Documentation
  11. Deployment
  12. Testing
  13. Troubleshooting

🎯 Overview

Crypto Hub Bot automates publishing crypto market updates, alerts, memes, and mobile-money CTAs to a Telegram channel. Key features:

βœ… Persistent schedule management β€” Create/list/pause/resume jobs stored in MongoDB
βœ… Timezone-aware scheduling β€” Europe/London with automatic DST handling
βœ… Gemini AI content generation β€” Dynamic market summaries and alerts
βœ… Public crypto APIs β€” CoinGecko price feeds with caching
βœ… Mobile money integrations β€” M-Pesa (Kenya), Airtel Money (Uganda/Malawi)
βœ… Crypto deposits β€” USDT/BTC addresses from environment
βœ… Admin management β€” Broadcasts, scheduled posts, dispute resolution
βœ… Analytics tracking β€” Message views, clicks, reactions
βœ… Retry/backoff logic β€” Resilient channel posting with exponential backoff


πŸš€ Quick Start

Prerequisites

  • Node.js 20+
  • MongoDB (local or Atlas)
  • Telegram Bot Token (create via @BotFather)
  • Telegram Channel (bot must be admin)

Installation

# 1. Clone repository
git clone <repo-url>
cd crypto-hub-bot

# 2. Install dependencies
npm install

# 3. Configure environment
cp .env.example .env
# Edit .env with your credentials

# 4. Start development server
npm run dev

Verify Setup

# Check bot is running
curl http://localhost:3000/api/health

# Test Telegram bot
# Send /start to your bot in Telegram

πŸ“ Project Structure

src/
β”œβ”€β”€ bot/
β”‚   β”œβ”€β”€ admin.js              # Admin commands (schedule management)
β”‚   └── commands.js           # User commands (/start, /deposit, /prices)
β”œβ”€β”€ cron/
β”‚   β”œβ”€β”€ channelScheduler.js   # DB-backed persistent scheduler
β”‚   └── scheduler.js          # Simple cron jobs (price caching)
β”œβ”€β”€ services/
β”‚   β”œβ”€β”€ geminiClient.js       # Gemini AI wrapper
β”‚   β”œβ”€β”€ priceFetcher.js       # CoinGecko API client
β”‚   β”œβ”€β”€ channelManager.js     # Channel posting + analytics
β”‚   β”œβ”€β”€ telegramBot.js        # Bot initialization
β”‚   β”œβ”€β”€ analytics.js          # Analytics tracking
β”‚   └── payments.js           # Payment helpers (placeholder)
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ User.js               # User accounts
β”‚   β”œβ”€β”€ ChannelMessage.js     # Posted messages + analytics
β”‚   β”œβ”€β”€ ScheduledJob.js       # Cron job definitions
β”‚   β”œβ”€β”€ Transaction.js        # Payment records
β”‚   β”œβ”€β”€ Subscription.js       # User subscriptions
β”‚   β”œβ”€β”€ Alert.js              # Price alerts
β”‚   └── PriceCache.js         # Cached price data
β”œβ”€β”€ routes/
β”‚   └── api.js                # REST API endpoints
β”œβ”€β”€ utils/
β”‚   └── paymentContacts.js    # Mobile money contact helper
β”œβ”€β”€ config.js                 # Environment configuration
β”œβ”€β”€ server.js                 # Express server
└── index.js                  # Application entry point

docs/                         # Comprehensive documentation (11 guides)
__tests__/                    # Jest test suite

βš™οΈ Environment Variables

Create .env file (never commit to git):

# === Core ===
NODE_ENV=development
PORT=3000
BASE_URL=https://crypto.loopnet.tech

# === Database ===
MONGO_URI=mongodb://localhost:27017/crypto_hub
# Or MongoDB Atlas:
# MONGO_URI=mongodb+srv://user:pass@cluster.mongodb.net/crypto_hub

# === Telegram ===
TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11
TELEGRAM_CHANNEL_ID=-1001234567890
ADMIN_TELEGRAM_ID=123456789

# === Gemini AI ===
GEMINI_API_KEY=AIzaSy...
GEMINI_MODEL=gemini-2.0-flash
GEMINI_TEMPERATURE=0.8
GEMINI_MAX_TOKENS=500

# === Crypto Addresses (public) ===
CRYPTO_USDT_ADDRESS=0xYourTetherUSDTAddressHere
CRYPTO_BTC_ADDRESS=bc1qyourbtcaddresshere

# === Mobile Money (E.164 format, no +) ===
MOBILE_MPESA_KE=254XXXXXXXXX
MOBILE_AIRTEL_UG=256XXXXXXXXX
MOBILE_AIRTEL_MW=265XXXXXXXXX
DEFAULT_PAYMENT_COUNTRY=KE

# === M-Pesa Daraja (optional - for STK Push) ===
MPESA_CONSUMER_KEY=your_consumer_key
MPESA_CONSUMER_SECRET=your_consumer_secret
MPESA_SHORTCODE=174379
MPESA_PASSKEY=your_passkey
MPESA_ENVIRONMENT=sandbox
MPESA_CALLBACK_URL=https://yourdomain.com/api/webhook/mpesa/callback

# === Airtel Money (optional) ===
AIRTEL_CLIENT_ID=your_client_id
AIRTEL_CLIENT_SECRET=your_client_secret
AIRTEL_ENVIRONMENT=staging

See .env.example for complete reference.


πŸ€– Bot Commands

User Commands

Command Description
/start Welcome message & signup CTA
/help Show available commands
/prices Latest crypto prices (BTC, ETH, BNB, SOL, ADA)
/deposit [country] Show crypto addresses & mobile money number
/confirm_deposit <amount> Confirm payment (for reconciliation)
/alerts View active price alerts
/subscribe <ticker> <price> Set price alert

Admin Commands (requires ADMIN_TELEGRAM_ID)

Command Description
/job_create Name || cron || type || content Create scheduled job
/job_list List all scheduled jobs
/job_pause <jobId> Pause a job
/job_resume <jobId> Resume paused job
/job_reschedule <jobId> || <newCron> Update job schedule
/job_run <jobId> Force-run job immediately
/broadcast <message> Send message to channel
/pin <messageId> Pin message in channel
/show_config Display configured addresses
/seed_jobs Seed all automation blueprint jobs
/clear_jobs Clear all jobs (requires confirm)

Job Creation Examples

Daily morning alpha (9 AM London time):

/job_create MorningAlpha || 0 9 * * * || alpha || gemini:Write a hacker-style alpha for BTC and ETH

Quick market update (every 15 minutes):

/job_create QuickUpdate || */15 * * * * || update || gemini:QUICK_UPDATE

Daily digest (6 PM London time):

/job_create EveningDigest || 0 18 * * * || digest || gemini:DAILY_DIGEST

⏰ Scheduler & Channel Management

πŸš€ Quick Start: Automated Content Blueprint

Seed 13 pre-configured jobs in one command:

/seed_jobs

This creates:

  • βœ… 5-min marketing messages (drive signups)
  • βœ… 5-min strategy tips (educate users)
  • βœ… 10-min whale alerts (real-time on-chain data)
  • βœ… 15-min trending coins (CoinGecko hot list)
  • βœ… 30-min top movers (gainers/losers)
  • βœ… Hourly market alpha (AI-generated insights)
  • βœ… 3-hour motivation posts (inspire action)
  • βœ… Daily greetings (morning/afternoon/night)
  • βœ… Daily digest (complete market summary)

See full blueprint: docs/12-CHANNEL-AUTOMATION-BLUEPRINT.md

How It Works

  1. Persistent Storage β€” Jobs stored in MongoDB (ScheduledJob model)
  2. Timezone-Aware β€” Uses cron library with Europe/London timezone (handles DST automatically)
  3. Dynamic Loading β€” On startup, loads all enabled jobs from DB
  4. Content Rotation β€” Automatically rotates through 30+ pre-written templates
  5. API Integration β€” Fetches live data from CoinGecko + Etherscan
  6. AI Enhancement β€” Uses Gemini for dynamic content generation
  7. Admin Control β€” Create/pause/resume/reschedule via Telegram commands

ScheduledJob Payload

{
  name: "MorningAlpha",
  cron: "0 9 * * *",
  timezone: "Europe/London",
  channelId: "-1001234567890",
  enabled: true,
  payload: {
    type: "alpha",           // alpha, update, digest, promo
    geminiPrompt: "...",     // AI-generated content
    content: "...",          // OR static content
    appendCTA: true          // Add CTA + disclaimer
  },
  retryPolicy: {
    retries: 2,
    backoffSec: 30
  }
}

Channel Posting Pipeline

  1. Generate Content β€” Static text or Gemini AI call
  2. Append CTA β€” Add link to https://crypto.loopnet.tech
  3. Post with Retry β€” channelManager.postToChannel() with exponential backoff
  4. Log Analytics β€” Store ChannelMessage record for tracking

πŸ’° Payment Integrations

Crypto Deposits

Addresses configured in .env:

  • USDT: ERC-20 or TRC-20 address
  • BTC: Native SegWit (bc1...) recommended

User Flow:

  1. User sends /deposit
  2. Bot displays addresses with instructions
  3. User sends crypto and uses /confirm_deposit <amount> <txid>
  4. Admin manually verifies transaction

Future Enhancement: Implement automated verification via Etherscan/Blockchain.info APIs.

M-Pesa (Kenya)

Integration Type: Daraja API (STK Push)

Flow:

  1. User initiates payment via bot command
  2. Backend calls STK Push API
  3. User receives M-Pesa prompt on phone
  4. User enters PIN
  5. Daraja sends callback to webhook
  6. System updates Transaction status

Documentation: See docs/05-PAYMENT-INTEGRATION.md

Airtel Money (Uganda/Malawi)

Integration Type: Collections API

Flow:

  1. User provides phone number
  2. Backend initiates collection request
  3. User receives payment prompt
  4. User approves transaction
  5. Webhook confirms payment
  6. System updates Transaction status

Documentation: See docs/05-PAYMENT-INTEGRATION.md


πŸ€– Gemini AI Usage

Configuration

Set in .env:

GEMINI_API_KEY=your_key
GEMINI_MODEL=gemini-2.0-flash  
GEMINI_TEMPERATURE=0.7
GEMINI_MAX_TOKENS=500

Example Prompts

Hacker-style alpha:

await generateOneLineSummary({
  btc: { usd: 50000, change_24h: 2.5 },
  eth: { usd: 3000, change_24h: -1.2 }
});
// Output: "Bitcoin surges past $50K as bulls dominate the market."

Daily digest:

await generateDailyDigest(priceData);
// Output: Professional 3-4 sentence market summary

Best Practices

βœ… Cache AI responses for repeated prompts
βœ… Limit token length (cost optimization)
βœ… Always have fallback content for API failures
βœ… Monitor token usage and costs
βœ… Test prompts iteratively for quality

Documentation: See docs/06-GEMINI-AI.md


🌐 API Endpoints

Public Endpoints

GET  /api/health          # Health check
GET  /api/prices          # Latest crypto prices
POST /api/subscribe       # Create subscription

Webhook Endpoints (secure in production)

POST /api/webhook/mpesa/callback       # M-Pesa STK callback
POST /api/webhook/mpesa/validation     # M-Pesa C2B validation
POST /api/webhook/mpesa/confirmation   # M-Pesa C2B confirmation
POST /api/webhook/airtel/callback      # Airtel payment callback

Admin Endpoints (add authentication)

GET  /api/admin/jobs           # List scheduled jobs
POST /api/admin/jobs           # Create job
PUT  /api/admin/jobs/:id       # Update job
DELETE /api/admin/jobs/:id     # Delete job

πŸ“š Documentation

Comprehensive guides in docs/ directory:

  1. 00-OVERVIEW.md β€” Project vision & navigation
  2. 01-SETUP.md β€” Local development setup
  3. 02-ARCHITECTURE.md β€” System design
  4. 03-API-REFERENCE.md β€” Complete API reference
  5. 04-SCHEDULER-GUIDE.md β€” Cron job management
  6. 05-PAYMENT-INTEGRATION.md β€” M-Pesa, Airtel, crypto
  7. 06-GEMINI-AI.md β€” AI content generation
  8. 07-DEPLOYMENT.md β€” PM2, Docker, Kubernetes
  9. 08-OPERATIONS.md β€” Monitoring & troubleshooting
  10. 09-ROADMAP.md β€” 24-week implementation plan
  11. 10-SECURITY.md β€” Security best practices
  12. 11-TESTING.md β€” Testing guide with Jest

🚒 Deployment

Option 1: PM2 (Simple VPS)

# Install PM2
npm install -g pm2

# Start application
pm2 start src/index.js --name crypto-hub-bot

# Save configuration
pm2 save
pm2 startup

Option 2: Docker

# Build image
docker build -t crypto-hub-bot .

# Run container
docker run -d \
  --name crypto-hub-bot \
  --env-file .env \
  -p 3000:3000 \
  crypto-hub-bot

Option 3: Docker Compose

docker-compose up -d

Option 4: Kubernetes

See docs/07-DEPLOYMENT.md for complete Kubernetes manifests.


πŸ§ͺ Testing

Run Tests

# Install test dependencies
npm install --save-dev jest supertest mongodb-memory-server nock @jest/globals

# Run all tests
npm test

# Watch mode
npm run test:watch

# Coverage report
npm run test:coverage

Test Structure

__tests__/
β”œβ”€β”€ setup.js                      # MongoDB Memory Server setup
β”œβ”€β”€ models/
β”‚   β”œβ”€β”€ User.test.js
β”‚   └── Transaction.test.js
β”œβ”€β”€ services/
β”‚   └── priceFetcher.test.js
└── utils/
    └── paymentContacts.test.js

Documentation: See docs/11-TESTING.md


πŸ”§ Troubleshooting

Bot Not Responding

Check:

  1. TELEGRAM_BOT_TOKEN is correct
  2. Bot is admin in channel
  3. MongoDB connection successful
# Test bot connection
curl https://api.telegram.org/bot<TOKEN>/getMe

# Check logs
pm2 logs crypto-hub-bot

Jobs Not Running

Check:

  1. Job is enabled (ScheduledJob.enabled = true)
  2. Cron expression is valid
  3. Timezone is set to Europe/London
# List jobs via admin command
/job_list

# Force run to test
/job_run <jobId>

Payment Webhook Not Received

Check:

  1. Webhook URL is HTTPS
  2. Port 443 is open
  3. URL is registered with payment provider
  4. Server responds with 200 status quickly
# Test webhook endpoint
curl -X POST https://yourdomain.com/api/webhook/mpesa/callback \
  -H "Content-Type: application/json" \
  -d '{"test":"data"}'

More troubleshooting: See docs/08-OPERATIONS.md


πŸ›£οΈ Roadmap

Phase 1: MVP (Weeks 1-8)

  • βœ… Bot with basic commands
  • βœ… Channel automation
  • βœ… Price fetching
  • βœ… Admin commands
  • βœ… Payment integration setup

Phase 2: Growth (Weeks 9-16)

  • Per-user crypto addresses
  • Automated payment verification
  • Analytics dashboard
  • Redis caching & locks
  • Advanced AI prompts

Phase 3: Enterprise (Weeks 17-24)

  • React admin dashboard
  • Multi-channel support
  • Advanced analytics
  • Kubernetes deployment
  • Revenue optimization

Full roadmap: See docs/09-ROADMAP.md


πŸ”’ Security

⚠️ Important Security Notes:

  • Never commit .env to git
  • Use environment variables for all secrets
  • Rotate API keys regularly
  • Validate all webhook payloads
  • Implement rate limiting on API endpoints
  • Use HTTPS for all webhook URLs
  • Add authentication to admin endpoints

Full security guide: See docs/10-SECURITY.md


πŸ“„ License

MIT License - see LICENSE file for details


🀝 Contributing

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

πŸ“ž Support


🎯 Quick Commands Cheat Sheet

# Development
npm run dev                    # Start with hot reload
npm test                       # Run tests
npm run test:coverage          # Generate coverage report

# Production
npm start                      # Start application
pm2 start src/index.js         # Start with PM2
docker-compose up -d           # Start with Docker

# Admin (via Telegram)
/job_create                    # Create scheduled job
/job_list                      # View all jobs
/broadcast <msg>               # Send to channel
/show_config                   # View configuration

Built with ❀️ for the crypto community

πŸ”— crypto.loopnet.tech

About

Crypto Hub Bot is a Telegram-based cryptocurrency intelligence and trading signal platform that delivers: - Real-time price alerts and market signals - AI-generated daily digests and research - Multi-channel content distribution (Telegram channel + private bot)

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages