Пример #1
0
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))
	}
}
Пример #2
0
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)
		}
	}
}
Пример #3
0
// twitterHandler is a ContextHandler that gets the OAuth1 access token from
// the ctx and calls Twitter verify_credentials to get the corresponding User.
// If successful, the User is added to the ctx and the success handler is
// called. Otherwise, the failure handler is called.
func twitterHandler(config *oauth1.Config, success, failure ctxh.ContextHandler) ctxh.ContextHandler {
	if failure == nil {
		failure = gologin.DefaultFailureHandler
	}
	fn := func(ctx context.Context, w http.ResponseWriter, req *http.Request) {
		accessToken, accessSecret, err := oauth1Login.AccessTokenFromContext(ctx)
		if err != nil {
			ctx = gologin.WithError(ctx, err)
			failure.ServeHTTP(ctx, w, req)
			return
		}
		httpClient := config.Client(ctx, oauth1.NewToken(accessToken, accessSecret))
		twitterClient := twitter.NewClient(httpClient)
		accountVerifyParams := &twitter.AccountVerifyParams{
			IncludeEntities: twitter.Bool(false),
			SkipStatus:      twitter.Bool(true),
			IncludeEmail:    twitter.Bool(false),
		}
		user, resp, err := twitterClient.Accounts.VerifyCredentials(accountVerifyParams)
		err = validateResponse(user, resp, err)
		if err != nil {
			ctx = gologin.WithError(ctx, err)
			failure.ServeHTTP(ctx, w, req)
			return
		}
		ctx = WithUser(ctx, user)
		success.ServeHTTP(ctx, w, req)
	}
	return ctxh.ContextHandlerFunc(fn)
}
Пример #4
0
// TODO: cache the twitter api call
// TODO: implement OPTIONS
func (l LinkerssHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	log.Printf("%+v\n", req)

	// TODO: has to be a cleaner pattern than this to get an int from query params
	numTweets := l.DefaultNumTweets
	numTweetsStr := req.URL.Query().Get("numTweets")
	if numTweetsStr != "" {
		var err error
		numTweets, err = strconv.Atoi(numTweetsStr)
		if err != nil {
			w.WriteHeader(http.StatusBadRequest)
			w.Write([]byte(fmt.Sprintf("invalid numTweets %s", numTweetsStr)))
			return
		}
	}
	if numTweets > l.MaxNumTweets {
		w.WriteHeader(http.StatusBadRequest)
		w.Write([]byte(fmt.Sprintf("invalid numTweets %d, must be less than %d",
			numTweets, l.MaxNumTweets)))
		return
	}

	// set up the twitter client
	config := oauth2.Config{}
	token := oauth2.Token{AccessToken: l.AccessToken}
	httpClient := config.Client(oauth2.NoContext, &token)
	client := twitter.NewClient(httpClient)

	// fetch the timeline
	screenName := req.URL.Query().Get("screenName")
	userTimelineParams := &twitter.UserTimelineParams{
		ScreenName: screenName, Count: numTweets}
	tweets, _, err := client.Timelines.UserTimeline(userTimelineParams)
	if err != nil {
		log.Fatal("error getting user timeline: %v", err)
	}

	// filter down to just tweets with urls
	urlTweets := make([]twitter.Tweet, 0)
	for _, t := range tweets {
		if t.Entities.Urls != nil {
			urlTweets = append(urlTweets, t)
		}
	}

	// turn them into feed entries
	feed := tweetsToFeed(urlTweets, screenName, l.Pool)

	// write back to client as rss
	err = feed.WriteRss(w)
	if err != nil {
		log.Fatal("error outputting as rss: %v", err)
	}
}
Пример #5
0
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()
}
Пример #6
0
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)
}
Пример #7
0
func main() {
	flags := flag.NewFlagSet("app-auth", flag.ExitOnError)
	accessToken := flags.String("app-access-token", "", "Twitter Application Access Token")
	flags.Parse(os.Args[1:])
	flagutil.SetFlagsFromEnv(flags, "TWITTER")

	if *accessToken == "" {
		log.Fatal("Application Access Token required")
	}

	config := &oauth2.Config{}
	token := &oauth2.Token{AccessToken: *accessToken}
	// OAuth2 http.Client will automatically authorize Requests
	httpClient := config.Client(oauth2.NoContext, token)

	// Twitter client
	client := twitter.NewClient(httpClient)

	// user show
	userShowParams := &twitter.UserShowParams{ScreenName: "golang"}
	user, _, _ := client.Users.Show(userShowParams)
	fmt.Printf("USERS SHOW:\n%+v\n", user)

	// users lookup
	userLookupParams := &twitter.UserLookupParams{ScreenName: []string{"golang", "gophercon"}}
	users, _, _ := client.Users.Lookup(userLookupParams)
	fmt.Printf("USERS LOOKUP:\n%+v\n", users)

	// status show
	statusShowParams := &twitter.StatusShowParams{}
	tweet, _, _ := client.Statuses.Show(584077528026849280, statusShowParams)
	fmt.Printf("STATUSES SHOW:\n%+v\n", tweet)

	// statuses lookup
	statusLookupParams := &twitter.StatusLookupParams{ID: []int64{20}}
	tweets, _, _ := client.Statuses.Lookup([]int64{573893817000140800}, statusLookupParams)
	fmt.Printf("STATUSES LOOKUP:\n%+v\n", tweets)

	// oEmbed status
	statusOembedParams := &twitter.StatusOEmbedParams{ID: 691076766878691329, MaxWidth: 500}
	oembed, _, _ := client.Statuses.OEmbed(statusOembedParams)
	fmt.Printf("OEMBED TWEET:\n%+v\n", oembed)

	// user timeline
	userTimelineParams := &twitter.UserTimelineParams{ScreenName: "golang", Count: 2}
	tweets, _, _ = client.Timelines.UserTimeline(userTimelineParams)
	fmt.Printf("USER TIMELINE:\n%+v\n", tweets)
}
Пример #8
0
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
}
Пример #9
0
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()
}
Пример #10
0
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()
}