This repository has been archived by the owner on Aug 14, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
bing.go
110 lines (95 loc) · 2.23 KB
/
bing.go
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
// Copyright 2015 The tgbot-ng Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"errors"
"io/ioutil"
"math/rand"
"net/http"
"path"
"regexp"
"github.com/jroimartin/tgbot-ng/bing"
"github.com/jroimartin/tgbot-ng/tg"
)
type cmdBing struct {
re *regexp.Regexp
config CmdConfigBing
cli *tg.Client
}
type CmdConfigBing struct {
Enabled bool `json:"enabled"`
ApiKey string `json:"api_key"`
SearchLimit int `json:"search_limit"`
}
func NewCmdBing(config CmdConfigBing, cli *tg.Client) Command {
if config.SearchLimit < 1 {
config.SearchLimit = 10
}
return &cmdBing{
re: regexp.MustCompile(`^/bing(?:@[^ ]+?)?(?:$| +(.+)$)`),
config: config,
cli: cli,
}
}
func (cmd *cmdBing) Match(text string) bool {
return cmd.re.MatchString(text)
}
func (cmd *cmdBing) Run(chatID, replyID int, text string) error {
var query string
m := cmd.re.FindStringSubmatch(text)
if len(m) == 2 {
query = m[1]
}
if query == "" {
kbd := tg.ReplyKeyboardMarkup{
Keyboard: [][]string{
[]string{"/bing underboobs", "/bing sideboobs"},
},
Resize: true,
OneTime: true,
Selective: true,
}
if _, err := cmd.cli.SendKbd(chatID, replyID, "Choose your destiny", kbd); err != nil {
return err
}
} else {
img, err := cmd.search(query)
if err != nil {
return err
}
if path.Ext(img.Name) == ".gif" {
_, err = cmd.cli.SendDocument(chatID, img)
} else {
_, err = cmd.cli.SendPhoto(chatID, img)
}
if err != nil {
return err
}
}
return nil
}
func (cmd *cmdBing) search(query string) (img tg.File, err error) {
c := bing.NewClient(cmd.config.ApiKey)
if cmd.config.SearchLimit > 0 {
c.Limit = cmd.config.SearchLimit
}
results, err := c.Query(bing.Image, query)
if err != nil {
return tg.File{}, err
}
if len(results) == 0 {
return tg.File{}, errors.New("no pics")
}
rndInt := rand.Intn(len(results))
resp, err := http.Get(results[rndInt].MediaUrl)
if err != nil {
return tg.File{}, err
}
defer resp.Body.Close()
imgData, err := ioutil.ReadAll(resp.Body)
if err != nil {
return tg.File{}, err
}
return tg.File{Name: results[rndInt].MediaUrl, Data: imgData}, nil
}