Skip to content

Commit

Permalink
first commit
Browse files Browse the repository at this point in the history
  • Loading branch information
vsaveliev committed Aug 31, 2016
0 parents commit 96611f2
Show file tree
Hide file tree
Showing 5 changed files with 188 additions and 0 deletions.
Empty file added DockerFile
Empty file.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# subscription_bot
121 changes: 121 additions & 0 deletions server.go
Original file line number Diff line number Diff line change
@@ -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
}
}
}
55 changes: 55 additions & 0 deletions session.go
Original file line number Diff line number Diff line change
@@ -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)

}
11 changes: 11 additions & 0 deletions sessions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"75259737": {
"chat_id": 75259737,
"user": {
"id": 75259737,
"first_name": "Владислав",
"last_name": "Савельев",
"username": "vsavel"
}
}
}

0 comments on commit 96611f2

Please sign in to comment.