-
-
Notifications
You must be signed in to change notification settings - Fork 139
/
main.go
86 lines (71 loc) · 2.51 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
// Binary bot-upload implements upload example for bot.
package main
import (
"context"
"flag"
"fmt"
"github.com/go-faster/errors"
"go.uber.org/zap"
"github.com/gotd/td/examples"
"github.com/gotd/td/telegram"
"github.com/gotd/td/telegram/message"
"github.com/gotd/td/telegram/message/html"
"github.com/gotd/td/telegram/uploader"
"github.com/gotd/td/tg"
)
func main() {
// Environment variables:
// BOT_TOKEN: token from BotFather
// APP_ID: app_id of Telegram app.
// APP_HASH: app_hash of Telegram app.
// SESSION_FILE: path to session file
// SESSION_DIR: path to session directory, if SESSION_FILE is not set
filePath := flag.String("file", "", "file to upload")
targetDomain := flag.String("target", "", "target to upload, e.g. channel name")
flag.Parse()
examples.Run(func(ctx context.Context, log *zap.Logger) error {
if *filePath == "" || *targetDomain == "" {
return errors.New("no --file or --target provided")
}
// The performUpload will be called after client initialization.
performUpload := func(ctx context.Context, client *telegram.Client) error {
// Raw MTProto API client, allows making raw RPC calls.
api := tg.NewClient(client)
// Helper for uploading. Automatically uses big file upload when needed.
u := uploader.NewUploader(api)
// Helper for sending messages.
sender := message.NewSender(api).WithUploader(u)
// Uploading directly from path. Note that you can do it from
// io.Reader or buffer, see From* methods of uploader.
log.Info("Uploading file")
upload, err := u.FromPath(ctx, *filePath)
if err != nil {
return fmt.Errorf("upload %q: %w", *filePath, err)
}
// Now we have uploaded file handle, sending it as styled message.
// First, preparing message.
document := message.UploadedDocument(upload,
html.String(nil, `Upload: <b>From bot</b>`),
)
// You can set MIME type, send file as video or audio by using
// document builder:
document.
MIME("audio/mp3").
Filename("some-audio.mp3").
Audio()
// Resolving target. Can be telephone number or @nickname of user,
// group or channel.
target := sender.Resolve(*targetDomain)
// Sending message with media.
log.Info("Sending file")
if _, err := target.Media(ctx, document); err != nil {
return fmt.Errorf("send: %w", err)
}
return nil
}
return telegram.BotFromEnvironment(ctx, telegram.Options{
Logger: log,
NoUpdates: true, // don't subscribe to updates in one-shot mode
}, nil, performUpload)
})
}