Skip to content

Commit

Permalink
Regularly flush store.
Browse files Browse the repository at this point in the history
  • Loading branch information
n1try committed Jul 4, 2017
1 parent 567ded3 commit f789587
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 16 deletions.
32 changes: 18 additions & 14 deletions main.go
Expand Up @@ -2,19 +2,19 @@ package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"os/signal"
"strings"
"io/ioutil"
"strconv"
"strings"
"time"

"github.com/satori/go.uuid"
)

const BOT_API_TOKEN = "<YOUR_API_TOKEN>"
const BOT_API_TOKEN = "263649871:AAFkTFZYrDhOfb718Cw_VNnXz9tH5ea8-Pk"
const BASE_URL = "https://api.telegram.org/bot"

//const BOT_API_TOKEN = ""
Expand All @@ -30,7 +30,7 @@ func sendMessage(recipientId, text string) error {
return err
}
reader := strings.NewReader(string(m))
_, err = http.Post(API_URL + "/sendMessage", "application/json", reader)
_, err = http.Post(API_URL+"/sendMessage", "application/json", reader)
if err != nil {
return err
}
Expand All @@ -44,7 +44,7 @@ func invalidateUserToken(userChatId int) {
StoreDelete(k)
}
}
}
}

func resolveToken(token string) string {
value := StoreGet(token)
Expand Down Expand Up @@ -75,13 +75,13 @@ func messageHandler(w http.ResponseWriter, r *http.Request) {
}

recipientId := resolveToken(m.RecipientToken)
if len(recipientId) == 0 {
if len(recipientId) == 0 {
w.Write([]byte("The token you passed doesn't seem to relate to a valid user."))
w.WriteHeader(404)
return
}

err = sendMessage(recipientId, "*" + m.Origin + "* wrote:\n\n" + m.Text)
err = sendMessage(recipientId, "*"+m.Origin+"* wrote:\n\n"+m.Text)
if err != nil {
w.WriteHeader(500)
return
Expand All @@ -95,7 +95,7 @@ func getUpdate() (*[]TelegramUpdate, error) {
if StoreGet(STORE_KEY_UPDATE_ID) != nil {
offset = int(StoreGet(STORE_KEY_UPDATE_ID).(float64)) + 1
}
url := API_URL + string("/getUpdates?timeout=" + strconv.Itoa(POLL_TIMEOUT_SEC) + "&offset=" + strconv.Itoa(offset))
url := API_URL + string("/getUpdates?timeout="+strconv.Itoa(POLL_TIMEOUT_SEC)+"&offset="+strconv.Itoa(offset))
log.Println("Polling for updates.")
request, _ := http.NewRequest("GET", url, nil)
client := &http.Client{Timeout: (POLL_TIMEOUT_SEC + 10) * time.Second}
Expand All @@ -117,7 +117,7 @@ func getUpdate() (*[]TelegramUpdate, error) {
}

if len(update.Result) > 0 {
var latestUpdateId interface{} = float64(update.Result[len(update.Result) - 1].UpdateId)
var latestUpdateId interface{} = float64(update.Result[len(update.Result)-1].UpdateId)
StorePut(STORE_KEY_UPDATE_ID, latestUpdateId)
}
return &update.Result, nil
Expand All @@ -127,10 +127,10 @@ func startPolling() {
for {
updates, err := getUpdate()
if err == nil {
for _, update := range (*updates) {
for _, update := range *updates {
var text string
chatId := update.Message.Chat.Id
if (strings.HasPrefix(update.Message.Text, "/start")) {
if strings.HasPrefix(update.Message.Text, "/start") {
id := uuid.NewV4().String()
invalidateUserToken(chatId)
StorePut(id, StoreObject{User: update.Message.From, ChatId: chatId})
Expand All @@ -151,16 +151,20 @@ func startPolling() {
func main() {
InitStore()
ReadStoreFromBinary(STORE_FILE)

go startPolling()
go func() {
for {
time.Sleep(30 * time.Minute)
FlushStoreToBinary(STORE_FILE)
}
}()

// Exit handler
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
signal.Notify(c, os.Kill)
go func() {
for _ = range c {
fmt.Println("Flushing store.")
FlushStoreToBinary(STORE_FILE)
os.Exit(0)
}
Expand Down
6 changes: 4 additions & 2 deletions store.go
Expand Up @@ -2,8 +2,8 @@ package main

import (
"encoding/gob"
"os"
"log"
"os"
)

var store map[string]interface{}
Expand All @@ -17,6 +17,7 @@ func initNewEmptyStore() {
}

func ReadStoreFromBinary(filePath string) {
log.Println("Loading store.")
file, err := os.Open(filePath)
defer file.Close()
if err != nil {
Expand All @@ -32,6 +33,7 @@ func ReadStoreFromBinary(filePath string) {
}

func FlushStoreToBinary(filePath string) {
log.Println("Flushing store.")
file, err := os.Create(filePath)
if err != nil {
log.Fatal(err)
Expand Down Expand Up @@ -59,4 +61,4 @@ func StoreDelete(key string) {

func StoreGetMap() map[string]interface{} {
return store
}
}

0 comments on commit f789587

Please sign in to comment.