-
-
Notifications
You must be signed in to change notification settings - Fork 134
/
main.go
90 lines (74 loc) · 2.05 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
// Binary bot-auth-manual implements example of custom session storage and
// manually setting up client options without environment variables.
package main
import (
"context"
"flag"
"sync"
"go.uber.org/zap"
"github.com/gotd/td/examples"
"github.com/gotd/td/session"
"github.com/gotd/td/telegram"
)
// memorySession implements in-memory session storage.
// Goroutine-safe.
type memorySession struct {
mux sync.RWMutex
data []byte
}
// LoadSession loads session from memory.
func (s *memorySession) LoadSession(context.Context) ([]byte, error) {
if s == nil {
return nil, session.ErrNotFound
}
s.mux.RLock()
defer s.mux.RUnlock()
if len(s.data) == 0 {
return nil, session.ErrNotFound
}
cpy := append([]byte(nil), s.data...)
return cpy, nil
}
// StoreSession stores session to memory.
func (s *memorySession) StoreSession(ctx context.Context, data []byte) error {
s.mux.Lock()
s.data = data
s.mux.Unlock()
return nil
}
func main() {
// Grab those from https://my.telegram.org/apps.
appID := flag.Int("api-id", 0, "app id")
appHash := flag.String("api-hash", "hash", "app hash")
// Get it from bot father.
token := flag.String("token", "", "bot token")
flag.Parse()
// Using custom session storage.
// You can save session to database, e.g. Redis, MongoDB or postgres.
// See memorySession for implementation details.
sessionStorage := &memorySession{}
examples.Run(func(ctx context.Context, log *zap.Logger) error {
client := telegram.NewClient(*appID, *appHash, telegram.Options{
SessionStorage: sessionStorage,
Logger: log,
})
return client.Run(ctx, func(ctx context.Context) error {
// Checking auth status.
status, err := client.Auth().Status(ctx)
if err != nil {
return err
}
// Can be already authenticated if we have valid session in
// session storage.
if !status.Authorized {
// Otherwise, perform bot authentication.
if _, err := client.Auth().Bot(ctx, *token); err != nil {
return err
}
}
// All good, manually authenticated.
log.Info("Done")
return nil
})
})
}