func (twittersource *twittersourceType) backend() { config := oauth1.NewConfig(twittersource.consumerKey, twittersource.consumerSecret) token := oauth1.NewToken(twittersource.accessToken, twittersource.accessSecret) // OAuth1 http.Client will automatically authorize Requests httpClient := config.Client(oauth1.NoContext, token) // Twitter Client client := twitter.NewClient(httpClient) // FILTER filterParams := &twitter.StreamFilterParams{ Track: twittersource.track, StallWarnings: twitter.Bool(true), } stream, err := client.Streams.Filter(filterParams) if err != nil { log.Fatal(err) } twittersource.stream = stream for evt := range stream.Messages { if tweet, ok := evt.(*twitter.Tweet); ok { data, _ := json.Marshal(tweet) var dataMap map[string]interface{} json.Unmarshal(data, &dataMap) twittersource.Manager.Emit(twittersource.ID, "out", dataMap) } } }
func main() { config.LoadConfig() dev := viper.Sub("app.development.twitter") fmt.Println(dev) fmt.Println(dev.Get("consumerKey")) consumerKey := viper.Get("app.development.twitter.consumerKey").(string) consumerSecret := viper.Get("app.development.twitter.consumerSecret").(string) tokenKey := viper.Get("app.development.twitter.token").(string) tokenSecret := viper.Get("app.development.twitter.tokenSecret").(string) config := oauth1.NewConfig(consumerKey, consumerSecret) token := oauth1.NewToken(tokenKey, tokenSecret) httpClient := config.Client(oauth1.NoContext, token) client := twitter.NewClient(httpClient) userShowParams := &twitter.UserShowParams{ScreenName: "realDonaldTrump"} user, _, _ := client.Users.Show(userShowParams) fmt.Printf("USERS SHOW:\n%v\n", user) f := new(bool) *f = false userTimelineParams := &twitter.UserTimelineParams{ScreenName: "realDonaldTrump", Count: 1, IncludeRetweets: f} tweets, _, _ := client.Timelines.UserTimeline(userTimelineParams) for tweet := range tweets { t, _ := json.MarshalIndent(tweets[tweet], "", " ") fmt.Println(string(t)) } }
func (cmd *Command) Request(sc *slack.SlashCommand) (*slack.CommandPayload, error) { // read credentials from environment variables slackAPIKey := os.Getenv("SLACK_KEY_BEATS1") consumerKey := os.Getenv("TWITTER_CONSUMER_KEY") consumerSecret := os.Getenv("TWITTER_CONSUMER_SECRET") accessToken := os.Getenv("TWITTER_ACCESS_TOKEN") accessTokenSecret := os.Getenv("TWITTER_ACCESS_TOKEN_SECRET") if slackAPIKey == "" || consumerKey == "" || consumerSecret == "" || accessToken == "" || accessTokenSecret == "" { panic("Missing required environment variable") } // Verify the request is coming from Slack if sc.Token != slackAPIKey { err := errors.New("Unauthorized Slack") return nil, err } // create payload cp := &slack.CommandPayload{ Channel: fmt.Sprintf("@%v", sc.UserName), Username: "******", Emoji: ":metal:", SlashResponse: true, SendPayload: false, } cp.Text = "Beats1" config := oauth1.NewConfig(consumerKey, consumerSecret) token := oauth1.NewToken(accessToken, accessTokenSecret) // httpClient will automatically authorize http.Request's httpClient := config.Client(token) url := fmt.Sprintf( "https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=%v&count=%v&trim_user=%v", "beats1plays", "1", "true", ) res, err := httpClient.Get(url) defer res.Body.Close() body, _ := ioutil.ReadAll(res.Body) if err != nil { return nil, err } var tweets []tweet json.Unmarshal(body, &tweets) var responseString string for _, t := range tweets { responseString += fmt.Sprint(t) } cp.Text = string(responseString) return cp, nil }
func main() { flag.Parse() if *configFile == "" { log.Fatal("missing -config") } _, err := toml.DecodeFile(*configFile, &conf) if err != nil { log.Fatalf("Could not read config: %v", err.Error()) } translateURL = translateBaseURL + "langpair=" + conf.Bot.SourceLanguage + "|" + conf.Bot.TargetLanguage + "&q=" oauthConfig := oauth1.NewConfig(conf.Twitter.ConsumerKey, conf.Twitter.ConsumerSecret) oauthToken := oauth1.NewToken(conf.Twitter.AccessKey, conf.Twitter.AccessSecret) httpClient := oauthConfig.Client(oauth1.NoContext, oauthToken) client := twitter.NewClient(httpClient) demux := twitter.NewSwitchDemux() demux.Tweet = func(tweet *twitter.Tweet) { log.Printf("Got tweet: '%v' by %v", tweet.Text, tweet.User.ScreenName) //TODO omit retweets without comment if tweet.User.ScreenName == conf.Bot.TranslatedUser && tweet.InReplyToStatusID == 0 { log.Print("Translating...") translation, err := getTranslation(tweet.Text) if err != nil { log.Printf("Translation failed: %v", err.Error()) } else { client.Statuses.Update("@"+tweet.User.Name+" "+translation, &twitter.StatusUpdateParams{InReplyToStatusID: tweet.ID}) } } } userParams := &twitter.StreamUserParams{ StallWarnings: twitter.Bool(true), With: "followings", } stream, err := client.Streams.User(userParams) if err != nil { log.Fatal(err) } go demux.HandleChan(stream.Messages) ch := make(chan os.Signal) signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM) log.Println(<-ch) fmt.Println("Stopping Stream...") stream.Stop() }
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) // Verify Credentials verifyParams := &twitter.AccountVerifyParams{ SkipStatus: twitter.Bool(true), IncludeEmail: twitter.Bool(true), } user, _, _ := client.Accounts.VerifyCredentials(verifyParams) fmt.Printf("User's ACCOUNT:\n%+v\n", user) // Home Timeline homeTimelineParams := &twitter.HomeTimelineParams{Count: 2} tweets, _, _ := client.Timelines.HomeTimeline(homeTimelineParams) fmt.Printf("User's HOME TIMELINE:\n%+v\n", tweets) // Mention Timeline mentionTimelineParams := &twitter.MentionTimelineParams{Count: 2} tweets, _, _ = client.Timelines.MentionTimeline(mentionTimelineParams) fmt.Printf("User's MENTION TIMELINE:\n%+v\n", tweets) // Retweets of Me Timeline retweetTimelineParams := &twitter.RetweetsOfMeTimelineParams{Count: 2} tweets, _, _ = client.Timelines.RetweetsOfMeTimeline(retweetTimelineParams) fmt.Printf("User's 'RETWEETS OF ME' TIMELINE:\n%+v\n", tweets) // Update (POST!) Tweet (uncomment to run) // tweet, _, _ := client.Statuses.Update("just setting up my twttr", nil) // fmt.Printf("Posted Tweet\n%v\n", tweet) }
func getRss() string { twitterConfig := oauth1.NewConfig(conf.ConsumerKey, conf.ConsumerSecret) token := oauth1.NewToken(conf.AccessToken, conf.AccessSecret) // OAuth1 http.Client will automatically authorize Requests httpClient := twitterConfig.Client(oauth1.NoContext, token) // Twitter Client client := twitter.NewClient(httpClient) // debugging & testing /*if conf.Debug { var tweetId int64 = 7654321 tweet, _, err := client.Statuses.Show(tweetId, &twitter.StatusShowParams{}) if err != nil { processAPIError("Couldn't load client.Statuses.Show: ", err) return "" } fmt.Println(parser.GetTweetUrl(*tweet)) spew.Dump(tweet) fmt.Println(parser.ParseTweetText(*tweet)) return "" }*/ // Get timeline homeTimelineParams := &twitter.HomeTimelineParams{Count: conf.MaxTweets} tweets, _, err := client.Timelines.HomeTimeline(homeTimelineParams) if err != nil { processAPIError("Couldn't load HomeTimeline: ", err) return "" } // get either single tweets or combine multiple tweets of the same author together var rssFeed *feeds.Feed if conf.CombinedFeed == false { rssFeed = feed.CreateIndividualFeed(conf, tweets) } else { rssFeed = feed.CreateCombinedUserFeed(conf, tweets) } // Create feed atom, err := rssFeed.ToAtom() if err != nil { log.Fatal(err) } return atom }
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 // What to do with each type of tweet demux := twitter.NewSwitchDemux() demux.Tweet = func(tweet *twitter.Tweet) { fmt.Println("Pedestrian Down!") fmt.Println(tweet.Text) fmt.Printf("https://twitter.com/%s/status/%s\n", tweet.User.ScreenName, tweet.IDStr) //If not @yyctransport skip if tweet.User.ID != 1729579022 { return } // Determine suffix from number number := 0 body, err := ioutil.ReadFile("/home/ubuntu/peddown/counter.txt") numberString := strings.TrimSpace(string(body)) if err != nil { fmt.Println("counter file does not exist") } else { number, err = strconv.Atoi(numberString) if err != nil { fmt.Println("not a valid string") number = 1 } } number += 1 //Convert number to byte array and save the number numberString = strconv.Itoa(number) body = []byte(numberString) ioutil.WriteFile("/home/ubuntu/peddown/counter.txt", body, 0644) suffix := "th" switch number % 10 { case 1: if (number % 100) != 11 { suffix = "st" } case 2: if (number % 100) != 12 { suffix = "nd" } case 3: if (number % 100) != 13 { suffix = "rd" } } tweetContent := fmt.Sprintf("%d%s tweeted pedestrian incident in 2016.\n#yycwalk #yyccc #ableg #visionzero\n@bmasonndp @shoffmanAB\n\nhttps://twitter.com/yyctransport/status/%s\n", number, suffix, tweet.IDStr) tweet, resp, err := client.Statuses.Update(tweetContent, nil) fmt.Println(resp) fmt.Println(err) } fmt.Println("Starting Stream...") // FILTER filterParams := &twitter.StreamFilterParams{ Track: []string{"ALERT ped,ALERT pedestrian"}, StallWarnings: twitter.Bool(true), } stream, err := client.Streams.Filter(filterParams) 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() }
func (self *Config) SingleUser(baseURL BaseURL) *Handle { config := oauth1.NewConfig(self.ConsumerKey, self.ConsumerSecret) token := oauth1.NewToken(self.AccessToken, self.AccessTokenSecret) client := config.Client(token) return &Handle{httpClient: client, baseURL: baseURL} }
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() }