icps

notes

Notify

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main

import (
    "fmt"
    "github.com/anaskhan96/soup"
    "io/ioutil"
    "net/http"
    "os"
    "os/exec"
    "regexp"
    "runtime"
)

var (
    path      = "/data/go/covid19/notify.txt"
    matsuhUrl = ""
    record    = readFile(path)
)

func main() {
    var content string
    doc := getDoc(matsuhUrl)
    for _, ul := range doc.FindAll("ul", "class", "newsList") {
        for _, li := range ul.FindAll("li") {
            a := li.Find("a")
            title := a.Find("p").Text()
            if regexMatch(title, "接種通知") {
                url := a.Attrs()["href"]
                date := a.Find("date").Text()
                text := getPageContent(url)
                content += (date + text)
                break
            }
        }
    }

    if record != content {
        lineMessage(content)
        saveFile(content, path)
    }

}

func getPageContent(url string) string {
    var text string
    doc2 := getDoc(url)
    for i, tag := range doc2.Find("article").Children() {
        if i <= 4 {
            for _, ta := range tag.Children() {
                text += "\n\n" + ta.FullText()
            }
        }
    }
    return text
}

func lineMessage(message string) {
    cmd := fmt.Sprintf(`/data/go/lineMessage/lineMessage me "%s"`, message)
    _, err := exec.Command("bash", "-c", cmd).Output()
    printError(err)
}

func getDoc(url string) soup.Root {
    req, err := http.NewRequest("GET", url, nil)
    printError(err)
    res, err := http.DefaultClient.Do(req)
    printError(err)
    body, err := ioutil.ReadAll(res.Body)
    printError(err)
    resp := string(body)
    return soup.HTMLParse(resp)
}

func regexMatch(str, keyword string) bool {
    match, _ := regexp.MatchString(keyword, str)
    return match
}

func readFile(path string) string {
    dat, err := ioutil.ReadFile(path)
    printError(err)
    return string(dat)
}

func saveFile(content, path string) {
    err := ioutil.WriteFile(path, []byte(content), 0644)
    printError(err)
}

func printError(err error) {
    if err != nil {
        pc, _, _, _ := runtime.Caller(1)
        fmt.Println(runtime.FuncForPC(pc).Name())
        fmt.Println(err)
    }
}

var _, _ = fmt.Println, os.Exit