Created
January 1, 2015 18:26
-
-
Save shinofara/f709654564c9782a7ffd to your computer and use it in GitHub Desktop.
ショッピングサイトをキーワード監視して、gmail経由で結果を送信するgo言語スクリプト
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"log" | |
"bytes" | |
"regexp" | |
"strings" | |
"net/smtp" | |
"text/template" | |
"github.com/PuerkitoBio/goquery" | |
) | |
//検索内容に関する構造 | |
type Search struct { | |
Url string | |
Keyword string | |
Title string | |
Result bool | |
} | |
//メール構造 | |
type Mail struct { | |
Subject string | |
Body string | |
To []string | |
} | |
// コンストラクタ関数を定義 | |
func NewSearch(url string, keyword string) *Search { | |
return &Search{url, keyword, "", false} | |
} | |
//スクレイピング実行 | |
func (se *Search) Run() { | |
var reg = regexp.MustCompile(se.Keyword) | |
doc, _ := goquery.NewDocument(se.Url) | |
doc.Find("body").Each(func(_ int, s *goquery.Selection) { | |
text := s.Text() | |
if reg.MatchString(text) { | |
se.Result = true | |
} | |
}) | |
se.Title = doc.Find("title").Text() | |
} | |
//メール送信用の構造体作成 | |
func NewMail(s *Search, to string) Mail { | |
status := "在庫あり" | |
if s.Result { | |
status = "在庫なし" | |
} | |
return Mail{fmt.Sprintf("[%s]%s", status, s.Title), s.Url, []string{to}} | |
} | |
//めーるそうしんー | |
func (m Mail) Send() { | |
userName := "送信元アカウント@gmail.com" | |
parameters := struct { | |
From string | |
To string | |
Subject string | |
Message string | |
}{ | |
userName, | |
strings.Join(m.To, ","), | |
m.Subject, | |
m.Body, | |
} | |
//buffer作成 | |
buffer := new(bytes.Buffer) | |
template := template.Must(template.New("emailTemplate").Parse(emailScript())) | |
template.Execute(buffer, ¶meters) | |
// Set up authentication information. | |
auth := smtp.PlainAuth( | |
"", | |
userName, | |
"Gmailのパスワード", //パスワード, | |
"smtp.gmail.com", | |
) | |
// Connect to the server, authenticate, set the sender and recipient, | |
// and send the email all in one step. | |
err := smtp.SendMail( | |
"smtp.gmail.com:587", | |
auth, | |
userName, //送信元 | |
m.To, //宛先 | |
buffer.Bytes(), | |
) | |
if err != nil { | |
log.Fatal(err) | |
} | |
} | |
func main() { | |
url := "監視するURL" | |
keyword := "ページ内で監視するワード" | |
s := NewSearch(url, keyword) | |
s.Run() | |
//メールに必要なデータ作成 | |
m := NewMail(s, "送信先") | |
//送信 | |
m.Send() | |
} | |
func emailScript() (script string) { | |
return `From: {{.From}} | |
To: {{.To}} | |
Subject: {{ .Subject }} | |
MIME-version: 1.0 | |
Content-Type: text/html; charset="UTF-8" | |
<html> | |
<a href="{{.Message}}">商品ページ</a> | |
</html>` | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment