all repos — telebonk @ d5fb0ba220b26f5bc0e7ff593c4be35a2cf65206

reposter from honk to telegram

main.go (view raw)

  1// Telebonk is a reposter from Honk to Telegram.
  2package main
  3
  4import (
  5	"bytes"
  6	"encoding/json"
  7	"flag"
  8	"fmt"
  9	"io"
 10	"log"
 11	"net/http"
 12	"net/url"
 13	"regexp"
 14	"sort"
 15	"strconv"
 16	"strings"
 17	"time"
 18)
 19
 20// A Config is holding configuration of telebonk.
 21type Config struct {
 22	TgBotToken    string
 23	TgChatID      string
 24	TgApiURL      string
 25	HonkAuthToken string
 26	HonkURL       string
 27}
 28
 29// Check makes sure that no Config fields are set to empty strings.
 30func (c *Config) Check() error {
 31	var what string
 32	if c.TgBotToken == "" {
 33		what = "bot_token"
 34	}
 35	if c.TgChatID == "" {
 36		what = "chat_id"
 37	}
 38	if c.TgApiURL == "" {
 39		what = "tgapi_url"
 40	}
 41	if c.HonkAuthToken == "" {
 42		what = "honk_token"
 43	}
 44	if c.HonkURL == "" {
 45		what = "honk_url"
 46	}
 47	if what != "" {
 48		return fmt.Errorf("'%s' shouldn't be empty", what)
 49	}
 50	return nil
 51}
 52
 53var config = &Config{}
 54
 55// A Honk is a honk's honk object with most fields omitted.
 56type Honk struct {
 57	ID     int
 58	What   string // to filter out honkbacks
 59	Oondle string
 60	Oonker string
 61	XID    string
 62	RID    string
 63	Date   time.Time
 64	Precis string // danger zone and all that
 65	Noise  string
 66	Onts   []string // to filter out #notg
 67	Donks  []*Donk
 68
 69	messID    int
 70	replyToID int
 71}
 72
 73// A Donk stores metadata for media files.
 74type Donk struct {
 75	URL   string
 76	Media string
 77	Desc  string
 78}
 79
 80// Check performs some checks on a Honk to filter out what's not going to be posted.
 81//
 82// It rejects honk if if falls into one of these categories:
 83//   - it is posted before the telebonk started
 84//   - it is replying to a honk that's not posted by telebonk (either a remote honk or old honk)
 85//   - it is of unsupported type (not a regular honk, reply or bonk)
 86//   - it contains a `#notg` tag.
 87//   - it is empty
 88func (h *Honk) Check() error {
 89	log.Print("checking honk #", h.ID)
 90	if h.Date.Before(now) {
 91		return fmt.Errorf("honk #%d is old", h.ID)
 92	}
 93	switch h.What {
 94	case "honked", "bonked":
 95		break
 96	case "honked back":
 97		hi, ok := honkMap[h.RID]
 98		if !ok {
 99			return fmt.Errorf("cannot reply to nonexisting telebonk")
100		}
101		h.replyToID = hi.t.Result.MessageID
102	default:
103		return fmt.Errorf("unsupported honk type: %s", h.What)
104	}
105
106	for _, ont := range h.Onts {
107		if strings.ToLower(ont) == "#notg" {
108			return fmt.Errorf("skipping #notg honk")
109		}
110	}
111
112	if h.Noise == emptyNoise && len(h.Donks) == 0 {
113		return fmt.Errorf("empty honk")
114	}
115	return nil
116}
117
118func (h *Honk) Decide() honkAction {
119	hi, ok := honkMap[h.XID]
120	if ok {
121		if hi.t == nil || hi.h.Date.Equal(h.Date) {
122			h.save(hi.t) // is this wrong?
123			return honkIgnore
124		}
125		h.messID = hi.t.Result.MessageID
126		return honkEdit
127	}
128	return honkSend
129}
130
131// save records Honk to a honkMap
132func (h *Honk) save(t *TelegramResponse) {
133	honkMap[h.XID] = honkInfo{h: h, t: t}
134}
135
136// forget removes Honk from a honkMap
137func (h *Honk) forget() {
138	delete(honkMap, h.XID)
139}
140
141type honkAction int
142
143const (
144	honkIgnore honkAction = iota
145	honkSend
146	honkEdit
147)
148
149const emptyNoise = "<p></p>\n"
150
151// A Mess holds data for a message to be sent to Telegram.
152type Mess struct {
153	Text             string `json:"text"`
154	ParseMode        string `json:"parse_mode"`
155	ChatID           string `json:"chat_id"`
156	MessageID        int    `json:"message_id,omitempty"`
157	ReplyToMessageID int    `json:"reply_to_message_id,omitempty"`
158
159	// Donks
160	Document string   `json:"document,omitempty"`
161	Photo    string   `json:"photo,omitempty"`
162	Caption  string   `json:"caption,omitempty"`
163	kind     messKind // messHonk, messDonkPht or messDonkDoc
164}
165
166// A TelegramResponse is for handling possible errors with Telegram API.
167type TelegramResponse struct {
168	Ok          bool
169	Description string
170	Result      telegramResponseResult
171}
172
173type telegramResponseResult struct {
174	MessageID int `json:"message_id"`
175}
176
177// NewMess creates and populates a new Mess with default values.
178func NewMess(parseMode string) *Mess {
179	return &Mess{
180		ParseMode: parseMode,
181		ChatID:    config.TgChatID,
182		kind:      messHonk,
183	}
184}
185
186// NewMessFromHonk creates a slice of Mess objects from existing Honk.
187func NewMessFromHonk(honk *Honk, action honkAction) []*Mess {
188	// donks should be sent as a separate messages, so need to create all of 'em
189	// cap(messes) = 1 for honk + 1 for each donk
190	var messes = make([]*Mess, 0, 1+len(honk.Donks))
191
192	messes = append(messes, NewMess("html"))
193	for _, donk := range honk.Donks {
194		donkMess := NewMess("MarkdownV2") // donks don't contain html
195		donkMess.Caption = donk.Desc      // FIXME: no check for length
196		switch {
197		case strings.HasPrefix(donk.Media, "image/"):
198			donkMess.Photo = donk.URL
199			donkMess.kind = messDonkPht
200		case donk.Media == "application/pdf", donk.Media == "text/plain":
201			donkMess.Document = donk.URL
202			donkMess.kind = messDonkDoc
203		}
204		messes = append(messes, donkMess)
205	}
206	if honk.Noise == emptyNoise {
207		messes = messes[1:] // just donks
208	}
209
210	if action == honkEdit {
211		// TODO: implement editing documents and photos
212		messes[0].kind = messEdit
213		messes[0].MessageID = honk.messID
214		messes = messes[:1] // don't donk if editing
215	}
216
217	var noise = calmNoise(honk.Noise)
218	// bonk, then honk back - ok
219	// honk back, then bonk - not gonna sync, is it ok?
220	// upd: bonks work really confusing
221	switch honk.What {
222	case "honked":
223		break
224	case "honked back":
225		messes[0].ReplyToMessageID = honk.replyToID
226	case "bonked":
227		oonker := fmt.Sprintf("<a href=\"%s\">%s</a>:", honk.Oonker, honk.Oondle)
228		noise = oonker + "\n" + noise
229	}
230
231	// danger zone handling
232	if strings.HasPrefix(honk.Precis, "DZ:") {
233		noise = strings.Join([]string{"<tg-spoiler>", "</tg-spoiler>"}, noise)
234		noise = honk.Precis + "\n" + noise
235	}
236	messes[0].Text = noise
237
238	return messes
239}
240
241// Send sends a Mess to Telegram.
242func (m *Mess) Send() (*TelegramResponse, error) {
243	var apiURL = botAPIMethod(tgSendMessage)
244
245	switch m.kind {
246	case messHonk:
247		// noop
248	case messEdit:
249		apiURL = botAPIMethod(tgEditMessageText)
250	case messDonkPht:
251		apiURL = botAPIMethod(tgSendPhoto)
252	case messDonkDoc:
253		apiURL = botAPIMethod(tgSendDocument)
254	}
255
256	junk, err := json.Marshal(m)
257	if err != nil {
258		return nil, err
259	}
260	buf := bytes.NewBuffer(junk)
261	req, err := http.NewRequest("POST", apiURL, buf)
262	if err != nil {
263		return nil, err
264	}
265	req.Header.Add("Content-type", "application/json")
266	req.Header.Add("Content-length", strconv.Itoa(buf.Len()))
267
268	resp, err := client.Do(req)
269	if err != nil {
270		return nil, err
271	}
272	defer resp.Body.Close()
273
274	var res TelegramResponse
275	json.NewDecoder(resp.Body).Decode(&res)
276	if !res.Ok {
277		return nil, fmt.Errorf("mess send: %s", res.Description)
278	}
279
280	return &res, nil
281}
282
283type messKind int
284
285const (
286	messHonk messKind = iota
287	messEdit
288	messDonkPht
289	messDonkDoc
290)
291
292func botAPIMethod(method string) string {
293	return fmt.Sprintf("%s/bot%s/%s", config.TgApiURL, config.TgBotToken, method)
294}
295
296func checkTgAPI() error {
297	var apiURL = botAPIMethod(tgGetMe)
298	resp, err := client.Get(apiURL)
299	if err != nil {
300		return err
301	}
302	if resp.StatusCode != 200 {
303		status, _ := io.ReadAll(resp.Body)
304		return fmt.Errorf("status: %d: %s", resp.StatusCode, status)
305	}
306	return nil
307}
308
309const (
310	tgGetMe           = "getMe"
311	tgSendMessage     = "sendMessage"
312	tgEditMessageText = "editMessageText"
313	tgSendPhoto       = "sendPhoto"
314	tgSendDocument    = "sendDocument"
315)
316
317// A honkInfo stores data for honk that is sent to Telegram.
318type honkInfo struct {
319	h *Honk
320	t *TelegramResponse
321}
322
323// getHonks receives and unmarshals some honks from a Honk instance.
324func getHonks(after int) ([]*Honk, error) {
325	query := url.Values{}
326	query.Set("token", config.HonkAuthToken)
327	query.Set("action", "gethonks")
328	query.Set("page", "home")
329	query.Set("after", strconv.Itoa(after))
330
331	resp, err := client.Get(fmt.Sprint(config.HonkURL, "/api?", query.Encode()))
332	if err != nil {
333		return nil, err
334	}
335	defer resp.Body.Close()
336
337	// honk outputs junk like `{ "honks": [ ... ] }`, need to get into the list
338	var honkJunk map[string][]*Honk
339	err = json.NewDecoder(resp.Body).Decode(&honkJunk)
340	if err != nil {
341		return nil, err
342	}
343
344	honks := honkJunk["honks"]
345	// honk.ID monotonically increases, so it can be used to sort them
346	sort.Slice(honks, func(i, j int) bool { return honks[i].ID < honks[j].ID })
347
348	return honks, nil
349}
350
351var (
352	rePTags   = regexp.MustCompile(`<\/?p>`)
353	reHlTags  = regexp.MustCompile(`<\/?span( class="[a-z]{2}")?>`)
354	reBrTags  = regexp.MustCompile(`<br>`)
355	reImgTags = regexp.MustCompile(`<img .*src="(.*)">`)
356	reUlTags  = regexp.MustCompile(`<\/?ul>`)
357	reTbTags  = regexp.MustCompile(`<table>.*</table>`)
358
359	reLiTags = regexp.MustCompile(`<li>([^<>\/]*)<\/li>`)
360	reHnTags = regexp.MustCompile(`<h[1-6]>(.*)</h[1-6]>`)
361	reHrTags = regexp.MustCompile(`<hr>.*<\/hr>`)
362	reBqTags = regexp.MustCompile(`<blockquote>(.*)<\/blockquote>`)
363)
364
365// calmNoise erases htm tags that are not supported by Telegram.
366func calmNoise(noise string) string {
367	// TODO: check length of a honk
368
369	// delete these
370	noise = rePTags.ReplaceAllString(noise, "")
371	noise = reHlTags.ReplaceAllString(noise, "")
372	noise = reBrTags.ReplaceAllString(noise, "")
373	noise = reImgTags.ReplaceAllString(noise, "")
374	noise = reUlTags.ReplaceAllString(noise, "")
375	noise = reTbTags.ReplaceAllString(noise, "")
376
377	// these can be repurposed
378	noise = reHrTags.ReplaceAllString(noise, "---\n")
379	noise = reHnTags.ReplaceAllString(noise, "<b>$1</b>\n\n")
380	noise = reBqTags.ReplaceAllString(noise, "| <i>$1</i>")
381	noise = reLiTags.ReplaceAllString(noise, "* $1\n")
382
383	return strings.TrimSpace(noise)
384}
385
386func init() {
387	flag.StringVar(&config.TgBotToken, "bot_token", "", "Telegram bot token")
388	flag.StringVar(&config.TgChatID, "chat_id", "", "Telegram chat_id")
389	flag.StringVar(&config.TgApiURL, "tgapi_url", "https://api.telegram.org", "Telegram API URL")
390	flag.StringVar(&config.HonkAuthToken, "honk_token", "", "Honk auth token")
391	flag.StringVar(&config.HonkURL, "honk_url", "", "URL of a Honk instance")
392
393	flag.Parse()
394
395	err := config.Check()
396	if err != nil {
397		log.Fatal("config:", err)
398	}
399	err = checkTgAPI()
400	if err != nil {
401		log.Fatal(err)
402	}
403}
404
405var client = http.DefaultClient
406var honkMap = make(map[string]honkInfo) // FIXME: not safe for use by multiple goroutines!
407var now = time.Now()
408
409func main() {
410
411	for {
412		honks, err := getHonks(0)
413		if err != nil {
414			log.Fatal("gethonks:", err)
415		}
416	HonkLoop:
417		for _, honk := range honks {
418			action := honk.Decide()
419			switch action {
420			case honkIgnore:
421				continue
422			case honkSend, honkEdit:
423				err := honk.Check()
424				if err != nil {
425					log.Print(err)
426					continue
427				}
428			}
429			messes := NewMessFromHonk(honk, action)
430			// messes[0] is a honk or a donk to be sent
431			resp, err := messes[0].Send()
432			if err != nil {
433				log.Print(err)
434				honk.forget() // retry
435				continue
436			}
437			// remember only the first mess' response
438			honk.save(resp)
439			for _, mess := range messes[1:] {
440				_, err := mess.Send()
441				if err != nil {
442					log.Print(err)
443					continue HonkLoop
444				}
445			}
446		}
447		time.Sleep(30 * time.Second)
448	}
449}