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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/go-telegram-bot-api/telegram-bot-api"
"github.com/neonxp/rutina"
"github.com/neonxp/tamtam"
)
type message struct {
From string
To int64
Text string
}
type routing struct {
TgID int64
TTID int64
}
func main() {
tamtamToken := os.Getenv("TAMTAM")
telegramToken := os.Getenv("TELEGRAM")
r := rutina.New()
routes := []routing{
{TgID: -1001046507545, TTID: -69062921115159},
}
tt2tg := make(chan message, 1)
tg2tt := make(chan message, 1)
// region TamTam
tamtamApi := tamtam.New(tamtamToken)
ttch := make(chan interface{}, 1)
r.Go(func(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return nil
case upd := <-ttch:
log.Printf("[TT] Received: %#v", upd)
switch upd := upd.(type) {
case tamtam.UpdateMessageCreated:
for _, r := range routes {
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)
}
tt2tg <- message{
To: r.TgID,
From: from,
Text: upd.Message.Body.Text,
}
}
}
default:
log.Printf("Unknown type: %#v", upd)
}
case msg := <-tg2tt:
res, err := tamtamApi.SendMessage(msg.To, msg.To, &tamtam.NewMessageBody{
Text: fmt.Sprintf("[TG] %s: %s", msg.From, msg.Text),
})
log.Printf("[TT] Answer: %#v %#v", res, err)
}
}
}, rutina.ShutdownIfDone, rutina.RestartIfFail)
r.Go(func(ctx context.Context) error {
return tamtamApi.GetUpdatesLoop(ctx, ttch)
}, rutina.ShutdownIfDone, rutina.RestartIfFail)
// endregion
// region Telegram
tgApi, err := tgbotapi.NewBotAPI(telegramToken)
if err != nil {
log.Panic(err)
}
tgApi.Debug = true
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := tgApi.GetUpdatesChan(u)
r.Go(func(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return nil
case upd := <-updates:
if upd.Message == nil { // ignore any non-Message Updates
continue
}
for _, r := range routes {
if r.TgID == upd.Message.Chat.ID {
from := fmt.Sprintf("%s %s", upd.Message.From.FirstName, upd.Message.From.LastName)
if upd.Message.From.UserName != "" {
from = fmt.Sprintf("%s %s (%s)", upd.Message.From.FirstName, upd.Message.From.LastName, upd.Message.From.UserName)
}
tg2tt <- message{
To: r.TTID,
From: from,
Text: upd.Message.Text,
}
}
}
case msg := <-tt2tg:
res, err := tgApi.Send(tgbotapi.NewMessage(msg.To, fmt.Sprintf("[TT] %s: %s", msg.From, msg.Text)))
log.Printf("[TG] Answer: %#v %#v", res, err)
}
}
}, rutina.ShutdownIfDone, rutina.RestartIfFail)
// endregion
r.ListenOsSignals()
if err := r.Wait(); err != nil {
log.Fatal(err)
}
}
|