Skip to content

Incept5/embabel-telegram-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

57 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

Telegram Bot Agent

Build

Kotlin Spring Apache Maven ChatGPT


A Telegram bot built with the Embabel framework

Built with Spring Boot 3.5.9, Embabel 0.3.1, and MySQL.

Setup

Prerequisites

  1. A Telegram bot token and chat ID (see setup instructions below)
  2. MySQL database (for survey functionality)

Database Setup

  1. Create a MySQL database:
CREATE DATABASE telegram_bot_db;
  1. Configure database credentials in src/main/resources/application.properties:
spring.datasource.username=your_db_user
spring.datasource.password=your_db_password

Or set via environment variables:

export DB_USERNAME=your_db_user
export DB_PASSWORD=your_db_password

The database tables will be created automatically on first run.

Telegram Configuration

1. Create a Telegram Bot

  1. Open Telegram and search for @BotFather
  2. Send /newbot and follow the instructions to create a bot
  3. Copy the bot token provided by BotFather

2. Configure the Bot Token

Set your bot token via environment variable:

export TELEGRAM_BOT_TOKEN="your_bot_token_here"

Or edit src/main/resources/application.properties:

telegram.bot.token=your_bot_token_here

3. Get Your Chat ID

To find your chat ID (needed for sending surveys):

  1. Start a conversation with your bot in Telegram
  2. Send any message to the bot
  3. Visit: https://api.telegram.org/bot<YOUR_BOT_TOKEN>/getUpdates
  4. Look for "chat":{"id":...} in the response - this is your chat ID

Note:

  • Individual chat IDs are positive numbers (e.g., 8360446449)
  • Group chat IDs are negative numbers (e.g., -123456789)

Troubleshooting

"Failed to send message: Forbidden"

  • The bot doesn't have permission. User must start a conversation with the bot first and send at least one message.

"Failed to send message: Bad Request: chat not found"

  • The chat ID is incorrect. Double-check using the getUpdates API endpoint above.

Running

Start the Embabel Spring Shell:

./scripts/shell.sh

Or use Maven directly:

mvn clean spring-boot:run

Usage

Survey Collection

Ask questions and collect responses from Telegram users:

# Ask one person
x "Ask user 8360446449 what their favourite colour is"

# Ask multiple people in a group
x "Ask 5 users in group -123456789 what their favorite food is"

# Survey with specific count
x "Survey 3 users in chat -987654321 about their preferred programming language"

How it works:

  1. Survey question is sent to the specified chat
  2. Users respond in Telegram with their answers
  3. Responses are automatically collected and stored
  4. When all expected responses are received, a summary is displayed in the shell:
================================================================================
πŸ“Š SURVEY COMPLETE - ID: 2
================================================================================
Question: What is your favourite colour?

Responses (3/3):
1. Alice: Blue
2. Bob: Red
3. Charlie: Green
================================================================================

How It Works

The bot uses two specialized agents that handle different parts of the survey workflow:

SurveyInitiationAgent

Handles survey creation and initiation:

  • Understands natural language survey requests
  • Extracts chat ID, question, and expected response count using AI
  • Creates survey records in the database
  • Sends the survey question to Telegram
  • Returns a SurveyInitiated object with the survey details

Keywords: ask, question, survey, poll, create, send

SurveyResultsAgent

Handles survey completion and results processing:

  • Triggered when a user submits a survey response
  • Checks if the survey has received all expected responses
  • When complete, analyzes responses using AI to extract insights
  • Publishes formatted results back to Telegram
  • Marks the survey as completed in the database

Keywords: process, results, analyze, complete

Architecture

User Request (Natural Language)
    ↓
SurveyInitiationAgent
    β”œβ”€ Parse request with AI
    β”œβ”€ Create survey in database
    β”œβ”€ Send question via Telegram
    └─ Return SurveyInitiated
    ↓
[Users respond in Telegram]
    ↓
TelegramBotListener (receives responses)
    β”œβ”€ Store response in database
    └─ Trigger SurveyResultsAgent
    ↓
SurveyResultsAgent
    β”œβ”€ Check if survey is complete
    β”œβ”€ If complete: analyze responses with AI
    β”œβ”€ Generate insights summary
    └─ Publish results to Telegram

Database Schema

surveys

  • id (PK)
  • chatId
  • question
  • status (ACTIVE, COMPLETED, CANCELLED)
  • expectedCount
  • createdAt, completedAt
  • summary

survey_responses

  • id (PK)
  • surveyId (FK)
  • userId
  • userName
  • response
  • respondedAt

pending_response_changes

  • id (PK)
  • surveyId (FK)
  • userId
  • oldResponse
  • newResponse
  • requestedAt

Troubleshooting

Bot not receiving group messages

If the bot isn't receiving messages in group chats:

  1. Disable privacy mode via @BotFather:

    /setprivacy
    [Select your bot]
    Disable
    
  2. Remove bot from group and re-add it

  3. Alternatively, make the bot an admin (admins always receive all messages)

Survey not completing

  • Check that the correct number of unique users have responded
  • Each user can only respond once per survey
  • Verify responses are text messages (not photos, stickers, etc.)
  • Check logs for any errors

Development

Project Structure

src/main/kotlin/com/embabel/template/
β”œβ”€β”€ agent/
β”‚   β”œβ”€β”€ SurveyInitiationAgent.kt    # Creates and sends surveys
β”‚   └── SurveyResultsAgent.kt       # Processes responses and publishes results
β”œβ”€β”€ bot/
β”‚   └── TelegramBotListener.kt      # Receives Telegram updates
β”œβ”€β”€ domain/
β”‚   β”œβ”€β”€ SurveyCheckInput.kt         # Input for checking survey completion
β”‚   β”œβ”€β”€ SurveyInitiated.kt          # Survey initiation result
β”‚   └── SurveyResults.kt            # Survey results data
β”œβ”€β”€ entity/
β”‚   β”œβ”€β”€ PendingResponseChange.kt    # Pending response modifications
β”‚   β”œβ”€β”€ Survey.kt                   # Survey entity
β”‚   β”œβ”€β”€ SurveyResponse.kt           # Response entity
β”‚   └── SurveyStatus.kt             # Status enum
β”œβ”€β”€ repository/
β”‚   β”œβ”€β”€ PendingResponseChangeRepository.kt # Pending change data access
β”‚   β”œβ”€β”€ SurveyRepository.kt         # Survey data access
β”‚   └── SurveyResponseRepository.kt # Response data access
β”œβ”€β”€ service/
β”‚   └── SurveyService.kt            # Survey business logic
└── tools/
    └── TelegramTools.kt            # Telegram messaging

Building

mvn clean install

Testing

Ensure your database is running and configured, then:

mvn spring-boot:run

License

Apache License 2.0 - see LICENSE file for details.

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Contributors 7