Skip to content

Commit

Permalink
Working code
Browse files Browse the repository at this point in the history
  • Loading branch information
rmoff committed Jul 23, 2020
1 parent a2c3c5b commit 4dd479f
Show file tree
Hide file tree
Showing 5 changed files with 142 additions and 16 deletions.
3 changes: 2 additions & 1 deletion telegram-bot-carparks/.gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
kafka-connect-rest
data/connectors
data/connectors
go/telegram_token.go
17 changes: 13 additions & 4 deletions telegram-bot-carparks/go/ksqldb_pull.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package main

import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
Expand Down Expand Up @@ -40,9 +41,17 @@ func checkSpaces(c string) (emptyPlaces float64, pctFull float64, err error) {
var CURRENT_EMPTY_PLACES float64
var PCT_FULL float64
err = json.Unmarshal(body, &m)
switch len(m) {
case 0:
// This shouldn't happen…
return 0, 0, fmt.Errorf("No results (not even a header row) returned from lookup")
case 1:
// len 1 means we just got a header, no rows
return 0, 0, fmt.Errorf("No result found")
default:
CURRENT_EMPTY_PLACES = m[1].Row.Columns[0].(float64)
PCT_FULL = m[1].Row.Columns[1].(float64)
return CURRENT_EMPTY_PLACES, PCT_FULL, nil
}

CURRENT_EMPTY_PLACES = m[1].Row.Columns[0].(float64)
PCT_FULL = m[1].Row.Columns[1].(float64)

return CURRENT_EMPTY_PLACES, PCT_FULL, nil
}
12 changes: 8 additions & 4 deletions telegram-bot-carparks/go/ksqldb_push.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import (
"time"
)

func alertSpaces(c int) (err error) {
func alertSpaces(a chan<- string, c int) (e error) {
defer close(a)

// Prepare the request
url := "http://localhost:8088/query"
Expand Down Expand Up @@ -58,14 +59,17 @@ func alertSpaces(c int) (err error) {
// {"row":{"columns":["Burnett St",1595373720000,122,117]}},
// becomes
// {"row":{"columns":["Burnett St",1595373720000,122,117]}}
//
// Pretty sure instead of `ReadBytes` above I should be using
// Scanner (https://golang.org/pkg/bufio/#Scanner) to split on ASCII 44 10 13 (,CRLF)
lb = lb[:len(lb)-2]

// Convert the JSON to Go object
if strings.Contains(string(lb), "row") {
// Looks like a Row, let's process it!
err = json.Unmarshal(lb, &r)
if err != nil {
fmt.Printf("Error decoding JSON %v (%v)\n", string(lb), err)
return fmt.Errorf("error decoding JSON %v (%v)\n", string(lb), err)
} else {
if r.Row.Columns != nil {
CARPARK = r.Row.Columns[0].(string)
Expand All @@ -74,8 +78,8 @@ func alertSpaces(c int) (err error) {
CAPACITY = r.Row.Columns[3].(float64)
// Handle the timestamp
t := int64(DATA_TS)
ts := time.Unix(t/1000, 0)
fmt.Printf("Carpark %v at %v has %v spaces available (capacity %v)\n", CARPARK, ts, CURRENT_EMPTY_PLACES, CAPACITY)
ts := time.Unix(t/1000, 0).Format(time.RFC822)
a <- fmt.Sprintf("✨ 🎉 🚗 The %v carpark has %v spaces available (capacity %v)\n(data as of %v)", CARPARK, CURRENT_EMPTY_PLACES, CAPACITY, ts)
}
}
} else {
Expand Down
93 changes: 86 additions & 7 deletions telegram-bot-carparks/go/main.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package main

import "fmt"
import (
"fmt"
"log"
"strconv"

tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
)

// These are split up as when reading the chunked
// response we need to be able to assert the Row only
Expand Down Expand Up @@ -30,12 +36,85 @@ type ksqlDBMessage []struct {

func main() {

c := "Broadway"
if p, f, e := checkSpaces(c); e == nil {
fmt.Printf("Car park %v is %.2f%% full (%v spaces available)\n\n", c, f, p)
} else {
fmt.Printf("There was an error calling `checkSpaces`.\n%v\n\n", e)
var resp string
var chatID int64

// Authorise and create bot instance
bot, err := tgbotapi.NewBotAPI(TELEGRAM_API_TOKEN)
if err != nil {
log.Panic(err)
}
alertSpaces(100)
log.Printf("Authorized on account %s", bot.Self.UserName)

// TODO: Check that the bot is set up for `alert` command
// and add it if not.
// Currently hardcoded in setup process, but outline function
// has been added. Need to change it to take existing commands,
// and add the new one (rather than overwrite)

// Subscribe to updates
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates, err := bot.GetUpdatesChan(u)

// Process any messages that we're sent as they arrive
for update := range updates {
if update.Message == nil { // ignore any non-Message Updates
continue
}

chatID = update.Message.Chat.ID
t := update.Message.Text
log.Printf("[%s] %s (command: %v)", update.Message.From.UserName, t, update.Message.IsCommand())

if update.Message.IsCommand() {
// Handle commands
switch update.Message.Command() {
case "alert":
threshold := update.Message.CommandArguments()
if th, e := strconv.Atoi(threshold); e == nil {
// Use a Go Routine to invoke the population
// of the alert channel and handling the returned
// alerts
go func() {
ac := make(chan string)
go alertSpaces(ac, th)
msg := tgbotapi.NewMessage(chatID, fmt.Sprintf("👍 Successfully created alert to be sent whenever more than %v spaces are available", th))
if _, e := bot.Send(msg); e != nil {
fmt.Printf("Error sending message to telegram.\nMessage: %v\nError: %v", msg, e)
}

for a := range ac {
msg := tgbotapi.NewMessage(chatID, a)
if _, e := bot.Send(msg); e != nil {
fmt.Printf("Error sending message to telegram.\nMessage: %v\nError: %v", msg, e)
}
}
}()
} else {
msg := tgbotapi.NewMessage(chatID, "Non-integer value specified for `/alert`")
if _, e := bot.Send(msg); e != nil {
fmt.Printf("Error sending message to telegram.\nMessage: %v\nError: %v", msg, e)
}

}

default:
bot.Send(tgbotapi.NewMessage(chatID, "🤔 Command not recognised."))
}
} else {
// We've got a carpark status request
if p, f, e := checkSpaces(t); e == nil {
resp = fmt.Sprintf("ℹ️ 🚗 Car park %v is %.2f%% full (%v spaces available)\n\n", t, f, p)
} else {
resp = fmt.Sprintf("⚠️ There was an error calling `checkSpaces` for %v:\n\n%v\n\n", t, e)
}
msg := tgbotapi.NewMessage(chatID, resp)

if _, e := bot.Send(msg); e != nil {
fmt.Printf("Error sending message to telegram.\nMessage: %v\nError: %v", msg, e)
}
}

}
}
33 changes: 33 additions & 0 deletions telegram-bot-carparks/go/set_command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@

func setCommand(a string) {

// curl --location --request GET 'https://api.telegram.org/botMY_TOKEN/setMyCommands' \
// --header 'Content-Type: application/json' \
// --data-raw '{
// "commands": [
// {
// "command": "Alert",
// "description": "Define an alert to be sent if a carpark becomes available with greater than the defined number of spaces"
// }
// ]
// }'

url := "https://api.telegram.org/bot" + a + "/setMyCommands"
method := "GET"

payload := strings.NewReader("{\"commands\": [ { \"command\": \"Alert\", \"description\": \"Define an alert to be sent if a carpark becomes available with greater than the defined number of spaces\" }]}")

client := &http.Client{}
req, err := http.NewRequest(method, url, payload)

if err != nil {
fmt.Println(err)
}
req.Header.Add("Content-Type", "application/json")

res, err := client.Do(req)
defer res.Body.Close()
body, err := ioutil.ReadAll(res.Body)

fmt.Println(string(body))
}

0 comments on commit 4dd479f

Please sign in to comment.