Skip to content

🚀 release: v0.1.0-beta #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Jun 19, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ build/Release
node_modules/
jspm_packages/

# Prevent npm lock file (we use Yarn)
package-lock.json

# TypeScript cache
*.tsbuildinfo

Expand Down
9 changes: 9 additions & 0 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# Force using Yarn instead of npm
# This file will cause npm commands to fail with an error
engine-strict=true

# Prevent npm from creating package-lock.json
package-lock=false

# Show a helpful error message
save-exact=true
11 changes: 11 additions & 0 deletions .yarnrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Yarn configuration
# This ensures consistent behavior across environments

# Use exact versions (no semver ranges)
save-exact true

# Disable emoji in output (better for logs)
emoji false

# Use network timeout for slow connections
network-timeout 300000
56 changes: 50 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

The Unthread Telegram Bot seamlessly connects your Telegram community with Unthread's powerful ticket management system. This official integration transforms how you handle support requests by enabling users to create and manage tickets directly within Telegram.

With simple commands and intuitive interactions, support tickets automatically sync between both platforms, streamlining your workflow and improving response times. Whether you're managing a community group, running a business chat, or supporting an open-source project, this bot provides the tools you need for efficient, organized customer support.
With simple commands and intuitive interactions, support tickets automatically sync between both platforms, streamlining your workflow and improving response times. Users receive real-time notifications when ticket status changes, ensuring they stay informed throughout the support process. Whether you're managing a community group, running a business chat, or supporting an open-source project, this bot provides the tools you need for efficient, organized customer support.

## 💸 Sponsored Ads

Expand All @@ -19,22 +19,27 @@ Open source development is resource-intensive. These **sponsored ads help keep L
The Unthread Telegram Bot creates a seamless bridge between your Telegram group chats and Unthread's ticket management system. Here's how it works:

### **📥 Ticket Creation**

- Users in group chats can create support tickets using the `/support` command
- The bot guides them through a simple conversation to collect issue summary and email (optional)
- Tickets are automatically created in Unthread with proper customer and user association

### **🔄 Bidirectional Communication**
### **🔄 Bidirectional Communication**

- **Agent → User**: When agents respond via the Unthread dashboard, messages are delivered to Telegram in real-time through webhook processing
- **User → Agent**: Users can simply reply to agent messages naturally - no special commands needed
- **Status Notifications**: Receive real-time notifications when ticket status changes (Open/Closed) with clear messaging and emoji indicators
- **Conversation Flow**: Maintains complete conversation history across both platforms using message reply chains
- **Webhook Server**: Powered by [`wgtechlabs/unthread-webhook-server`](https://github.com/wgtechlabs/unthread-webhook-server) which processes Unthread webhooks and queues events in Redis for real-time delivery

### **🏢 Smart Customer Management**

- Automatically extracts customer company names from group chat titles (e.g., "Company X Relay" → "Company X")
- Creates customers in Unthread with `[Telegram]` prefix for platform identification
- Maps Telegram users to Unthread user profiles with fallback email generation

### **💾 Multi-Layer Storage**

- **Memory Layer** (24h): Fast access for active conversations
- **Redis Layer** (3 days): Intermediate caching for recent activity
- **PostgreSQL** (permanent): Long-term storage with full conversation history
Expand All @@ -44,7 +49,8 @@ The Unthread Telegram Bot creates a seamless bridge between your Telegram group
This bot works in conjunction with the [`wgtechlabs/unthread-webhook-server`](https://github.com/wgtechlabs/unthread-webhook-server) to enable real-time bidirectional communication. Here's how the complete system works:

### **🏗️ System Architecture**
```

```text
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐
│ Unthread │ │ Webhook │ │ Redis │ │ Telegram │
│ Dashboard │───▶│ Server │───▶│ Queue │───▶│ Bot │
Expand All @@ -55,13 +61,16 @@ This bot works in conjunction with the [`wgtechlabs/unthread-webhook-server`](ht
```

### **🔄 Event Flow**

1. **Agent responds** in Unthread dashboard to a ticket
2. **Unthread webhook** fires and sends event to the webhook server
3. **Webhook server** processes the event and queues it in Redis with proper formatting
4. **Telegram bot** polls the Redis queue and delivers the message to the appropriate group chat
5. **User replies** in Telegram, and the bot sends it back to Unthread API
6. **Status changes** (ticket closed/reopened) trigger real-time notifications to users

### **⚙️ Configuration Requirements**

- **Webhook Server**: Must be deployed separately to receive Unthread webhooks
- **Shared Redis**: Both webhook server and bot must use the same Redis instance
- **Queue Names**: Both webhook server and bot use the standard queue name `unthread-events`
Expand All @@ -71,37 +80,45 @@ For webhook server setup instructions, see the [`wgtechlabs/unthread-webhook-ser
## ✨ Key Features

### **🎫 Seamless Ticket Management**

- Create support tickets directly from Telegram group chats with `/support` command
- Interactive ticket creation with guided prompts for summary and email
- Automatic ticket numbering and confirmation messages
- Smart customer extraction from group chat names

### **💬 Real-Time Bidirectional Communication**

- Agent responses from Unthread dashboard delivered instantly to Telegram
- Users reply naturally to agent messages without special commands
- Complete conversation history maintained across both platforms
- Message reply chains preserve conversation context
- **Status Notifications**: Real-time alerts when tickets are opened or closed with emoji-rich formatting
- **Reaction-Based Feedback**: User messages are reacted to with ⏳ (sending) → ✅ (sent) or ❌ (error) for clean, non-intrusive status updates

### **🏢 Enterprise-Ready Customer Management**

- Automatic customer creation with `[Telegram]` platform identification
- Smart company name extraction from group chat titles (e.g., "Acme Corp x Support" → "Acme Corp")
- User profile mapping with automatic fallback email generation
- Duplicate prevention for customers and users

### **🚀 Production-Grade Architecture**

- Multi-layer storage: Memory (24h) → Redis (3d) → PostgreSQL (permanent)
- Webhook-based real-time event processing from Unthread via [`wgtechlabs/unthread-webhook-server`](https://github.com/wgtechlabs/unthread-webhook-server)
- Redis queue system for reliable webhook event processing and delivery
- Graceful degradation when services are unavailable
- Comprehensive error handling and recovery mechanisms

### **⚡ Developer Experience**

- Built with modern ES6+ modules and async/await patterns
- Structured logging with `@wgtechlabs/log-engine` integration
- Auto-setup database schema on first run
- Clean separation of concerns with SDK architecture

### **🔧 Flexible Configuration**

- Environment variable based configuration
- Support for both basic mode (ticket creation only) and full mode (with webhooks)
- Configurable webhook polling intervals and queue names
Expand Down Expand Up @@ -162,6 +179,7 @@ That's it! The database schema will be created automatically on first run.
[![Deploy on Railway](https://railway.app/button.svg)](https://railway.com/u/warengonzaga)

#### **🐳 Docker Support**

```bash
# Coming soon - Docker deployment support
docker-compose up -d
Expand All @@ -181,6 +199,7 @@ docker-compose up -d
The bot provides several commands for users and administrators:

#### **User Commands**

- `/start` - Welcome message and bot introduction
- `/help` - Display available commands and usage instructions
- `/support` - Create a new support ticket (group chats only)
Expand All @@ -193,7 +212,7 @@ The bot provides several commands for users and administrators:
3. **Email (Optional)**: Provide email or skip for auto-generated one
4. **Confirmation**: Receive ticket number and confirmation message

```
```text
User: /support
Bot: Let's create a support ticket. Please provide your issue summary:

Expand All @@ -209,40 +228,50 @@ Bot: 🎫 Support Ticket Created Successfully!
### **Agent Workflow**

#### **Receiving Tickets**

- New tickets appear in your Unthread dashboard
- Customer name shows as `[Telegram] GroupChatName`
- User information includes Telegram username and ID

#### **Responding to Users**

- Reply to tickets in Unthread dashboard as normal
- Messages are automatically delivered to the original Telegram group
- Users receive agent responses in real-time

#### **Ongoing Conversations**

- Users can reply directly to agent messages in Telegram
- No special commands needed - natural conversation flow
- All replies are automatically sent back to Unthread
- **Status Updates**: Users receive real-time notifications when tickets are closed (🔒) or reopened (📂)
- **Reply Status**: Message reactions show reply status (⏳ sending → ✅ sent successfully / ❌ error)
- Status notifications include clear messaging about next steps and reply to original ticket messages

### **Group Chat Setup**

#### **Adding the Bot**

1. Add your bot to the desired Telegram group chat
2. Ensure the bot has permission to read and send messages
3. Group chat title should ideally include customer company name

#### **Best Practices**

- Use descriptive group chat names (e.g., "Acme Corp Support", "ClientName x YourCompany")
- The bot automatically extracts customer names from chat titles
- Only group members can create support tickets (private chats are blocked)

### **Admin Features**

#### **Customer Management**

- Customers are automatically created from group chat names
- Duplicate prevention ensures one customer per chat
- Customer names are prefixed with `[Telegram]` for easy identification

#### **Conversation Tracking**

- Each ticket maintains complete conversation history
- Reply chains preserve context across platforms
- Message metadata includes user information and timestamps
Expand All @@ -256,32 +285,39 @@ Bot: 🎫 Support Ticket Created Successfully!
- **PostgreSQL 12+** (primary database)
- **Redis 6+** (optional, for enhanced performance)

> **⚠️ Package Manager Notice:** This project enforces the use of Yarn and will prevent npm installation attempts. If you try to use `npm install`, you'll receive an error message with instructions to use Yarn instead.

### **Step-by-Step Installation**

#### **1. Clone Repository**

```bash
git clone https://github.com/wgtechlabs/unthread-telegram-bot.git
cd unthread-telegram-bot
```

#### **2. Install Dependencies**

```bash
# Use Yarn only (npm not supported)
yarn install
```

#### **3. Create Telegram Bot**

1. Message [@BotFather](https://t.me/botfather) on Telegram
2. Create new bot with `/newbot` command
3. Save the bot token for environment configuration

#### **4. Setup Unthread Integration**

1. Log into your Unthread dashboard
2. Navigate to Settings → API Keys
3. Generate a new API key
4. Find your channel ID in the dashboard URL

#### **5. Database Setup**

```bash
# PostgreSQL (required)
createdb unthread_telegram_bot
Expand All @@ -291,6 +327,7 @@ createdb unthread_telegram_bot
```

#### **6. Environment Configuration**

```bash
# Copy example environment file
cp .env.example .env
Expand All @@ -300,6 +337,7 @@ nano .env
```

Required environment variables:

```bash
TELEGRAM_BOT_TOKEN=your_bot_token_from_botfather
POSTGRES_URL=postgresql://user:password@localhost:5432/unthread_telegram_bot
Expand All @@ -308,6 +346,7 @@ UNTHREAD_CHANNEL_ID=your_unthread_channel_id
```

Optional environment variables:

```bash
WEBHOOK_REDIS_URL=redis://localhost:6379
PLATFORM_REDIS_URL=redis://localhost:6379
Expand All @@ -316,6 +355,7 @@ WEBHOOK_POLL_INTERVAL=1000
```

#### **7. Start the Bot**

```bash
# Development mode (with auto-restart)
yarn dev
Expand All @@ -327,8 +367,10 @@ yarn start
### **Verification**

#### **Check Bot Status**

1. Look for successful startup logs:
```

```text
[INFO] Database initialized successfully
[INFO] BotsStore initialized successfully
[INFO] Bot initialized successfully
Expand All @@ -343,12 +385,14 @@ yarn start
#### **Troubleshooting**

**Common Issues:**

- **Import errors**: Ensure you're using Yarn, not npm
- **Database connection**: Verify PostgreSQL is running and connection string is correct
- **Bot not responding**: Check bot token and ensure bot is added to group with proper permissions
- **Webhook issues**: Verify Redis connection if using webhook features

**Debug Mode:**

```bash
# Enable detailed logging
NODE_ENV=development yarn start
Expand All @@ -359,7 +403,7 @@ NODE_ENV=development yarn start
Join our community discussions to get help, share ideas, and connect with other users:

- 📣 **[Announcements](https://github.com/wgtechlabs/unthread-telegram-bot/discussions/categories/announcements)**: Official updates from the maintainer
- 📸 **[Showcase](https://github.com/wgtechlabs/unthread-telegram-bot/discussions/categories/showcase)**: Show and tell your implementation
- 📸 **[Showcase](https://github.com/wgtechlabs/unthread-telegram-bot/discussions/categories/showcase)**: Show and tell your implementation
- 💖 **[Wall of Love](https://github.com/wgtechlabs/unthread-telegram-bot/discussions/categories/wall-of-love)**: Share your experience with the bot
- 🛟 **[Help & Support](https://github.com/wgtechlabs/unthread-telegram-bot/discussions/categories/help-support)**: Get assistance from the community
- 🧠 **[Ideas](https://github.com/wgtechlabs/unthread-telegram-bot/discussions/categories/ideas)**: Suggest new features and improvements
Expand Down
27 changes: 19 additions & 8 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,34 +1,45 @@
{
"name": "unthread-telegram-bot",
"version": "0.1.0-alpha",
"version": "0.1.0-beta",
"description": "A Telegram bot integrated with Unthread API featuring enhanced logging with @wgtechlabs/log-engine",
"main": "src/index.js",
"main": "dist/index.js",
"type": "module",
"private": true,
"engines": {
"node": ">=20.0.0",
"yarn": ">=1.22.22"
},
"packageManager": "[email protected]",
"scripts": {
"start": "node src/index.js",
"dev": "nodemon src/index.js"
"preinstall": "npx only-allow yarn",
"build": "tsc",
"start": "node dist/index.js",
"dev": "nodemon --exec 'npm run build && npm start' src/index.ts",
"dev:watch": "concurrently \"tsc --watch\" \"nodemon dist/index.js\"",
"clean": "rm -rf dist"
},
"dependencies": {
"@wgtechlabs/log-engine": "^1.2.1",
"@wgtechlabs/log-engine": "^1.3.0",
"dotenv": "^16.4.7",
"node-fetch": "^3.3.2",
"pg": "^8.16.0",
"redis": "^5.1.1",
"telegraf": "^4.0.0"
},
"devDependencies": {
"nodemon": "^3.1.9"
"@types/node": "24.0.3",
"@types/pg": "8.15.4",
"concurrently": "9.1.2",
"nodemon": "^3.1.9",
"typescript": "5.8.3"
},
"keywords": [
"telegram",
"bot"
],
"author": "Waren Gonzaga <[email protected]> (https://warengonzaga.com)",
"license": "AGPL-3.0-only",
"packageManager": "[email protected]"
"contributors": [
"WG Tech Labs <[email protected]> (https://wgtechlabs.com)"
],
"license": "AGPL-3.0-only"
}
Loading