~mendelmaleh/tg_colorbot

ref: cce38233eec481c4c66b3ef8b42d9a824705910e tg_colorbot/main.go -rw-r--r-- 2.3 KiB
cce38233Mendel E Add web preview description 1 year, 20 days ago
                                                                                
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
package main

import (
	"fmt"
	"html"
	"io/ioutil"
	"log"
	"net/url"
	"strings"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
	"github.com/pelletier/go-toml"
)

type Config struct {
	Bot struct {
		Token string
	}
}

type Color struct {
	Color            string
	Name, Background int
}

var colors = map[uint]Color{
	0: {"red", 0xfb6169, 0xdd4554},
	3: {"green", 0x85de85, 0x63aa55},
	// {"yellow", 0xf3bc5c, 0xd0973c}, unreachable
	5: {"blue", 0x65bdf3, 0x4388b9},
	2: {"purple", 0xb48bf2, 0x7965c1},
	6: {"pink", 0xff5694, 0xcb4f87},
	4: {"sea", 0x62d4e3, 0x41a4a6},
	1: {"orange", 0xfaa357, 0xdb863b},
}

func main() {
	doc, err := ioutil.ReadFile("config.toml")
	if err != nil {
		log.Panic(err)
	}

	config := Config{}
	err = toml.Unmarshal(doc, &config)
	if err != nil {
		log.Panic(err)
	}

	bot, err := tgbotapi.NewBotAPI(config.Bot.Token)
	if err != nil {
		log.Panic(err)
	}

	log.Printf("Authorized on account %s", bot.Self.UserName)
	updates, err := bot.GetUpdatesChan(tgbotapi.UpdateConfig{Timeout: 60})
	if err != nil {
		log.Panic(err)
	}

	for u := range updates {
		if u.InlineQuery != nil {
			q := u.InlineQuery

			var n uint
			if q.From.ID < 0 {
				n = uint(q.From.ID * -1)
			} else {
				n = uint(q.From.ID)
			}

			c, ok := colors[n%7]
			if !ok {
				continue
			}

			r := tgbotapi.InlineQueryResultArticle{
				Type:        "article", // must be
				ID:          c.Color,
				Title:       strings.Title(c.Color),
				Description: fmt.Sprintf("Your color is %s", c.Color),
				ThumbURL:    fmt.Sprintf("https://dummy.mendel.sh/?width=64&color=%x&color=%x", c.Background, c.Name),
				InputMessageContent: tgbotapi.InputTextMessageContent{
					ParseMode: "html",
					Text: fmt.Sprintf(
						"Your color is <b>%s</b>\n - name: <code>#%x</code>\n - background: <code>#%x</code>\n<a href=\"%s\">&#8203;</a>",
						c.Color, c.Name, c.Background, html.EscapeString(fmt.Sprintf(
							"https://dummy.mendel.sh/web/%d/?width=64&color=%x&color=%x&desc=%s",
							q.From.ID, c.Background, c.Name, url.QueryEscape("What's my color?"),
						)),
					),
				},
			}

			results := make([]interface{}, 1)
			results[0] = r

			api, err := bot.AnswerInlineQuery(tgbotapi.InlineConfig{
				InlineQueryID: q.ID,
				Results:       results,
			})
			if err != nil {
				log.Println(api, err)
			}
		}
	}
}