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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
|
package plugins
import (
"context"
"fmt"
"log"
"strings"
"github.com/neonxp/tamtam"
"transport/lib"
)
type TamTam struct {
Routing []lib.Routing
API *tamtam.Api
Updates chan lib.Message
Bus chan lib.Message
}
func NewTamTam(token string, updates chan lib.Message, bus chan lib.Message, routing []lib.Routing) *TamTam {
return &TamTam{API: tamtam.New(token), Updates: updates, Bus: bus, Routing: routing}
}
func (t *TamTam) Run(ctx context.Context) error {
updates := make(chan interface{}, 1)
go func() {
if err := t.API.GetUpdatesLoop(ctx, updates); err != nil {
log.Printf("[TT] Error: %#v", err)
}
}()
for {
select {
case <-ctx.Done():
return nil
case upd := <-updates:
log.Printf("[TT] Received: %#v", upd)
switch upd := upd.(type) {
case tamtam.UpdateMessageCreated:
for _, r := range t.Routing {
if r.TTID == upd.Message.Recipient.ChatId {
from := upd.Message.Sender.Name
if upd.Message.Sender.Username != "" {
from = fmt.Sprintf("%s (%s)", upd.Message.Sender.Name, upd.Message.Sender.Username)
}
isSticker := ""
images := make([]string, 0)
for _, a := range upd.Message.Body.Attachments {
switch a := a.(type) {
case *tamtam.PhotoAttachment:
images = append(images, *a.Payload.Url)
case *tamtam.StickerAttachment:
images = append(images, a.Payload.Url)
isSticker = "СТИКЕР"
}
}
t.Bus <- lib.Message{
To: r.TgID,
From: from,
Text: upd.Message.Body.Text,
Images: images,
Sticker: isSticker,
}
}
}
default:
log.Printf("Unknown type: %#v", upd)
}
case msg := <-t.Updates:
text := fmt.Sprintf("*%s*:\n%s", strings.Trim(msg.From, " "), msg.Text)
if msg.Sticker != "" {
text = fmt.Sprintf("*%s*: [%s]", strings.Trim(msg.From, " "), msg.Sticker)
}
attachments := make([]interface{}, 0, len(msg.Images))
if len(msg.Images) > 0 {
toSent := []string{}
for _, i := range msg.Images {
ok := true
for _, j := range toSent {
if i == j {
ok = false
}
}
if ok {
toSent = append(toSent, i)
}
}
for _, i := range toSent {
attachments = append(attachments, tamtam.PhotoAttachment{
Type: "image",
Payload: tamtam.PhotoAttachmentPayload{
Url: &i,
},
})
}
}
if len(text) > 0 || len(attachments) > 0 {
res, err := t.API.SendMessage(msg.To, msg.To, &tamtam.NewMessageBody{
Text: text,
Attachments: attachments,
})
log.Printf("[TT] Answer: %#v %#v", res, err)
}
}
}
}
|