Now have already posted memory

This commit is contained in:
Romain de Laage 2021-02-19 17:09:09 +01:00
parent 1ce81afb81
commit 33541bdd48
Signed by: rdelaage
GPG Key ID: 534845FADDF0C329
1 changed files with 55 additions and 21 deletions

76
bot.go
View File

@ -20,6 +20,7 @@ package main
import (
"io/ioutil"
"bufio"
"bytes"
"log"
"net/http"
@ -65,9 +66,10 @@ func main() {
api_token := os.Getenv("MM_ASSOS_TOKEN")
api_endpointmm := os.Getenv("MM_ASSOS_ENDPOINTMM")
api_endpointassos := os.Getenv("MM_ASSOS_ENDPOINTASSOS")
db_path := os.Getenv("MM_ASSOS_DBPATH")
if channel_id == "" || api_token == "" || api_endpointmm == "" || api_endpointassos == "" {
log.Fatalln("MM_ASSOS_CHANNEL, MM_ASSOS_ENDPOINTMM, MM_ASSOS_ENDPOINTASSOS or MM_ASSOS_TOKEN not defined")
if channel_id == "" || api_token == "" || api_endpointmm == "" || api_endpointassos == "" || db_path == "" {
log.Fatalln("MM_ASSOS_CHANNEL, MM_ASSOS_ENDPOINTMM, MM_ASSOS_ENDPOINTASSOS, MM_ASSOS_DBPATH or MM_ASSOS_TOKEN not defined")
os.Exit(1)
}
@ -92,34 +94,66 @@ func main() {
json.Unmarshal(body, &articles)
for i := 0; i < len(articles); i++ {
var message Message
message.Channel_id = channel_id
message.Message_content = "# " + articles[i].Title + "\n" + "par *" + articles[i].Owned_by.Name + "*\n\n" + articles[i].Content
json_content, err := json.Marshal(message)
db_file, err := os.OpenFile(db_path, os.O_CREATE|os.O_RDWR, 0777)
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
req, err := http.NewRequest("POST", api_endpointmm, bytes.NewBuffer(json_content))
if err != nil {
log.Fatalln(err)
os.Exit(1)
scanner := bufio.NewScanner(db_file)
scanner.Split(bufio.ScanLines)
var entries []string
for scanner.Scan() {
entries = append(entries, scanner.Text())
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer " + api_token)
in_db := 0
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
os.Exit(1)
for _, entry := range entries {
if articles[i].Id == entry {
in_db = 1
}
}
if resp.StatusCode != 201 {
log.Fatalln("Error while posting message, server returned " + resp.Status)
os.Exit(1)
if in_db == 0 {
var message Message
message.Channel_id = channel_id
message.Message_content = "# " + articles[i].Title + "\n" + "par *" + articles[i].Owned_by.Name + "*\n\n" + articles[i].Content
json_content, err := json.Marshal(message)
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
req, err := http.NewRequest("POST", api_endpointmm, bytes.NewBuffer(json_content))
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer " + api_token)
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
if resp.StatusCode != 201 {
log.Fatalln("Error while posting message, server returned " + resp.Status)
os.Exit(1)
}
_, err = db_file.WriteString(articles[i].Id + "\n")
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
}
db_file.Close()
}
}