DEV Community

guardlabs_team
guardlabs_team

Posted on Originally published at guardlabs.online

Add a Telegram Bot to Collect Customer Feedback and Ratings Automatically

Add a Telegram Bot to Collect Customer Feedback and Ratings Automatically

To automatically collect customer ratings and feedback through Telegram, you need a Telegram Bot token, a script to capture user inputs, and an integration (such as an API call or webhook) to trigger the survey after a customer interaction.

1. Create Your Telegram Bot

  • Open Telegram and search for @botfather.
  • Send /newbot and follow the prompts to set a name and username.
  • Copy the HTTP API access token provided upon creation.

2. Deploy the Feedback Collector Script

Install the required Python library:

pip install python-telegram-bot
Enter fullscreen mode Exit fullscreen mode

This script serves an inline 1–5 star rating keyboard, records the score, prompts for written comments, and saves the entry into an SQLite database.

import sqlite3
from telegram import InlineKeyboardButton, InlineKeyboardMarkup, Update
from telegram.ext import ApplicationBuilder, CallbackQueryHandler, CommandHandler, ContextTypes, MessageHandler, filters

# Setup SQLite DB
conn = sqlite3.connect('feedback.db', check_same_thread=False)
cursor = conn.cursor()
cursor.execute('''
    CREATE TABLE IF NOT EXISTS feedback (
        user_id INTEGER,
        rating INTEGER,
        comments TEXT
    )
''')
conn.commit()

TOKEN = "YOUR_BOT_TOKEN_HERE"

async def start_survey(update: Update, context: ContextTypes.DEFAULT_TYPE):
    keyboard = [[
        InlineKeyboardButton("1 ⭐", callback_data="rate_1"),
        InlineKeyboardButton("2 ⭐", callback_data="rate_2"),
        InlineKeyboardButton("3 ⭐", callback_data="rate_3"),
        InlineKeyboardButton("4 ⭐", callback_data="rate_4"),
        InlineKeyboardButton("5 ⭐", callback_data="rate_5")
    ]]
    reply_markup = InlineKeyboardMarkup(keyboard)
    await update.message.reply_text("How would you rate your recent experience?", reply_markup=reply_markup)

async def handle_rating(update: Update, context: ContextTypes.DEFAULT_TYPE):
    query = update.callback_query
    await query.answer()
    rating = int(query.data.split("_")[1])
    context.user_data['rating'] = rating
    await query.edit_message_text(f"You rated us {rating}/5. Please reply with any additional feedback:")

async def handle_comments(update: Update, context: ContextTypes.DEFAULT_TYPE):
    rating = context.user_data.get('rating')
    if rating:
        comments = update.message.text
        user_id = update.effective_user.id

        cursor.execute("INSERT INTO feedback (user_id, rating, comments) VALUES (?, ?, ?)", 
                       (user_id, rating, comments))
        conn.commit()

        context.user_data.clear()
        await update.message.reply_text("Thank you! Your feedback has been saved.")

if __name__ == '__main__':
    app = ApplicationBuilder().token(TOKEN).build()
    app.add_handler(CommandHandler("feedback", start_survey))
    app.add_handler(CallbackQueryHandler(handle_rating, pattern="^rate_"))
    app.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_comments))
    app.run_polling()

Enter fullscreen mode Exit fullscreen mode

3. Trigger Surveys Automatically via API

To request feedback automatically after a purchase or support resolution, send a direct HTTP POST request from your backend CRM or e-commerce platform to Telegram's API.

Endpoint:

https://api.telegram.org/bot<YOUR_BOT_TOKEN>/sendMessage
Enter fullscreen mode Exit fullscreen mode

JSON Payload:

{
  "chat_id": "CUSTOMER_TELEGRAM_ID",
  "text": "Please rate your recent order:",
  "reply_markup": {
    "inline_keyboard": [
      [
        {"text": "1 ⭐", "callback_data": "rate_1"},
        {"text": "2 ⭐", "callback_data": "rate_2"},
        {"text": "3 ⭐", "callback_data": "rate_3"},
        {"text": "4 ⭐", "callback_data": "rate_4"},
        {"text": "5 ⭐", "callback_data": "rate_5"}
      ]
    ]
  }
}
Enter fullscreen mode Exit fullscreen mode

4. Operational Considerations

  • Customer Mapping: Store the user's Telegram chat_id in your primary database during registration or checkout so you can target triggers correctly.
  • Rate Limits: Telegram limits broadcast messages to 30 requests per second. Queue outbound requests if processing large batches.
  • State Cleanup: Implement a cron job or scheduled task to clear stale user state sessions if a user leaves a survey incomplete.

Need this done fast? order a Telegram bot on FreelanceHunt (https://freelancehunt.com/freelancer/sspoisk.html).

Top comments (1)

Collapse
 
mohith_kumar_05846f3211f3 profile image
Mohith kumar •

Nice approach for audiences that already live in Telegram. The piece I'd add is a follow-up when the rating is low or the comment is two words, because "bad" alone can't be acted on. That follow-up logic is what I built chatform.in around, and the same pattern would fit your bot: one clarifying question, then store both answers.