/
main.go
94 lines (84 loc) · 2.08 KB
/
main.go
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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
twitter "github.com/0xCucu/go-twitter/v2"
"log"
"net/http"
"os"
"os/signal"
"syscall"
)
type authorize struct {
Token string
}
func (a authorize) Add(req *http.Request) {
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", a.Token))
}
/*
*
In order to run, the user will need to provide the bearer token and a file name to be used as a log.
*
*/
func main() {
token := flag.String("token", "", "twitter API token")
output := flag.String("output", "", "output")
flag.Parse()
client := &twitter.Client{
Authorizer: authorize{
Token: *token,
},
Client: http.DefaultClient,
Host: "https://api.twitter.com",
}
opts := twitter.TweetSearchStreamOpts{}
fmt.Println("Callout to tweet search stream callout")
outputFile, err := os.Create(*output)
if err != nil {
log.Panicf("tweet stream output file error %v", err)
}
defer outputFile.Close()
tweetStream, err := client.TweetSearchStream(context.Background(), opts)
if err != nil {
log.Panicf("tweet sample callout error: %v", err)
}
ch := make(chan os.Signal, 1)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM, syscall.SIGKILL)
func() {
defer tweetStream.Close()
for {
select {
case <-ch:
fmt.Println("closing")
return
case tm := <-tweetStream.Tweets():
tmb, err := json.Marshal(tm)
if err != nil {
fmt.Printf("error decoding tweet message %v", err)
}
outputFile.WriteString(fmt.Sprintf("tweet: %s\n\n", string(tmb)))
outputFile.Sync()
fmt.Println("tweet")
case sm := <-tweetStream.SystemMessages():
smb, err := json.Marshal(sm)
if err != nil {
fmt.Printf("error decoding system message %v", err)
}
outputFile.WriteString(fmt.Sprintf("system: %s\n\n", string(smb)))
outputFile.Sync()
fmt.Println("system")
case strErr := <-tweetStream.Err():
outputFile.WriteString(fmt.Sprintf("error: %v\n\n", strErr))
outputFile.Sync()
fmt.Println("error")
default:
}
if tweetStream.Connection() == false {
fmt.Println("connection lost")
return
}
}
}()
}