Initialisation du dépôt

This commit is contained in:
Romain de Laage 2021-02-19 15:46:33 +01:00
commit bf2a9f8ed1
Signed by: rdelaage
GPG Key ID: 534845FADDF0C329
1 changed files with 108 additions and 0 deletions

108
bot.go Normal file
View File

@ -0,0 +1,108 @@
package main
import (
"io/ioutil"
"bytes"
//"fmt"
"log"
"net/http"
"os"
"encoding/json"
)
type Owner struct {
Id string `json:"id"`
Login string `json:"login"`
Name string `json:"name"`
Image string `json:"image"`
Deleted_at *string `json:"deleted_at,omitempty"`
In_cemetery_at *string `json:"in_cemetry_at,omitempty"`
Model string `json:"model"`
}
type VisibilityT struct {
Id string `json:"id"`
Type string `json:"type"`
Name string `json:"name"`
}
type Article struct {
Id string `json:"id"`
Title string `json:"title"`
Description string `json:"description"`
Content string `json:"content"`
Image string `json:"image,omitempty"`
Created_at string `json:"created_at"`
Owned_by Owner `json:"owned_by"`
Visibility VisibilityT `json:"visibility"`
Event *string `json:"event,omitempty"`
}
type Message struct {
Channel_id string `json:"channel_id"`
Message_content string `json:"message"`
}
func main() {
channel_id := os.Getenv("MM_ASSOS_CHANNEL")
api_token := os.Getenv("MM_ASSOS_TOKEN")
api_endpointmm := os.Getenv("MM_ASSOS_ENDPOINTMM")
api_endpointassos := os.Getenv("MM_ASSOS_ENDPOINTASSOS")
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")
os.Exit(1)
}
resp, err := http.Get(api_endpointassos)
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
if resp.StatusCode != 200 {
log.Fatalln("Error when fetching articles, server returned " + resp.Status)
os.Exit(1)
}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatalln(err)
os.Exit(1)
}
log.Printf("Successfully got articles")
var articles []Article
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)
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)
}
}
}