forked from 4FR4KO-POVELECKO/teles
/
bot.go
137 lines (108 loc) · 2.08 KB
/
bot.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package teles
import (
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"strconv"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)
type telegrambot struct {
Bot *tgbotapi.BotAPI
ChatID int64
}
func new(token string) (*telegrambot, error) {
bot, err := tgbotapi.NewBotAPI(token)
if err != nil {
return nil, err
}
bot.Debug = false
id, result := checkChatID()
if result {
return &telegrambot{
Bot: bot,
ChatID: id,
}, nil
}
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, _ := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil {
continue
}
saveChatID(update.Message.Chat.ID)
return &telegrambot{
Bot: bot,
ChatID: update.Message.Chat.ID,
}, nil
}
return nil, nil
}
func (b *telegrambot) Send(text string) {
msg := tgbotapi.NewMessage(b.ChatID, text)
b.Bot.Send(msg)
}
func checkChatID() (int64, bool) {
f, err := os.Open("./.teles/chat_id")
if err != nil {
return 0, false
}
defer f.Close()
b, err := ioutil.ReadAll(f)
if err != nil {
return 0, false
}
s := string(b)
id, _ := strconv.ParseInt(s, 10, 64)
return id, true
}
func saveChatID(id int64) {
err := checkOrCreateDir("./.teles")
if err != nil {
return
}
f, err := checkOrCreateFile("./.teles/chat_id")
if err != nil {
return
}
defer f.Close()
_, err = f.WriteString(fmt.Sprint(id))
if err != nil {
return
}
}
func checkOrCreateDir(path string) error {
result, err := os.Stat(path)
if os.IsNotExist(err) {
err := os.Mkdir(path, os.ModePerm)
if err != nil {
return err
}
return nil
}
if !result.IsDir() {
return errors.New("Error to create directory, a file with the same name already exists")
}
return nil
}
func checkOrCreateFile(path string) (*os.File, error) {
result, err := os.Stat(path)
if os.IsNotExist(err) {
f, err := os.Create(path)
if err != nil {
return nil, err
}
return f, nil
}
if result.IsDir() {
return nil, errors.New("IsDir")
}
f, err := os.Open(path)
if err != nil {
return nil, err
}
return f, nil
}