├── images └── tfeel-flow.png ├── scripts ├── run.sh ├── deploy.sh ├── config.sh ├── cleanup.sh └── setup.sh ├── sql └── queries.sql ├── Makefile ├── .gitignore ├── publisher.go ├── Gopkg.toml ├── README.md ├── main.go ├── processor.go ├── provider.go ├── Gopkg.lock └── LICENSE /images/tfeel-flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mchmarny/tfeel/HEAD/images/tfeel-flow.png -------------------------------------------------------------------------------- /scripts/run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # get global vars 4 | . scripts/config.sh 5 | 6 | export GOOGLE_APPLICATION_CREDENTIALS="./service-account-key.json" 7 | 8 | ../tfeel/tfeel --query="google, gcp, bigquery, cloud" 9 | -------------------------------------------------------------------------------- /sql/queries.sql: -------------------------------------------------------------------------------- 1 | 2 | // Negative posts 3 | SELECT sum(r.score) as score_sum, t.by 4 | FROM [mchmarny-dev:tfeel.tweets] t 5 | JOIN [mchmarny-dev:tfeel.results] r on t.id = r.id 6 | WHERE r.query='XXX' AND r.score < 0 7 | GROUP BY t.by 8 | ORDER BY 1 9 | 10 | // All tweets by user 11 | SELECT t.on, r.score, t.body 12 | FROM [mchmarny-dev:tfeel.tweets] t 13 | JOIN [mchmarny-dev:tfeel.results] r on t.id = r.id 14 | WHERE r.query='XXX' AND t.by = 'XXX' 15 | ORDER BY 1 desc 16 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | # Go parameters 3 | GCP_PROJECT_NAME=s9-demo 4 | BINARY_NAME=tfeel 5 | 6 | all: test 7 | build: 8 | go build -o ./bin/$(BINARY_NAME) -v 9 | 10 | build-linux: 11 | CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -v -o ./bin/$(BINARY_NAME) 12 | 13 | test: 14 | go test -v ./... 15 | 16 | clean: 17 | go clean 18 | rm -f ./bin/$(BINARY_NAME) 19 | 20 | run: build 21 | bin/$(BINARY_NAME) 22 | 23 | deps: 24 | go get github.com/golang/dep/cmd/dep 25 | dep ensure -------------------------------------------------------------------------------- /scripts/deploy.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIR="$(dirname "$0")" 4 | . "${DIR}/config.sh" 5 | 6 | 7 | gcloud beta compute instances create "${APP_NAME}-vm" \ 8 | --project=$GCLOUD_PROJECT \ 9 | --zone=us-west1-c \ 10 | --machine-type=n1-standard-2 \ 11 | --scopes=cloud-platform \ 12 | --boot-disk-size=10GB \ 13 | --boot-disk-type=pd-ssd \ 14 | --boot-disk-device-name=tfeel-vm 15 | 16 | 17 | #gcloud compute ssh --project $GCLOUD_PROJECT --zone us-west1-c "${APP_NAME}-vm" -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled Object files, Static and Dynamic libs (Shared Objects) 2 | *.o 3 | *.a 4 | *.so 5 | 6 | # Folders 7 | _obj 8 | _test 9 | *.DS_Store 10 | 11 | # Architecture specific extensions/prefixes 12 | *.[568vq] 13 | [568vq].out 14 | 15 | *.cgo1.go 16 | *.cgo2.c 17 | _cgo_defun.c 18 | _cgo_gotypes.go 19 | _cgo_export.* 20 | 21 | _testmain.go 22 | 23 | *.exe 24 | *.test 25 | *.prof 26 | 27 | #vendor 28 | vendor 29 | 30 | # bin 31 | tfeel 32 | 33 | secrets.sh 34 | service-account.json 35 | service-account-key.json 36 | sa-key.json 37 | -------------------------------------------------------------------------------- /scripts/config.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Assumes Twitter API envirnment variables are arleady defined 4 | # export T_CONSUMER_KEY="" 5 | # export T_CONSUMER_SECRET="" 6 | # export T_ACCESS_TOKEN="" 7 | # export T_ACCESS_SECRET="" 8 | 9 | # Google 10 | export APP_NAME=$(basename "$PWD") 11 | export PUBSUB_TW_TOPIC="tweets" 12 | export PUBSUB_RZ_TOPIC="results" 13 | export PUBSUB_TW_SUB="${PUBSUB_TW_TOPIC}-events" 14 | export SERVICE_ACCOUNT_NAME="${APP_NAME}-sa" 15 | export SA_EMAIL="${SERVICE_ACCOUNT_NAME}@${GCLOUD_PROJECT}.iam.gserviceaccount.com" 16 | -------------------------------------------------------------------------------- /publisher.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "log" 7 | 8 | "cloud.google.com/go/pubsub" 9 | ) 10 | 11 | const ( 12 | topicTweets = "tweets" 13 | topicResults = "results" 14 | subTweetsEvents = "tweets-events" 15 | ) 16 | 17 | var ( 18 | tweetTopic *pubsub.Topic 19 | resultTopic *pubsub.Topic 20 | pubsubClient *pubsub.Client 21 | ) 22 | 23 | func initPublisher() { 24 | 25 | client, err := pubsub.NewClient(appContext, projectID) 26 | if err != nil { 27 | log.Panicf("Failed to create client: %v", err) 28 | } 29 | 30 | pubsubClient = client 31 | tweetTopic = client.Topic(topicTweets) 32 | resultTopic = client.Topic(topicResults) 33 | } 34 | 35 | func publish(t *pubsub.Topic, m interface{}) error { 36 | b, err := json.Marshal(m) 37 | if err != nil { 38 | return fmt.Errorf("Error while marshaling object: %v", err) 39 | } 40 | 41 | msg := &pubsub.Message{Data: b} 42 | result := t.Publish(appContext, msg) 43 | id, err := result.Get(appContext) 44 | if err != nil { 45 | return fmt.Errorf("Error while publishing message: %v:%v", err, id) 46 | } 47 | 48 | //log.Printf("Published: %v", id) 49 | 50 | return nil 51 | } 52 | -------------------------------------------------------------------------------- /Gopkg.toml: -------------------------------------------------------------------------------- 1 | # Gopkg.toml example 2 | # 3 | # Refer to https://golang.github.io/dep/docs/Gopkg.toml.html 4 | # for detailed Gopkg.toml documentation. 5 | # 6 | # required = ["github.com/user/thing/cmd/thing"] 7 | # ignored = ["github.com/user/project/pkgX", "bitbucket.org/user/project/pkgA/pkgY"] 8 | # 9 | # [[constraint]] 10 | # name = "github.com/user/project" 11 | # version = "1.0.0" 12 | # 13 | # [[constraint]] 14 | # name = "github.com/user/project2" 15 | # branch = "dev" 16 | # source = "github.com/myfork/project2" 17 | # 18 | # [[override]] 19 | # name = "github.com/x/y" 20 | # version = "2.4.0" 21 | # 22 | # [prune] 23 | # non-go = false 24 | # go-tests = true 25 | # unused-packages = true 26 | 27 | 28 | [[constraint]] 29 | name = "cloud.google.com/go" 30 | version = "0.24.0" 31 | 32 | [[constraint]] 33 | branch = "master" 34 | name = "github.com/dghubble/go-twitter" 35 | 36 | [[constraint]] 37 | name = "github.com/dghubble/oauth1" 38 | version = "0.4.0" 39 | 40 | [[constraint]] 41 | branch = "master" 42 | name = "golang.org/x/net" 43 | 44 | [[constraint]] 45 | branch = "master" 46 | name = "google.golang.org/genproto" 47 | 48 | [prune] 49 | go-tests = true 50 | unused-packages = true 51 | -------------------------------------------------------------------------------- /scripts/cleanup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIR="$(dirname "$0")" 4 | . "${DIR}/config.sh" 5 | 6 | 7 | read -p "Are you sure you want to cancel all Dataflow jobs created in this project today? [Y/n] " -n 1 -r 8 | echo # move to a new line 9 | if [[ $REPLY =~ ^[Yy]$ ]] 10 | then 11 | echo "Canceling all Dataflow jobs created today in this project..." 12 | TODAY=$(date +'%Y-%m-%d') 13 | for JOB_ID in $(gcloud beta dataflow jobs list --format='value(JOB_ID)') 14 | do 15 | JOB_DATE=$(echo ${JOB_ID}| cut -d'_' -f 1) 16 | if [ "$TODAY" == "$JOB_DATE" ] 17 | then 18 | gcloud beta dataflow jobs cancel $JOB_ID 19 | fi 20 | done 21 | fi 22 | 23 | echo "Deleting BigQuery dataset and tables..." 24 | bq rm -r -f tfeel 25 | 26 | echo "Deleting PubSub topics and subscriptions..." 27 | gcloud beta pubsub subscriptions delete $PUBSUB_TW_SUB 28 | gcloud beta pubsub topics delete $PUBSUB_TW_TOPIC 29 | gcloud beta pubsub topics delete $PUBSUB_RZ_TOPIC 30 | 31 | 32 | echo "Delete Service Account project bindings, will prompt..." 33 | # TODO: why this fails due to insufficient caller permissions? 34 | #gcloud beta iam service-accounts delete $SERVICE_ACCOUNT_NAME 35 | gcloud projects remove-iam-policy-binding ${GCLOUD_PROJECT} \ 36 | --member "serviceAccount:${SA_EMAIL}" --role roles/editor 37 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TFEEL 2 | 3 | > Personal project, does not represent Google 4 | 5 | Short for Twitter Feeling... simple sentiment analyses over tweeter data for 6 | specific terms using Google Cloud services: 7 | 8 | * [Google Container Engine](https://cloud.google.com/container-engine/) 9 | * [Google NLP API](https://cloud.google.com/natural-language/) 10 | * [Google Dataflow](https://cloud.google.com/dataflow/) 11 | * [Google Pub/Sub](https://cloud.google.com/pubsub/) 12 | 13 | ![tfeel data flow](/../master/images/tfeel-flow.png?raw=true "tfeel data flow") 14 | 15 | > All GCP services used in this example can be run under the GCP Free Tier 16 | plan. More more information see https://cloud.google.com/free/ 17 | 18 | ## Configuration 19 | 20 | Edit the `scripts/config.sh` file with your Twitter API info. Alternatively 21 | define the following environment variables. Instractions how to configure your Twitter API access codes are found [here](http://docs.inboundnow.com/guide/create-twitter-application/): 22 | 23 | ``` 24 | # export T_CONSUMER_KEY="" 25 | # export T_CONSUMER_SECRET="" 26 | # export T_ACCESS_TOKEN="" 27 | # export T_ACCESS_SECRET="" 28 | ``` 29 | 30 | ## Dependencies 31 | 32 | `tfeel` depends on a few GCP services. You can setup these servicesmanually followingthe commandsfound in the `scripts/setup.sh` file or just execute that script. This script will also configure a service account for the `tfeel` application to run under. 33 | 34 | ## Run 35 | 36 | Once all the necessary GC resources have been created (dependencies) you can execute the `tfeel` application using the `scripts/run.sh` script. 37 | 38 | ## Cleanup 39 | 40 | The cleanup of all the resources created in this application can be accomplished by executing the `scripts/cleanup.sh` script. 41 | 42 | ### TODO 43 | 44 | * Tests, yes please 45 | * Minimize account service roles (currently, project editor) 46 | -------------------------------------------------------------------------------- /main.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "log" 7 | "os" 8 | "os/signal" 9 | "strings" 10 | "sync" 11 | "syscall" 12 | 13 | "golang.org/x/net/context" 14 | ) 15 | 16 | var ( 17 | appContext context.Context 18 | projectID string 19 | queryFlag string 20 | canceling bool 21 | ) 22 | 23 | func main() { 24 | 25 | // START CONFIG 26 | flag.StringVar(&projectID, "projectID", os.Getenv("GCLOUD_PROJECT"), "GCP Project ID") 27 | flag.StringVar(&queryFlag, "query", os.Getenv("T_QUERY"), "Query args (e.g. golang, code, cloud)") 28 | flag.Parse() 29 | 30 | if projectID == "" { 31 | log.Fatal("ProjectID argument required") 32 | } 33 | 34 | if queryFlag == "" { 35 | log.Fatal("Query argument required") 36 | } 37 | queryArgs := strings.Split(queryFlag, ",") 38 | // END CONFIG 39 | 40 | ctx, cancel := context.WithCancel(context.Background()) 41 | appContext = ctx 42 | go func() { 43 | // Wait for SIGINT and SIGTERM (HIT CTRL-C) 44 | ch := make(chan os.Signal) 45 | signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) 46 | log.Println(<-ch) 47 | canceling = true 48 | cancel() 49 | os.Exit(0) 50 | }() 51 | 52 | // messages channel with some buffer 53 | messages := make(chan MiniTweet) 54 | results := make(chan ProcessResult) 55 | 56 | // initialize publsher 57 | initPublisher() 58 | 59 | // start processing 60 | go process(results) 61 | 62 | // configure ingester 63 | ingester := newIngester() 64 | err := ingester.start(queryArgs, messages) 65 | if err != nil { 66 | log.Fatal(err) 67 | } 68 | defer ingester.stop() 69 | 70 | // counter stuff 71 | var mu sync.Mutex 72 | processedCount := 0 73 | acquiredCount := 0 74 | 75 | for { 76 | select { 77 | case <-appContext.Done(): 78 | break 79 | case m := <-messages: 80 | publish(tweetTopic, m) 81 | mu.Lock() 82 | acquiredCount++ 83 | mu.Unlock() 84 | case r := <-results: 85 | publish(resultTopic, r) 86 | mu.Lock() 87 | processedCount++ 88 | fmt.Printf("\aAcquired:%d Processed:%d\n", acquiredCount, processedCount) 89 | mu.Unlock() 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /scripts/setup.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | DIR="$(dirname "$0")" 4 | . "${DIR}/config.sh" 5 | 6 | # ============================================================================== 7 | # Service Account 8 | # ============================================================================== 9 | 10 | # Set policies manualy 11 | # gcloud iam service-accounts get-iam-policy ${SA_EMAIL} --format json > policy.json 12 | # gcloud iam service-accounts set-iam-policy ${SA_EMAIL} policy.json 13 | 14 | echo "Checking if Service Account alredy created..." 15 | SA=$(gcloud beta iam service-accounts list --format='value(EMAIL)' --filter="EMAIL:${SA_EMAIL}") 16 | if [ -z "${SA}" ]; then 17 | echo "Service Account not set, creating..." 18 | gcloud beta iam service-accounts create ${SERVICE_ACCOUNT_NAME} \ 19 | --display-name="${APP_NAME} service account" 20 | 21 | echo "Creating service account key..." 22 | gcloud beta iam service-accounts keys create --iam-account $SA_EMAIL \ 23 | service-account-key.json 24 | fi 25 | 26 | echo "Creating service account bindings..." 27 | gcloud projects add-iam-policy-binding ${GCLOUD_PROJECT} \ 28 | --member "serviceAccount:${SA_EMAIL}" --role roles/editor 29 | 30 | # ============================================================================== 31 | # GCP Dependancies 32 | # ============================================================================== 33 | 34 | echo "Creating topics and subscriptions..." 35 | gcloud beta pubsub topics create ${PUBSUB_TW_TOPIC} 36 | gcloud beta pubsub topics create ${PUBSUB_RZ_TOPIC} 37 | gcloud beta pubsub subscriptions create $PUBSUB_TW_SUB \ 38 | --topic=${PUBSUB_TW_TOPIC} \ 39 | --ack-deadline=60 40 | 41 | echo "Creating BigQuery tables..." 42 | bq mk tfeel 43 | bq mk --schema query:string,id:string,on:string,by:string,body:string -t tfeel.tweets 44 | bq mk --schema id:string,score:float,parts:string -t tfeel.results 45 | 46 | 47 | # This will not succeed until 2.0 :( 48 | echo "Creating dataflow job to drain tweet topic to BigQuery..." 49 | gcloud beta dataflow jobs run ${APP_NAME}-${PUBSUB_TW_TOPIC} \ 50 | --gcs-location gs://dataflow-templates/pubsub-to-bigquery/template_file \ 51 | --parameters="topic=projects/${GCLOUD_PROJECT}/topics/${PUBSUB_TW_TOPIC}","table=${GCLOUD_PROJECT}:${APP_NAME}.${PUBSUB_TW_TOPIC}" \ 52 | --service-account-email="${SA_EMAIL}" 53 | 54 | echo "Creating dataflow job to drain result topic to BigQuery..." 55 | gcloud beta dataflow jobs run "${APP_NAME}-${PUBSUB_RZ_TOPIC}" \ 56 | --gcs-location gs://dataflow-templates/pubsub-to-bigquery/template_file \ 57 | --parameters="topic=projects/${GCLOUD_PROJECT}/topics/${PUBSUB_RZ_TOPIC}","table=${GCLOUD_PROJECT}:${APP_NAME}.${PUBSUB_RZ_TOPIC}" \ 58 | --service-account-email="${SA_EMAIL}" 59 | -------------------------------------------------------------------------------- /processor.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "log" 6 | 7 | "bytes" 8 | 9 | lang "cloud.google.com/go/language/apiv1" 10 | langpb "google.golang.org/genproto/googleapis/cloud/language/v1" 11 | 12 | "cloud.google.com/go/pubsub" 13 | 14 | "golang.org/x/net/context" 15 | ) 16 | 17 | var ( 18 | langClient *lang.Client 19 | ) 20 | 21 | // ProcessResult represents processed Message and it's content 22 | type ProcessResult struct { 23 | SourceID string `json:"id"` 24 | SentimentScore float32 `json:"score"` 25 | EntityAttributes string `json:"parts"` 26 | } 27 | 28 | func process(r chan<- ProcessResult) { 29 | 30 | // START INIT LANG API 31 | client, err := lang.NewClient(appContext) 32 | if err != nil { 33 | log.Panicf("Failed to create client: %v", err) 34 | } 35 | langClient = client 36 | // END INIT LANG API 37 | 38 | sub := pubsubClient.Subscription(subTweetsEvents) 39 | log.Printf("Subscribing: %v", sub) 40 | err = sub.Receive(appContext, func(c context.Context, m *pubsub.Message) { 41 | 42 | if canceling { 43 | log.Print("Cancel pending, skipping...") 44 | m.Nack() 45 | return 46 | } 47 | 48 | var mt MiniTweet 49 | if err := json.Unmarshal(m.Data, &mt); err != nil { 50 | log.Printf("Error while decoding tweet data: %#v", err) 51 | m.Nack() 52 | return 53 | } 54 | 55 | // score 56 | score, aErr := scoreSentiment(mt.Body) 57 | if aErr != nil { 58 | log.Printf("Error while scoring: %v", aErr) 59 | } 60 | 61 | // analyze 62 | args, eErr := analyzeEntities(mt.Body) 63 | if eErr != nil { 64 | log.Printf("Error while analyzing: %v", eErr) 65 | } 66 | 67 | result := ProcessResult{ 68 | SourceID: mt.ID, 69 | SentimentScore: score, 70 | EntityAttributes: args, 71 | } 72 | 73 | r <- result 74 | 75 | m.Ack() 76 | 77 | //log.Printf("P: %v", result.SourceID) 78 | 79 | }) 80 | 81 | if err != nil { 82 | log.Printf("Error on subscription: %v", err) 83 | } 84 | 85 | } 86 | 87 | func scoreSentiment(s string) (float32, error) { 88 | 89 | result, err := langClient.AnalyzeSentiment(appContext, &langpb.AnalyzeSentimentRequest{ 90 | Document: &langpb.Document{ 91 | Source: &langpb.Document_Content{ 92 | Content: s, 93 | }, 94 | Type: langpb.Document_PLAIN_TEXT, 95 | }, 96 | EncodingType: langpb.EncodingType_UTF8, 97 | }) 98 | if err != nil { 99 | return 0, err 100 | } 101 | return result.DocumentSentiment.Score, nil 102 | } 103 | 104 | func analyzeEntities(s string) (string, error) { 105 | result, err := langClient.AnalyzeEntities(appContext, &langpb.AnalyzeEntitiesRequest{ 106 | Document: &langpb.Document{ 107 | Source: &langpb.Document_Content{ 108 | Content: s, 109 | }, 110 | Type: langpb.Document_PLAIN_TEXT, 111 | }, 112 | EncodingType: langpb.EncodingType_UTF8, 113 | }) 114 | if err != nil { 115 | return "", err 116 | } 117 | 118 | var b bytes.Buffer 119 | for _, e := range result.Entities { 120 | b.WriteString("(" + e.Name + ":" + e.Type.String() + ") ") 121 | } 122 | return b.String(), nil 123 | } 124 | -------------------------------------------------------------------------------- /provider.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strings" 9 | "time" 10 | 11 | "github.com/dghubble/go-twitter/twitter" 12 | "github.com/dghubble/oauth1" 13 | ) 14 | 15 | const ( 16 | layoutTwitter = "Mon Jan 02 15:04:05 -0700 2006" 17 | layoutBigQuery = "2006-01-02 15:04:05" 18 | ) 19 | 20 | // MiniTweet represents simple tweet content 21 | type MiniTweet struct { 22 | Query string `json:"query"` 23 | ID string `json:"id"` 24 | On string `json:"on"` 25 | By string `json:"by"` 26 | Body string `json:"body"` 27 | } 28 | 29 | // toString returns readable string representation of the MiniTweet struct 30 | func (m *MiniTweet) toString() string { 31 | return fmt.Sprintf("ID:%v, On:%v, By:%v, Body:%v", m.ID, m.On, m.By, m.Body) 32 | } 33 | 34 | type ingester struct { 35 | stream *twitter.Stream 36 | } 37 | 38 | func newIngester() *ingester { 39 | return &ingester{} 40 | } 41 | 42 | func (i *ingester) stop() { 43 | log.Println("Stopping Ingester...") 44 | if i.stream != nil { 45 | i.stream.Stop() 46 | } 47 | } 48 | 49 | // start initiates the Tweeter stream subscription and pumps all messages into 50 | // the passed in channel 51 | func (i *ingester) start(s []string, ch chan<- MiniTweet) error { 52 | 53 | consumerKey := os.Getenv("T_CONSUMER_KEY") 54 | consumerSecret := os.Getenv("T_CONSUMER_SECRET") 55 | accessToken := os.Getenv("T_ACCESS_TOKEN") 56 | accessSecret := os.Getenv("T_ACCESS_SECRET") 57 | 58 | if consumerKey == "" || consumerSecret == "" || accessToken == "" || accessSecret == "" { 59 | return errors.New("Both, consumer key/secret and access token/secret are required") 60 | } 61 | 62 | query := strings.Join(s, ",") 63 | 64 | // init convif 65 | config := oauth1.NewConfig(consumerKey, consumerSecret) 66 | token := oauth1.NewToken(accessToken, accessSecret) 67 | 68 | // HTTP Client - will automatically authorize Requests 69 | httpClient := config.Client(oauth1.NoContext, token) 70 | client := twitter.NewClient(httpClient) 71 | demux := twitter.NewSwitchDemux() 72 | 73 | //Tweet processor 74 | demux.Tweet = func(tweet *twitter.Tweet) { 75 | 76 | tsTest, err := time.Parse(layoutTwitter, tweet.CreatedAt) 77 | if err != nil { 78 | fmt.Printf("Error formatting Twitter timestamp %v", err) 79 | } 80 | 81 | msg := MiniTweet{ 82 | Query: query, 83 | ID: tweet.IDStr, 84 | On: tsTest.Format(layoutBigQuery), 85 | By: strings.ToLower(tweet.User.ScreenName), 86 | Body: tweet.Text, 87 | } 88 | //log.Printf("I: %v", msg.ID) 89 | ch <- msg 90 | } 91 | 92 | // Tweet filter 93 | filterParams := &twitter.StreamFilterParams{ 94 | Track: s, 95 | StallWarnings: twitter.Bool(true), 96 | Language: []string{"en"}, 97 | } 98 | 99 | log.Printf("Starting Ingest For: %v\n", strings.Join(s, ",")) 100 | 101 | // Start stream 102 | stream, err := client.Streams.Filter(filterParams) 103 | if err != nil { 104 | log.Fatal(err) 105 | return err 106 | } 107 | 108 | // set local stream ref and go to work 109 | i.stream = stream 110 | go demux.HandleChan(stream.Messages) 111 | 112 | return nil 113 | 114 | } 115 | -------------------------------------------------------------------------------- /Gopkg.lock: -------------------------------------------------------------------------------- 1 | # This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'. 2 | 3 | 4 | [[projects]] 5 | name = "cloud.google.com/go" 6 | packages = [ 7 | "compute/metadata", 8 | "iam", 9 | "internal/optional", 10 | "internal/version", 11 | "language/apiv1", 12 | "pubsub", 13 | "pubsub/apiv1", 14 | "pubsub/internal/distribution" 15 | ] 16 | revision = "777200caa7fb8936aed0f12b1fd79af64cc83ec9" 17 | version = "v0.24.0" 18 | 19 | [[projects]] 20 | name = "github.com/cenkalti/backoff" 21 | packages = ["."] 22 | revision = "2ea60e5f094469f9e65adb9cd103795b73ae743e" 23 | version = "v2.0.0" 24 | 25 | [[projects]] 26 | branch = "master" 27 | name = "github.com/dghubble/go-twitter" 28 | packages = ["twitter"] 29 | revision = "b77318be397b2373226c0d80337213103b853637" 30 | 31 | [[projects]] 32 | name = "github.com/dghubble/oauth1" 33 | packages = ["."] 34 | revision = "70562a5920ad9b6ff03ef697c0f90ae569abbd2b" 35 | version = "v0.4.0" 36 | 37 | [[projects]] 38 | name = "github.com/dghubble/sling" 39 | packages = ["."] 40 | revision = "eb56e89ac5088bebb12eef3cb4b293300f43608b" 41 | version = "v1.1.0" 42 | 43 | [[projects]] 44 | name = "github.com/golang/protobuf" 45 | packages = [ 46 | "proto", 47 | "protoc-gen-go/descriptor", 48 | "ptypes", 49 | "ptypes/any", 50 | "ptypes/duration", 51 | "ptypes/empty", 52 | "ptypes/timestamp" 53 | ] 54 | revision = "b4deda0973fb4c70b50d226b1af49f3da59f5265" 55 | version = "v1.1.0" 56 | 57 | [[projects]] 58 | branch = "master" 59 | name = "github.com/google/go-querystring" 60 | packages = ["query"] 61 | revision = "53e6ce116135b80d037921a7fdd5138cf32d7a8a" 62 | 63 | [[projects]] 64 | name = "github.com/googleapis/gax-go" 65 | packages = ["."] 66 | revision = "317e0006254c44a0ac427cc52a0e083ff0b9622f" 67 | version = "v2.0.0" 68 | 69 | [[projects]] 70 | name = "go.opencensus.io" 71 | packages = [ 72 | ".", 73 | "exporter/stackdriver/propagation", 74 | "internal", 75 | "internal/tagencoding", 76 | "plugin/ocgrpc", 77 | "plugin/ochttp", 78 | "plugin/ochttp/propagation/b3", 79 | "stats", 80 | "stats/internal", 81 | "stats/view", 82 | "tag", 83 | "trace", 84 | "trace/internal", 85 | "trace/propagation" 86 | ] 87 | revision = "e262766cd0d230a1bb7c37281e345e465f19b41b" 88 | version = "v0.14.0" 89 | 90 | [[projects]] 91 | branch = "master" 92 | name = "golang.org/x/net" 93 | packages = [ 94 | "context", 95 | "context/ctxhttp", 96 | "http/httpguts", 97 | "http2", 98 | "http2/hpack", 99 | "idna", 100 | "internal/timeseries", 101 | "trace" 102 | ] 103 | revision = "039a4258aec0ad3c79b905677cceeab13b296a77" 104 | 105 | [[projects]] 106 | branch = "master" 107 | name = "golang.org/x/oauth2" 108 | packages = [ 109 | ".", 110 | "google", 111 | "internal", 112 | "jws", 113 | "jwt" 114 | ] 115 | revision = "ef147856a6ddbb60760db74283d2424e98c87bff" 116 | 117 | [[projects]] 118 | branch = "master" 119 | name = "golang.org/x/sync" 120 | packages = [ 121 | "errgroup", 122 | "semaphore" 123 | ] 124 | revision = "1d60e4601c6fd243af51cc01ddf169918a5407ca" 125 | 126 | [[projects]] 127 | name = "golang.org/x/text" 128 | packages = [ 129 | "collate", 130 | "collate/build", 131 | "internal/colltab", 132 | "internal/gen", 133 | "internal/tag", 134 | "internal/triegen", 135 | "internal/ucd", 136 | "language", 137 | "secure/bidirule", 138 | "transform", 139 | "unicode/bidi", 140 | "unicode/cldr", 141 | "unicode/norm", 142 | "unicode/rangetable" 143 | ] 144 | revision = "f21a4dfb5e38f5895301dc265a8def02365cc3d0" 145 | version = "v0.3.0" 146 | 147 | [[projects]] 148 | branch = "master" 149 | name = "google.golang.org/api" 150 | packages = [ 151 | "googleapi/transport", 152 | "internal", 153 | "iterator", 154 | "option", 155 | "support/bundler", 156 | "transport", 157 | "transport/grpc", 158 | "transport/http" 159 | ] 160 | revision = "1d2d9cc0ae74226e8076e2a87e211c8fea38a160" 161 | 162 | [[projects]] 163 | name = "google.golang.org/appengine" 164 | packages = [ 165 | ".", 166 | "internal", 167 | "internal/app_identity", 168 | "internal/base", 169 | "internal/datastore", 170 | "internal/log", 171 | "internal/modules", 172 | "internal/remote_api", 173 | "internal/socket", 174 | "internal/urlfetch", 175 | "socket", 176 | "urlfetch" 177 | ] 178 | revision = "b1f26356af11148e710935ed1ac8a7f5702c7612" 179 | version = "v1.1.0" 180 | 181 | [[projects]] 182 | branch = "master" 183 | name = "google.golang.org/genproto" 184 | packages = [ 185 | "googleapis/api/annotations", 186 | "googleapis/cloud/language/v1", 187 | "googleapis/iam/v1", 188 | "googleapis/pubsub/v1", 189 | "googleapis/rpc/status", 190 | "protobuf/field_mask" 191 | ] 192 | revision = "e92b116572682a5b432ddd840aeaba2a559eeff1" 193 | 194 | [[projects]] 195 | name = "google.golang.org/grpc" 196 | packages = [ 197 | ".", 198 | "balancer", 199 | "balancer/base", 200 | "balancer/roundrobin", 201 | "codes", 202 | "connectivity", 203 | "credentials", 204 | "credentials/oauth", 205 | "encoding", 206 | "encoding/proto", 207 | "grpclog", 208 | "internal", 209 | "internal/backoff", 210 | "internal/channelz", 211 | "internal/grpcrand", 212 | "keepalive", 213 | "metadata", 214 | "naming", 215 | "peer", 216 | "resolver", 217 | "resolver/dns", 218 | "resolver/passthrough", 219 | "stats", 220 | "status", 221 | "tap", 222 | "transport" 223 | ] 224 | revision = "168a6198bcb0ef175f7dacec0b8691fc141dc9b8" 225 | version = "v1.13.0" 226 | 227 | [solve-meta] 228 | analyzer-name = "dep" 229 | analyzer-version = 1 230 | inputs-digest = "f03425c07bb94a312bf7e200cdad6e13d53f9177577a8a1cc6ff5e70bbaa2325" 231 | solver-name = "gps-cdcl" 232 | solver-version = 1 233 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------