Skip to content

Instantly share code, notes, and snippets.

@ericho
Created October 27, 2016 04:56
Show Gist options
  • Save ericho/6658ac133c8d94a70947fd7643ba6781 to your computer and use it in GitHub Desktop.
Save ericho/6658ac133c8d94a70947fd7643ba6781 to your computer and use it in GitHub Desktop.
Sample telegram bot
package main
import (
"log"
"gopkg.in/telegram-bot-api.v4"
"fmt"
"database/sql"
_ "github.com/lib/pq"
)
const (
DB_USER = "USER"
DB_PASSWORD = "PASS"
DB_NAME = "DBNAME"
TOKEN = "THETOKEN"
)
func getLastTemp(db* sql.DB) (result string) {
query := `SELECT value_int FROM data_sample_raw WHERE hostname like '%board%' AND data_item LIKE '%temperature' ORDER BY time_stamp DESC LIMIT 1`
res := db.QueryRow(query)
var temp int
if err := res.Scan(&temp); err != nil {
result = fmt.Sprintf("Error scanning : %s", err)
}
result = fmt.Sprintf("Temp=%d", temp)
return
}
func getLastLight(db* sql.DB) (result string) {
query := "SELECT value_int FROM data_sample_raw WHERE hostname like '%board%' AND data_item LIKE '%light' ORDER BY time_stamp DESC LIMIT 1"
res := db.QueryRow(query)
var light int
if err := res.Scan(&light); err != nil {
result = fmt.Sprintf("Error scanning : %s", err)
}
result = fmt.Sprintf("Light=%d", light)
return
}
func getLastDistance(db* sql.DB) (result string) {
query := "SELECT value_real FROM data_sample_raw WHERE hostname like '%board%' AND data_item LIKE '%distance' ORDER BY time_stamp DESC LIMIT 1"
res := db.QueryRow(query)
var distance float64
if err := res.Scan(&distance); err != nil {
result = fmt.Sprintf("Error scanning : %s", err)
}
result = fmt.Sprintf("Dist=%f", distance)
return
}
func getDataFromDB() (result string) {
dbconnect := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable",
DB_USER, DB_PASSWORD, DB_NAME)
db, err := sql.Open("postgres", dbconnect)
defer db.Close()
if err != nil {
result = fmt.Sprintf("Error in database : %s", err)
return
}
temp := getLastTemp(db)
light := getLastLight(db)
dist := getLastDistance(db)
result = fmt.Sprintf("%s\n%s\n%s\n", light, temp, dist)
return
}
func main() {
bot, err := tgbotapi.NewBotAPI(TOKEN)
if err != nil {
panic(err)
}
bot.Debug = false
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message == nil {
continue
}
var tmp_msg string
if update.Message.Text == `/getlastmetric` {
tmp_msg = getDataFromDB()
} else {
tmp_msg = "Command not implemented"
}
msg := tgbotapi.NewMessage(update.Message.Chat.ID, tmp_msg)
bot.Send(msg)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment