Overview
This example demonstrates how to create conversational flows where your bot asks questions and waits for user responses.
Code
package examples
import (
"fmt"
"github.com/amarnathcjd/gogram/telegram"
)
const (
appID = 6
appHash = "YOUR_APP_HASH"
botToken = "YOUR_BOT_TOKEN"
)
func main() {
// Create a new client object
client, _ := telegram.NewClient(telegram.ClientConfig{
AppID: appID,
AppHash: appHash,
LogLevel: telegram.LogInfo,
})
// Authenticate as a bot
client.LoginBot(botToken)
// Add message handler with Ask() method
client.On("message", convEventHandler)
// Create a new conversation manually
conv, _ := client.NewConversation("username or id", false, 30) // 30 second timeout, false = not exclusive
defer conv.Close()
// Send initial message
_, err := conv.Respond("Hello, Please reply to this message")
if err != nil {
panic(err)
}
// Wait for user response
resp, err := conv.GetResponse() // Wait for any response
// resp, err := conv.GetReply() // Wait for reply to specific message
// conv.MarkRead() // Mark conversation as read
// conv.WaitEvent() // Wait for any custom update
if err != nil {
panic(err)
}
fmt.Println("response:", resp.Text())
}
// Handler that uses Ask() for simple conversations
func convEventHandler(m *telegram.NewMessage) error {
// Ask a question and wait for response
response, err := m.Ask("What's your name?")
if err != nil {
return err
}
// Reply with response
response.Reply("Nice to meet you, " + response.Text())
return nil
}
How It Works
- Ask Method:
m.Ask() sends a message and waits for user response
- Manual Conversation:
NewConversation() creates a conversation context
- Wait for Response:
GetResponse() blocks until user replies
- Timeout: Conversations automatically timeout after specified duration
- Close: Always
defer conv.Close() to clean up resources
Ask Method (Simple)
The easiest way to create conversations:
Basic Ask
Multiple Questions
client.On("message", func(m *telegram.NewMessage) error {
// Ask and wait for response
response, err := m.Ask("What's your favorite color?")
if err != nil {
return err
}
m.Reply("Great! I like " + response.Text() + " too!")
return nil
})
Manual Conversations
For more control, use NewConversation():
Basic Conversation
Exclusive Conversation
Wait for Reply
Custom Events
func StartConversation(client *telegram.Client, userID int64) {
// Create conversation (userID, exclusive, timeout)
conv, err := client.NewConversation(userID, false, 30)
if err != nil {
return
}
defer conv.Close()
// Send message
conv.Respond("Hello! Let's chat.")
// Wait for response
resp, err := conv.GetResponse()
if err != nil {
conv.Respond("No response received.")
return
}
conv.Respond("You said: " + resp.Text())
}
Conversation Methods
Send a message in the conversation
Wait for any response from the user
Wait for a reply to the last sent message
Wait for a button click in the conversation
Wait for any update event in the conversation
Mark conversation messages as read
End the conversation and clean up resources
Complete Example: Survey Bot
func SurveyBot(m *telegram.NewMessage) error {
m.Reply("📋 Let's start a quick survey!")
// Question 1
q1, _ := m.Ask("1. How would you rate our service? (1-5)")
rating := q1.Text()
// Question 2
q2, _ := m.Ask("2. What do you like most?")
likes := q2.Text()
// Question 3
q3, _ := m.Ask("3. What can we improve?")
improvements := q3.Text()
// Summary
summary := fmt.Sprintf(
"✅ Survey Complete!\n\n"+
"Rating: %s/5\n"+
"Likes: %s\n"+
"Improvements: %s\n\n"+
"Thank you for your feedback!",
rating, likes, improvements,
)
m.Reply(summary)
// Save to database...
return nil
}
func main() {
client, _ := telegram.NewClient(telegram.ClientConfig{
AppID: appID,
AppHash: appHash,
LogLevel: telegram.LogInfo,
})
client.LoginBot(botToken)
client.On("message:/survey", SurveyBot)
client.Idle()
}
Running the Example
- Replace
YOUR_APP_HASH and YOUR_BOT_TOKEN with your credentials
- Replace
"username or id" with a target user (for manual conversation example)
- Run the program
- Send any message to trigger
convEventHandler, which will ask for your name
Timeouts: Conversations have a default timeout. Use appropriate timeout values based on expected response time.
For complex multi-step flows, consider using state management or conversation states to track progress.
Next Steps