Gogram supports multiple authentication methods to connect to Telegram. You can authenticate as a bot using a bot token or as a user using a phone number.
client, err := telegram.NewClient(telegram.ClientConfig{ AppID: 6, AppHash: "your_app_hash", SessionName: "my_session", // Custom session name Session: "session.dat", // Custom session filename or path to use // optional, the key used to encrypt the session file. SessionAESKey: "12345678901234567890123456789012"})
session.dat is the default session file name
If you use more than one account or bot in the same program or directory, make sure their Session or SessionName fields are unique to prevent authentication data from being overwritten.
For advanced use cases, you can implement custom session storage using MongoDB, Redis, or any other database.The session is represented by the Session struct:
Copy
type Session struct { Key []byte // AUTH_KEY Hash []byte // AUTH_KEY_HASH (SHA1 of AUTH_KEY) Salt int64 // SERVER_SALT Hostname string // HOSTNAME (IP address of the DC) AppID int32 // APP_ID}
Export and Import Raw Session:
Copy
// Export raw sessionrawSession := client.ExportRawSession()encodedSession := rawSession.Encode()// Import raw sessionclient.ImportAuth(encodedSession)
Example with Redis:
Copy
import ( "encoding/json" "github.com/amarnathcjd/gogram/telegram")// After authentication, export and save to RedisrawSession := client.ExportRawSession()sessionJSON, _ := json.Marshal(rawSession)redisClient.Set(ctx, "session:"+userID, sessionJSON, 0)// Load from Redis and importsessionJSON, _ := redisClient.Get(ctx, "session:"+userID).Bytes()var session telegram.Sessionjson.Unmarshal(sessionJSON, &session)client, _ := telegram.NewClient(telegram.ClientConfig{ AppID: 6, AppHash: "your_app_hash",})client.ImportAuth(session.Encode())client.Conn()
// Export as encoded string (base64)sessionString := client.ExportSession()// Store in databasedatabase.Save(userID, sessionString)// Later, retrieve and importsessionString := database.Load(userID)client.ImportSession([]byte(sessionString))
Custom session handlers are perfect for multi-tenant applications or when you need centralized session management across multiple instances.
If your account has 2FA enabled, provide the password:
Copy
// The library will prompt for the password if neededclient.Login("+1234567890")// Or handle it manuallyclient.Login("+1234567890", &tg.LoginOptions{ Password: "your_2fa_password",})