Exemplo n.º 1
0
// Notify updates the authorized user's status. Returns the tweet ID on success.
func (n *Notifier) Notify(r *scuttlebutt.Repository) (*scuttlebutt.Message, error) {
	text := NotifyText(r)

	// Construct request.
	req, err := http.NewRequest("POST", "/1.1/statuses/update.json", strings.NewReader((url.Values{"status": {text}}).Encode()))
	if err != nil {
		return nil, fmt.Errorf("notify request: %s", err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	// Send request.
	resp, err := n.Client.SendRequest(req)
	if err != nil {
		return nil, fmt.Errorf("send request: %s", err)
	}
	defer resp.Body.Close()

	// Parse the response.
	var tweet twittergo.Tweet
	if err := resp.Parse(&tweet); err != nil && strings.Contains(err.Error(), "Status is over 140 characters") {
		return nil, ErrTweetTooLong
	} else if err != nil {
		return nil, fmt.Errorf("parse: %s", err)
	}

	// Update last tweet time cache.
	n.lastTweetTime = tweet.CreatedAt()

	return &scuttlebutt.Message{ID: tweet.Id(), Text: text, RepositoryID: r.ID}, nil
}
Exemplo n.º 2
0
func main() {
	var (
		err    error
		client *twittergo.Client
		tweet  *twittergo.Tweet
	)
	if client, err = LoadCredentials(); err != nil {
		fmt.Printf("Could not parse CREDENTIALS file: %v\n", err)
		os.Exit(1)
	}
	tweet_ids := []string{
		"451453919017697280",
		"451453883575848960",
		"451453847622262784",
		"451453811035357184",
		"451453775882899456",
		"451453738603909120",
		"451453703375953920",
		"451453667409817600",
		"451453613231964160",
		"451453567233040384",
		"451453517819949056",
		"451453478502539264",
		"451453436769218560",
	}

	for _, id := range tweet_ids {
		if tweet, err = GetTweet(client, id); err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		fmt.Println(tweet.Text())
	}
}
Exemplo n.º 3
0
func main() {
	// Register command-line flags.
	numWords := flag.Int("words", 17, "maximum number of words to print")
	prefixLen := flag.Int("prefix", 2, "prefix length in words")

	flag.Parse()                     // Parse command-line flags.
	rand.Seed(time.Now().UnixNano()) // Seed the random number generator.

	c := NewChain(*prefixLen)     // Initialize a new Chain.
	c.Build(os.Stdin)             // Build chains from standard input.
	text := c.Generate(*numWords) // Generate text.

	var (
		err    error
		client *twittergo.Client
		req    *http.Request
		resp   *twittergo.APIResponse
		tweet  *twittergo.Tweet
	)
	client, err = LoadCredentials()
	if err != nil {
		fmt.Printf("Could not parse CREDENTIALS file: %v\n", err)
		os.Exit(1)
	}
	data := url.Values{}
	data.Set("status", text)
	body := strings.NewReader(data.Encode())
	req, err = http.NewRequest("POST", "/1.1/statuses/update.json", body)
	if err != nil {
		fmt.Printf("Could not parse request: %v\n", err)
		os.Exit(1)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	resp, err = client.SendRequest(req)
	if err != nil {
		fmt.Printf("Could not send request: %v\n", err)
		os.Exit(1)
	}
	tweet = &twittergo.Tweet{}
	err = resp.Parse(tweet)
	if err != nil {
		if rle, ok := err.(twittergo.RateLimitError); ok {
			fmt.Printf("Rate limited, reset at %v\n", rle.Reset)
		} else if errs, ok := err.(twittergo.Errors); ok {
			for i, val := range errs.Errors() {
				fmt.Printf("Error #%v - ", i+1)
				fmt.Printf("Code: %v ", val.Code())
				fmt.Printf("Msg: %v\n", val.Message())
			}
		} else {
			fmt.Printf("Problem parsing response: %v\n", err)
		}
		os.Exit(1)
	}
	fmt.Printf("ID: %v\n", tweet.Id())
	fmt.Printf("Tweet: %v\n", tweet.Text())
}
Exemplo n.º 4
0
func Tweet(newTweet string) {
	var (
		err    error
		client *twittergo.Client
		req    *http.Request
		resp   *twittergo.APIResponse
		tweet  *twittergo.Tweet
	)

	fmt.Println("Loading credentials ...")

	client, err = LoadCredentials()
	if err != nil {
		fmt.Printf("Could not parse CREDENTIALS file: %v\n", err)
		panic(err)
	}

	data := url.Values{}
	data.Set("status", newTweet)
	body := strings.NewReader(data.Encode())
	req, err = http.NewRequest("POST", "/1.1/statuses/update.json", body)
	if err != nil {
		fmt.Printf("Could not parse request: %v\n", err)
		os.Exit(1)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	resp, err = client.SendRequest(req)
	if err != nil {
		fmt.Printf("Could not send request: %v\n", err)
		os.Exit(1)
	}
	tweet = &twittergo.Tweet{}
	err = resp.Parse(tweet)
	if err != nil {
		if rle, ok := err.(twittergo.RateLimitError); ok {
			fmt.Printf("Rate limited, reset at %v\n", rle.Reset)
		} else if errs, ok := err.(twittergo.Errors); ok {
			for i, val := range errs.Errors() {
				fmt.Printf("Error #%v - ", i+1)
				fmt.Printf("Code: %v ", val.Code())
				fmt.Printf("Msg: %v\n", val.Message())
			}
		} else {
			fmt.Printf("Problem parsing response: %v\n", err)
		}
		os.Exit(1)
	}
	fmt.Printf("ID:                   %v\n", tweet.Id())
	fmt.Printf("Tweet:                %v\n", tweet.Text())
	fmt.Printf("User:                 %v\n", tweet.User().Name())
	if resp.HasRateLimit() {
		fmt.Printf("Rate limit:           %v\n", resp.RateLimit())
		fmt.Printf("Rate limit remaining: %v\n", resp.RateLimitRemaining())
		fmt.Printf("Rate limit reset:     %v\n", resp.RateLimitReset())
	} else {
		fmt.Printf("Could not parse rate limit from response.\n")
	}
}
Exemplo n.º 5
0
func newChannelConverter(c chan *Tweet, client *twittergo.Client) func([]byte) {
	rateLimitActive := false
	timer := time.AfterFunc(10*time.Second, func() {
		rateLimitActive = false
	})
	timer.Stop()

	return func(data []byte) {
		if rateLimitActive {
			return
		}

		rateLimitActive = true
		timer.Reset(10 * time.Second)

		var tweet twittergo.Tweet
		err := json.Unmarshal(data, &tweet)
		if err != nil {
			log.Printf("Received invalid tweet: %s", err)
			return
		}

		profileImageUrl, err := getUserProfileImageURL(client, tweet.User().Id())
		if err != nil {
			log.Printf("Could not get users profile image url: %s", err)
			return
		}
		profileImage, err := getImage(profileImageUrl)
		if err != nil {
			log.Printf("Could not get users profile image: %s", err)
			return
		}
		c <- &Tweet{
			Text: tweet.Text(),
			Date: tweet.CreatedAt(),
			Author: TwitterUser{
				ScreenName:     tweet.User().ScreenName(),
				Name:           tweet.User().Name(),
				ProfilePicture: profileImage,
			},
		}
	}
}
Exemplo n.º 6
0
func main() {
	var (
		err    error
		client *twittergo.Client
		req    *http.Request
		resp   *twittergo.APIResponse
		tweet  *twittergo.Tweet
	)
	client, err = LoadCredentials()
	if err != nil {
		fmt.Printf("Could not parse CREDENTIALS file: %v\n", err)
		os.Exit(1)
	}

	body, header, err := GetBody()
	if err != nil {
		fmt.Printf("Problem loading body: %v\n", err)
		os.Exit(1)
	}

	endpoint := "/1.1/statuses/update_with_media.json"
	req, err = http.NewRequest("POST", endpoint, body)
	if err != nil {
		fmt.Printf("Could not parse request: %v\n", err)
		os.Exit(1)
	}
	req.Header.Set("Content-Type", header)

	resp, err = client.SendRequest(req)
	if err != nil {
		fmt.Printf("Could not send request: %v\n", err)
		os.Exit(1)
	}
	tweet = &twittergo.Tweet{}
	err = resp.Parse(tweet)
	if err != nil {
		fmt.Printf("Problem parsing response: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("ID:                         %v\n", tweet.Id())
	fmt.Printf("Tweet:                      %v\n", tweet.Text())
	fmt.Printf("User:                       %v\n", tweet.User().Name())
	if resp.HasRateLimit() {
		fmt.Printf("Rate limit:                 %v\n", resp.RateLimit())
		fmt.Printf("Rate limit remaining:       %v\n", resp.RateLimitRemaining())
		fmt.Printf("Rate limit reset:           %v\n", resp.RateLimitReset())
	} else {
		fmt.Printf("Could not parse rate limit from response.\n")
	}
	if resp.HasMediaRateLimit() {
		fmt.Printf("Media Rate limit:           %v\n", resp.MediaRateLimit())
		fmt.Printf("Media Rate limit remaining: %v\n", resp.MediaRateLimitRemaining())
		fmt.Printf("Media Rate limit reset:     %v\n", resp.MediaRateLimitReset())
	} else {
		fmt.Printf("Could not parse media rate limit from response.\n")
	}
}
Exemplo n.º 7
0
func (tw *RealTwitterWrapper) RespondToTweet(tweet *twittergo.Tweet, message string) {
	var (
		err  error
		user twittergo.User
		req  *http.Request
		resp *twittergo.APIResponse
	)

	user = tweet.User()
	data := url.Values{}

	// set status
	status := fmt.Sprintf("@%v %v", user.ScreenName(), message)
	data.Set("status", status)
	// set in_reply_to_status_id
	status_id := fmt.Sprintf("%d", tweet.Id())
	data.Set("in_reply_to_status_id", status_id)

	log.Printf("Set status '%v' to '%v' in reply to %v", status, user.ScreenName(), status_id)

	body := strings.NewReader(data.Encode())
	req, err = http.NewRequest("POST", "/1.1/statuses/update.json", body)
	if err != nil {
		log.Fatalf("Could not parse request: %v\n", err)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	resp, err = tw.client.SendRequest(req)
	if err != nil {
		log.Fatalf("Could not send request: %v\n", err)
	}
	tweet = &twittergo.Tweet{}
	err = resp.Parse(tweet)
	if err != nil {
		log.Fatalf("Problem parsing response: %v\n", err)
	}
}
Exemplo n.º 8
0
func main() {
	var (
		err    error
		client *twittergo.Client
		req    *http.Request
		resp   *twittergo.APIResponse
		tweet  *twittergo.Tweet
	)
	client, err = LoadCredentials()
	if err != nil {
		fmt.Printf("Could not parse CREDENTIALS file: %v\n", err)
		os.Exit(1)
	}
	data := url.Values{}
	data.Set("status", fmt.Sprintf("Fakekurrik-Fakekurrik %v", time.Now()))
	data.Set("place_id", "15cbc94209abe896")
	body := strings.NewReader(data.Encode())
	req, err = http.NewRequest("POST", "/1.1/statuses/update.json", body)
	if err != nil {
		fmt.Printf("Could not parse request: %v\n", err)
		os.Exit(1)
	}
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	resp, err = client.SendRequest(req)
	if err != nil {
		fmt.Printf("Could not send request: %v\n", err)
		os.Exit(1)
	}
	tweet = &twittergo.Tweet{}
	err = resp.Parse(tweet)
	if err != nil {
		fmt.Printf("Problem parsing response: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("ID:                   %v\n", tweet.Id())
	fmt.Printf("Tweet:                %v\n", tweet.Text())
	fmt.Printf("User:                 %v\n", tweet.User().Name())
	if resp.HasRateLimit() {
		fmt.Printf("Rate limit:           %v\n", resp.RateLimit())
		fmt.Printf("Rate limit remaining: %v\n", resp.RateLimitRemaining())
		fmt.Printf("Rate limit reset:     %v\n", resp.RateLimitReset())
	} else {
		fmt.Printf("Could not parse rate limit from response.\n")
	}
}
Exemplo n.º 9
0
func main() {
	var (
		err        error
		client     *twittergo.Client
		apiResp    *twittergo.APIResponse
		mediaResp  twittergo.MediaResponse
		mediaId    string
		mediaBytes []byte
	)
	client, err = LoadCredentials()
	if err != nil {
		fmt.Printf("Could not parse CREDENTIALS file: %v\n", err)
		os.Exit(1)
	}
	if mediaBytes, err = ioutil.ReadFile("video_upload/twitter_media_upload.mp4"); err != nil {
		fmt.Printf("Error reading media: %v\n", err)
		os.Exit(1)
	}
	if mediaResp, err = SendMediaRequest(
		client,
		"https://upload.twitter.com/1.1/media/upload.json",
		map[string]string{
			"command":     "INIT",
			"media_type":  "video/mp4",
			"total_bytes": fmt.Sprintf("%d", len(mediaBytes)),
		},
		nil,
	); err != nil {
		fmt.Printf("Problem sending INIT request: %v\n", err)
		os.Exit(1)
	}
	mediaId = fmt.Sprintf("%v", mediaResp.MediaId())
	if mediaResp, err = SendMediaRequest(
		client,
		"https://upload.twitter.com/1.1/media/upload.json",
		map[string]string{
			"command":       "APPEND",
			"media_id":      mediaId,
			"segment_index": "0",
		},
		mediaBytes,
	); err != nil {
		fmt.Printf("Problem sending APPEND request: %v\n", err)
		os.Exit(1)
	}
	if mediaResp, err = SendMediaRequest(
		client,
		"https://upload.twitter.com/1.1/media/upload.json",
		map[string]string{
			"command":  "FINALIZE",
			"media_id": mediaId,
		},
		nil,
	); err != nil {
		fmt.Printf("Problem sending FINALIZE request: %v\n", err)
		os.Exit(1)
	}
	if apiResp, err = SendApiRequest(
		client,
		"/1.1/statuses/update.json",
		map[string]string{
			"status":    fmt.Sprintf("Media! %v", time.Now()),
			"media_ids": mediaId,
		},
	); err != nil {
		fmt.Printf("Problem sending Tweet request: %v\n", err)
		os.Exit(1)
	}
	var (
		tweet *twittergo.Tweet = &twittergo.Tweet{}
	)
	if err = apiResp.Parse(tweet); err != nil {
		fmt.Printf("Problem parsing Tweet response: %v\n", err)
		os.Exit(1)
	}
	fmt.Printf("ID:                         %v\n", tweet.Id())
	fmt.Printf("Tweet:                      %v\n", tweet.Text())
	fmt.Printf("User:                       %v\n", tweet.User().Name())
	fmt.Printf("Media Id:                   %v\n", mediaResp.MediaId())
	if apiResp.HasRateLimit() {
		fmt.Printf("Rate limit:                 %v\n", apiResp.RateLimit())
		fmt.Printf("Rate limit remaining:       %v\n", apiResp.RateLimitRemaining())
		fmt.Printf("Rate limit reset:           %v\n", apiResp.RateLimitReset())
	} else {
		fmt.Printf("Could not parse rate limit from response.\n")
	}
	if apiResp.HasMediaRateLimit() {
		fmt.Printf("Media Rate limit:           %v\n", apiResp.MediaRateLimit())
		fmt.Printf("Media Rate limit remaining: %v\n", apiResp.MediaRateLimitRemaining())
		fmt.Printf("Media Rate limit reset:     %v\n", apiResp.MediaRateLimitReset())
	} else {
		fmt.Printf("Could not parse media rate limit from response.\n")
	}
}
Exemplo n.º 10
0
func (tw *FakeTwitterWrapper) RespondToTweet(tweet *twittergo.Tweet, message string) {
	fmt.Printf("Hypothetically Send tweet '%v' to '%v'\n", message, tweet.User().ScreenName())
}