summaryrefslogblamecommitdiff
path: root/plugins/tg.go
blob: ccd3a9b1479919e5067195978d0b53acfec6589e (plain) (tree)
































































































































                                                                                                                                                                  
package plugins

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"net/http"
	"os"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
	"github.com/neonxp/tamtam"

	"transport/lib"
)

type Telegram struct {
	Routing []lib.Routing
	API     *tgbotapi.BotAPI
	Updates chan lib.Message
	Bus     chan lib.Message
}

func NewTelegram(token string, updates chan lib.Message, bus chan lib.Message, routing []lib.Routing) *Telegram {
	tgApi, err := tgbotapi.NewBotAPI(token)
	if err != nil {
		log.Panic(err)
	}

	return &Telegram{API: tgApi, Updates: updates, Bus: bus, Routing: routing}
}

func (t *Telegram) Run(ctx context.Context) error {

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates, err := t.API.GetUpdatesChan(u)
	if err != nil {
		return err
	}
	for {
		select {
		case <-ctx.Done():
			return nil
		case upd := <-updates:
			if upd.Message == nil { // ignore any non-Message Updates
				continue
			}
			for _, r := range t.Routing {
				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)
					}
					isSticker := ""
					images := make([]string, 0)
					if upd.Message.Sticker != nil {
						isSticker = upd.Message.Sticker.Emoji
						s, _ := t.API.GetFileDirectURL(upd.Message.Sticker.Thumbnail.FileID)
						images = append(images, s)
					}
					if upd.Message.Photo != nil && len(*upd.Message.Photo) > 0 {
						p := (*upd.Message.Photo)[0]
						s, _ := t.API.GetFileDirectURL(p.FileID)
						images = append(images, s)
					}
					t.Bus <- lib.Message{
						To:      r.TTID,
						From:    from,
						Text:    upd.Message.Text,
						Images:  images,
						Sticker: isSticker,
					}
				}
			}
		case msg := <-t.Updates:
			att := make([]interface{}, 0)
			for _, a := range msg.Images {
				att = append(att, tamtam.Image{Url: a})
			}
			text := fmt.Sprintf("*%s*:\n%s", msg.From, msg.Text)
			if len(msg.Text) > 0 {
				res, err := t.API.Send(tgbotapi.MessageConfig{
					BaseChat: tgbotapi.BaseChat{
						ChatID:           msg.To,
						ReplyToMessageID: 0,
					},
					Text:                  text,
					DisableWebPagePreview: false,
					ParseMode:             "markdown",
				})
				log.Printf("[TG] Send text: %#v %#v", res, err)
			}
			if len(msg.Images) > 0 {
				for _, i := range msg.Images {
					u, err := t.DownloadFile(i)
					if err != nil {
						log.Printf("[TG] Download image: %#v", err)
						continue
					}
					m := tgbotapi.NewPhotoUpload(msg.To, u)
					m.Caption = msg.Sticker
					res, err := t.API.Send(m)
					log.Printf("[TG] Send image: %#v %#v", res, err)
				}
			}
		}
	}
}

func (t *Telegram) DownloadFile(u string) (string, error) {
	resp, err := http.Get(u)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	// Write the body to file

	f, err := ioutil.TempFile(os.TempDir(), "tg*")
	if err != nil {
		return "", err
	}
	_, err = io.Copy(f, resp.Body)
	defer f.Close()
	return f.Name(), nil
}