From 96611f2ebf3fec35470dab480913117e7a5ae286 Mon Sep 17 00:00:00 2001 From: vsaveliev Date: Wed, 31 Aug 2016 22:19:57 +0700 Subject: [PATCH] first commit --- DockerFile | 0 README.md | 1 + server.go | 121 ++++++++++++++++++++++++++++++++++++++++++++++++++ session.go | 55 +++++++++++++++++++++++ sessions.json | 11 +++++ 5 files changed, 188 insertions(+) create mode 100644 DockerFile create mode 100644 README.md create mode 100644 server.go create mode 100644 session.go create mode 100644 sessions.json diff --git a/DockerFile b/DockerFile new file mode 100644 index 0000000..e69de29 diff --git a/README.md b/README.md new file mode 100644 index 0000000..b89d856 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# subscription_bot diff --git a/server.go b/server.go new file mode 100644 index 0000000..f15db56 --- /dev/null +++ b/server.go @@ -0,0 +1,121 @@ +package main + +import ( + "encoding/json" + "gopkg.in/telegram-bot-api.v3" + "log" + "net/http" + "strconv" +) + +var userSessions map[string]UserSession + +type Message struct { + Message string +} + +func main() { + bot, err := createBot() + if err != nil { + log.Panic(err) + } + + http.HandleFunc("/subscription/add", func(w http.ResponseWriter, r *http.Request) { + var msg Message + + if r.Body == nil { + http.Error(w, "Please send a request body", 400) + return + } + + err := json.NewDecoder(r.Body).Decode(&msg) + if err != nil { + http.Error(w, err.Error(), 400) + return + } + + sendVacationToAll(bot, msg.Message) + + w.Header().Set("Content-Type", "application/json; charset=UTF-8") + w.WriteHeader(http.StatusOK) + }) + + go initApp(bot) + + log.Fatal(http.ListenAndServe(":8080", nil)) +} + +func initApp(bot *tgbotapi.BotAPI) { + userSessions = getUserSessions() + + u := tgbotapi.NewUpdate(0) + u.Timeout = 60 + + updates, _ := bot.GetUpdatesChan(u) + + for update := range updates { + log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text) + + processUpdate(bot, update) + } +} + +func processUpdate(bot *tgbotapi.BotAPI, update tgbotapi.Update) { + msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text) + + // switch { + // case msg.Text == "/start": + _, isExists := userSessions[strconv.FormatInt(update.Message.Chat.ID, 10)] + + if !isExists { + sendGreetingMessage(bot, msg) + addSession(update) + } + // } +} + +func createBot() (*tgbotapi.BotAPI, error) { + bot, err := tgbotapi.NewBotAPI("258957984:AAGmMmfsA8eYeHx8OB_mvyFqHZPGoOxOvds") + if err != nil { + return nil, err + } + bot.Debug = true + + log.Printf("Authorized on account %s", bot.Self.UserName) + + return bot, nil +} + +// TODO: create special struct for it #1 +func sendGreetingMessage(bot *tgbotapi.BotAPI, msg tgbotapi.MessageConfig) (bool, error) { + msg.Text = "Привет. Я твой персональный помощник по поиску вакансий! Теперь я буду отправлять вам вакансии" + + _, err := bot.Send(msg) + if err != nil { + return false, err + } + + return true, nil +} + +func sendVacationToAll(bot *tgbotapi.BotAPI, message string) { + + log.Printf("Send message to all - %s", message) + + for chatId, session := range userSessions { + log.Printf("Send message to - %s", chatId) + + msg := tgbotapi.MessageConfig{ + Text: message, + BaseChat: tgbotapi.BaseChat{ + ChatID: session.ChatId, + }, + ParseMode: "HTML", + } + + _, err := bot.Send(msg) + if err != nil { + return + } + } +} diff --git a/session.go b/session.go new file mode 100644 index 0000000..2c264b3 --- /dev/null +++ b/session.go @@ -0,0 +1,55 @@ +package main + +import ( + "encoding/json" + "fmt" + "gopkg.in/telegram-bot-api.v3" + "io/ioutil" + "log" + "os" + "strconv" +) + +type UserSession struct { + ChatId int64 `json:"chat_id"` + User tgbotapi.User `json:"user"` +} + +func getUserSessions() map[string]UserSession { + raw, err := ioutil.ReadFile("/var/www/gocode/src/github.com/user/mypromoagent/sessions.json") + if err != nil { + fmt.Println(err.Error()) + os.Exit(1) + } + + c := make(map[string]UserSession) + json.Unmarshal(raw, &c) + return c +} + +func saveUserSessions(sessions map[string]UserSession) { + j, jerr := json.MarshalIndent(sessions, "", " ") + if jerr != nil { + fmt.Println("jerr:", jerr.Error()) + } + + werr := ioutil.WriteFile("./sessions.json", j, os.ModeExclusive) + if werr != nil { + fmt.Println("werr:", werr.Error()) + } +} + +func addSession(update tgbotapi.Update) { + chatId := strconv.FormatInt(update.Message.Chat.ID, 10) + + newSession := UserSession{ + ChatId: update.Message.Chat.ID, + User: update.Message.From, + } + userSessions[chatId] = newSession + + go saveUserSessions(userSessions) + + log.Printf("new session =", newSession.ChatId) + +} diff --git a/sessions.json b/sessions.json new file mode 100644 index 0000000..dc3dc2a --- /dev/null +++ b/sessions.json @@ -0,0 +1,11 @@ +{ + "75259737": { + "chat_id": 75259737, + "user": { + "id": 75259737, + "first_name": "Владислав", + "last_name": "Савельев", + "username": "vsavel" + } + } +} \ No newline at end of file