forked from dghubble/go-twitter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
streaming.go
91 lines (77 loc) · 2.41 KB
/
streaming.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
package main
import (
"flag"
"fmt"
"log"
"os"
"os/signal"
"syscall"
"github.com/coreos/pkg/flagutil"
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
)
func main() {
flags := flag.NewFlagSet("user-auth", flag.ExitOnError)
consumerKey := flags.String("consumer-key", "", "Twitter Consumer Key")
consumerSecret := flags.String("consumer-secret", "", "Twitter Consumer Secret")
accessToken := flags.String("access-token", "", "Twitter Access Token")
accessSecret := flags.String("access-secret", "", "Twitter Access Secret")
flags.Parse(os.Args[1:])
flagutil.SetFlagsFromEnv(flags, "TWITTER")
if *consumerKey == "" || *consumerSecret == "" || *accessToken == "" || *accessSecret == "" {
log.Fatal("Consumer key/secret and Access token/secret required")
}
config := oauth1.NewConfig(*consumerKey, *consumerSecret)
token := oauth1.NewToken(*accessToken, *accessSecret)
// OAuth1 http.Client will automatically authorize Requests
httpClient := config.Client(oauth1.NoContext, token)
// Twitter Client
client := twitter.NewClient(httpClient)
// Convenience Demux demultiplexed stream messages
demux := twitter.NewSwitchDemux()
demux.Tweet = func(tweet *twitter.Tweet) {
fmt.Println(tweet.Text)
}
demux.DM = func(dm *twitter.DirectMessage) {
fmt.Println(dm.SenderID)
}
demux.Event = func(event *twitter.Event) {
fmt.Printf("%#v\n", event)
}
fmt.Println("Starting Stream...")
// FILTER
filterParams := &twitter.StreamFilterParams{
Track: []string{"cat"},
StallWarnings: twitter.Bool(true),
}
stream, err := client.Streams.Filter(filterParams)
if err != nil {
log.Fatal(err)
}
// USER (quick test: auth'd user likes a tweet -> event)
// userParams := &twitter.StreamUserParams{
// StallWarnings: twitter.Bool(true),
// With: "followings",
// Language: []string{"en"},
// }
// stream, err := client.Streams.User(userParams)
// if err != nil {
// log.Fatal(err)
// }
// SAMPLE
// sampleParams := &twitter.StreamSampleParams{
// StallWarnings: twitter.Bool(true),
// }
// stream, err := client.Streams.Sample(sampleParams)
// if err != nil {
// log.Fatal(err)
// }
// Receive messages until stopped or stream quits
go demux.HandleChan(stream.Messages)
// Wait for SIGINT and SIGTERM (HIT CTRL-C)
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
log.Println(<-ch)
fmt.Println("Stopping Stream...")
stream.Stop()
}