-
Notifications
You must be signed in to change notification settings - Fork 1
/
stream.go
73 lines (54 loc) · 1.5 KB
/
stream.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
package tweethog
import (
"github.com/dghubble/go-twitter/twitter"
"github.com/dghubble/oauth1"
"log"
"os"
"os/signal"
"syscall"
)
type Stream struct {
config *Config
client *twitter.Client
}
func NewStream(config *Config) *Stream {
oauth1Config := oauth1.NewConfig(config.ConsumerKey, config.ConsumerSecret)
oauth1Token := oauth1.NewToken(config.AccessToken, config.AccessSecret)
httpClient := oauth1Config.Client(oauth1.NoContext, oauth1Token)
result := &Stream{
config: config,
client: twitter.NewClient(httpClient),
}
return result
}
func (stream *Stream) GetConfig() *Config {
return stream.config
}
func (stream *Stream) Start(action func(status *Status)) error {
demux := twitter.NewSwitchDemux()
demux.Tweet = func(tweet *twitter.Tweet) {
status := NewStatus(tweet, stream)
action(status)
}
log.Println("Starting Twitter stream...")
// FILTER
filterParams := &twitter.StreamFilterParams{
Track: stream.config.Filter.Topics,
StallWarnings: twitter.Bool(true),
Language: stream.config.Filter.Languages,
}
filterStream, err := stream.client.Streams.Filter(filterParams)
if err != nil {
log.Fatal(err)
}
// Receive messages until stopped or stream quits
go demux.HandleChan(filterStream.Messages)
// Create channel for termination signal
ch := make(chan os.Signal)
signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
// Wait for SIGINT and SIGTERM (HIT CTRL-C)
log.Println(<-ch)
log.Println("Stopping Twitter stream...")
filterStream.Stop()
return nil
}