Beispiel #1
0
// 自分のTimelineを表示する。
func GetHomeTimeline(api *anaconda.TwitterApi, v url.Values) {
	tweets, err := api.GetHomeTimeline(v)
	check(err)
	for _, tweet := range tweets {
		PrintTweet(tweet)
	}
}
Beispiel #2
0
func postImageTweet(api *anaconda.TwitterApi, gifFile string, t *anaconda.Tweet) error {
	// Post

	data, err := ioutil.ReadFile(gifFile)
	if err != nil {
		return err
	}

	mediaResponse, err := api.UploadMedia(base64.StdEncoding.EncodeToString(data))
	if err != nil {
		return err
	}

	v := url.Values{}
	v.Set("media_ids", strconv.FormatInt(mediaResponse.MediaID, 10))
	v.Set("in_reply_to_status_id", t.IdStr)

	tweetString := fmt.Sprintf("@%s here are your fireworks", t.User.ScreenName)

	_, err = api.PostTweet(tweetString, v)
	if err != nil {
		return err
	} else {
		// fmt.Println(result)
	}

	return nil
}
func PublishTweet(article *Article, replyToId string, api *anaconda.TwitterApi) (string, error) {
	msg := twitterize(article)
	_, err := api.PostTweet(msg, url.Values{
		"in_reply_to_status_id": []string{replyToId},
	})
	return msg, err
}
Beispiel #4
0
// Fetch stats from Twitter and store it for display by the web interface.
func fetchStats(api *anaconda.TwitterApi) error {
	handles := strings.Join(democrats, ",") + "," + strings.Join(republicans, ",")

	users, err := api.GetUsersLookup(handles, url.Values{})
	if err != nil {
		return err
	}

	t := make([]TwitterInfo, len(users))
	for i, u := range users {
		t[i].Name = u.Name
		t[i].Image = u.ProfileImageURL
		t[i].Followers = u.FollowersCount
		t[i].Tweets = u.StatusesCount
		for _, d := range democrats {
			if u.ScreenName == d {
				t[i].Democrat = true
				break
			}
		}
	}
	sort.Sort(ByFollowers(t))
	stats.Put(t)

	return nil
}
Beispiel #5
0
// Returns a slice with twitter ids of the given user's friends
func fetchTwitterFriends(screenName string, api *anaconda.TwitterApi) ([]string, error) {
	if api == nil {
		// Let's just pretend he has no friends, because we can't actually ask
		// Twitter about it
		return []string{}, nil
	}

	v := url.Values{}
	v.Set("count", "100")
	v.Set("cursor", "-1")
	v.Set("screen_name", screenName)

	friendsIds, err := api.GetFriendsIds(v)
	if err != nil {
		return nil, err
	}

	friends, err := api.GetUsersLookupByIds(friendsIds.Ids, url.Values{})
	if err != nil {
		return nil, err
	}

	var friendsNames []string
	for _, friend := range friends {
		friendsNames = append(friendsNames, friend.ScreenName)
	}

	return friendsNames, nil
}
Beispiel #6
0
// Block a user, and tweet a notification of why they were blocked
func blockUser(tweet anaconda.Tweet, ruleName string, cfg *Config, api *anaconda.TwitterApi) {
	// Block the user from the main account
	user, err1 := api.BlockUserId(tweet.User.Id, nil)
	if err1 != nil {
		log.Fatalf("Failed to block user: %s", err1)
	}

	// Let them know via the notification account
	anaconda.SetConsumerKey(cfg.Auth2.ConsumerKey)
	anaconda.SetConsumerSecret(cfg.Auth2.ConsumerSecret)
	api2 := anaconda.NewTwitterApi(cfg.Auth2.AccessToken, cfg.Auth2.AccessTokenSecret)

	// TODO: Make this work...
	params := url.Values{}
	params.Set("InReplyToStatusID", tweet.IdStr)
	params.Set("InReplyToStatusIdStr", tweet.IdStr)

	tweet2, err2 := api2.PostTweet("@"+user.ScreenName+
		": Hi! You've been blocked by @"+cfg.Settings.MyScreenName+
		". Reason: "+cfg.Settings.ReasonsURL+"#"+ruleName, params)
	if err2 != nil {
		log.Fatalf("Failed to notify blocked user: %s", err2)
	}

	// Display tweet in terminal
	fmt.Println(">> " + tweet2.Text)

	// Restore API to main account auth settings
	anaconda.SetConsumerKey(cfg.Auth.ConsumerKey)
	anaconda.SetConsumerSecret(cfg.Auth.ConsumerSecret)
}
Beispiel #7
0
func FetchTweet(id int64, api *anaconda.TwitterApi) anaconda.Tweet {
	tweet, err := api.GetTweet(id, nil)
	if err != nil {
		panic(err)
	}
	return tweet
}
Beispiel #8
0
func checkForTweets(api anaconda.TwitterApi) error {
	searchResult, err := api.GetHomeTimeline()
	if err != nil {
		log.Print("error fetching timeline: %v", err)
		return err
	}
	//Assume that we haven't tweeted at each other more than 10 times since the last check
	//Knowing us, this is a very bad assumption.

	log.Printf("We have %d results", len(searchResult))
	//Iterate over the tweets in chronological order (the reverse order from what is returned)
	for i := len(searchResult) - 1; i >= 0; i-- {
		tweet := searchResult[i]
		if TweetMentionsATarget(tweet) {
			if err := retweetAndLog(api, tweet); err != nil {
				log.Print("error when retweeting %v", err)
				continue
			}
			log.Print(tweet.Text)
		} else {
			//log.Printf("Skipping tweet %v", tweet.Text)
		}
	}
	return nil
}
Beispiel #9
0
func twitterHandler(api *anaconda.TwitterApi) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {

		re := regexp.MustCompile("(http|ftp|https)://([\\w_-]+(?:(?:\\.[\\w_-]+)+))([\\w.,@?^=%&:/~+#-]*[\\w@?^=%&/~+#-])?")

		query := r.URL.Query().Get("q")

		v := url.Values{}
		//v.Set("f", "news")
		v.Set("lang", "en")
		v.Set("count", "100")

		result, err := api.GetSearch(query, v)
		if err != nil {
			handleWebErr(w, err)
			return
		}

		var results []string

		for _, tweet := range result.Statuses {
			results = append(results, re.ReplaceAllLiteralString(tweet.Text, ""))
		}

		msg, err := json.Marshal(results)
		if err != nil {
			handleWebErr(w, err)
			return
		}

		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, string(msg))

	}
}
Beispiel #10
0
func GenerateFireworkFor(api *anaconda.TwitterApi, t *anaconda.Tweet) error {

	checkFile := MakeGifFilename(t.User.ScreenName, t.Id)
	if Exists(checkFile) {
		fmt.Println("Already Exsists")
		return nil
	}

	v := url.Values{}
	v.Set("screen_name", t.User.ScreenName)
	v.Set("count", "30")
	search_result, err := api.GetUserTimeline(v)
	if err != nil {
		return err
	}

	gifFile, e := genTwitterGif(search_result, t.User.ScreenName, t.Id)
	if e != nil {
		return e
	}

	if *live {
		return postImageTweet(api, gifFile, t)
	} else {
		fmt.Println("Not live: ", live, t.User.ScreenName, gifFile)
	}

	return nil
}
Beispiel #11
0
func (tc *TwitterController) GetSearchStream(api *anaconda.TwitterApi, query string) chan anaconda.Tweet {
	c := make(chan anaconda.Tweet)
	go func(chanNotify chan anaconda.Tweet) {
		var since_id int64
		for {
			v := url.Values{}
			v.Set("local", "ja")
			v.Set("count", "20")
			if since_id > 0 {
				ssince_id := strconv.FormatInt(since_id, 10)
				v.Set("since_id", ssince_id)
			}
			resp, err := api.GetSearch(query, v)
			if err == nil {
				for _, status := range resp.Statuses {
					chanNotify <- status
					if status.Id > since_id {
						since_id = status.Id
					}
				}
			} else {
				log.Printf("An error occured while searching. err:%v", err)
			}
			time.Sleep(time.Second * 30)
		}
	}(c)
	return c
}
Beispiel #12
0
// 指定したユーザのTweetを表示する。
func ShowTimeline(api *anaconda.TwitterApi, v url.Values, screenName string) {
	v.Set("screen_name", screenName)
	tweets, err := api.GetUserTimeline(v)
	check(err)
	for _, tweet := range tweets {
		PrintTweet(tweet)
	}
}
Beispiel #13
0
func updateStatus(subject string, api anaconda.TwitterApi) bool {
	_, err := api.PostTweet(subject, nil)
	if err != nil {
		fmt.Println("Posting Tweet failed! Error : ", err)
		os.Exit(1)
	}
	return true
}
Beispiel #14
0
func updateTimeline(api *an.TwitterApi) []an.Tweet {
	v := url.Values{}
	home, err := api.GetHomeTimeline(v)
	if err != nil {
		fmt.Println("error: ", err)
	}
	return home
}
Beispiel #15
0
func getLatestTweets(client *anaconda.TwitterApi, screenName string, length int) (tweets []anaconda.Tweet, err error) {
	query := url.Values{}
	query.Set("screen_name", screenName)
	query.Set("count", fmt.Sprintf("%v", length))
	query.Set("trim_user", "true")
	query.Set("exclude_replies", "true")
	query.Set("include_rts", "true")
	return client.GetUserTimeline(query)
}
Beispiel #16
0
func Tweet(status string) (tweet anaconda.Tweet, err error) {
	var client *anaconda.TwitterApi
	if twitterClient != nil {
		client = twitterClient
	} else {
		client = TwitterClient()
	}
	return client.PostTweet(status, url.Values{})
}
Beispiel #17
0
func showTimeLine(api *anaconda.TwitterApi, v url.Values) {
	tweets, err := api.GetHomeTimeline(v)
	if err != nil {
		panic(err)
	}
	for _, tweet := range tweets {
		fmt.Println("tweet: ", tweet.Text)
		fmt.Println("id: ", tweet.Id)
	}
}
Beispiel #18
0
func PostTweets(api *anaconda.TwitterApi, bts []BeetTweet, db *sql.DB) {
	for _, bt := range bts {
		//TODO: Psuedo random reminder messages. For fun, and not angering the twitter api.
		_, err := api.PostTweet(fmt.Sprintf("@%s The number is %d.", bt.Name, bt.Hours), nil)

		if err == nil {
			query := fmt.Sprintf("UPDATE tweet SET NOTIFIED = true WHERE ID = %d;", bt.Id)
			db.Query(query)
		}
	}
}
Beispiel #19
0
func newTwitterStream(conf *Config, api *anaconda.TwitterApi) *anaconda.Stream {
	track, follow := conf.GetTweetFilter()

	params := url.Values{}
	params.Set("track", track)
	params.Set("follow", follow)

	stream := api.PublicStreamFilter(params)

	return stream

}
Beispiel #20
0
// Get mentions
func getMentions(mentionsCount string, api *anaconda.TwitterApi) []anaconda.Tweet {
	params := url.Values{}
	params.Set("count", mentionsCount)

	// TODO: Track tweet ID we checked up to last time, and check from there onwards

	mentions, err := api.GetMentionsTimeline(params)
	if err != nil {
		log.Fatalf("Failed to get mentions: %s", err)
	}

	return (mentions)
}
Beispiel #21
0
func twitterSearch(twitter *anaconda.TwitterApi, query string) ([]anaconda.Tweet, error) {

	v := url.Values{}
	//v.Set("f", "news")
	v.Set("lang", "en")
	v.Set("count", "100")

	result, err := twitter.GetSearch(query, v)
	if err != nil {
		return result.Statuses, err
	}
	return result.Statuses, nil
}
Beispiel #22
0
// Given config and observation, tweets latest update
func tweetCurrent(config Config, o string) {
	fmt.Println("Preparing to tweet observation...")
	var api *anaconda.TwitterApi
	api = anaconda.NewTwitterApi(config.Token, config.TokenSecret)
	anaconda.SetConsumerKey(config.ConsumerKey)
	anaconda.SetConsumerSecret(config.ConsumerSecret)
	tweet, err := api.PostTweet(o, nil)
	if err != nil {
		fmt.Println("update error:", err)
	} else {
		fmt.Println("Tweet posted:")
		fmt.Println(tweet.Text)
	}
}
Beispiel #23
0
func hydrateTweet(conf *Config, api *anaconda.TwitterApi, sseEventStream chan<- interface{}, tweetId int64) {
	t, err := api.GetTweet(tweetId, nil)
	if err != nil {
		// log here
		return
	}
	tweet, err := convertTweet(t)
	if err != nil {
		// log here
		return
	}
	conf.StoreTweet(tweet)
	sseEventStream <- tweet
}
Beispiel #24
0
// public stream 受信
func PublicStream(api *anaconda.TwitterApi) {
	stream := api.PublicStreamSample(nil)
	for {
		x := <-stream.C
		switch tweet := x.(type) {
		case anaconda.Tweet:
			PrintTweet(tweet)
		case anaconda.StatusDeletionNotice:
			// pass
		default:
			fmt.Printf("unknown type(%T) : %v \n", x, x)
		}
	}
}
Beispiel #25
0
func feedJBBS2Twitter(board *jbbsreader.Board, api *anaconda.TwitterApi) error {
	done := make(chan struct{})
	defer close(done)
	respc, errc := board.FeedNewResponses(done)
	for resp := range respc {
		log.Printf("Fetched %#v\n", resp)
		tweet, err := api.PostTweet(resp.Content, nil)
		if err != nil {
			return err
		}
		log.Printf("Sent tweet %#v\n", tweet)
	}
	return <-errc
}
Beispiel #26
0
// Authenticate is a function called for every client's new session.
// It manages several important tasks at the start of the session.
// 1.Ask the user for Username and twitter ID.
// 2.Search the DB to find the player if it's not a new one.
// 3.If the player is new there is a subsequence initiated:
// 3.1.Create a new sun with GenerateSun
// 3.2.Choose home planet from the newly created solar sysitem.
// 3.3.Create a reccord of the new player and start comunication.
func authenticate(ws *websocket.Conn) (*entities.Player, *anaconda.TwitterApi, error) {
	var (
		nickname  string
		twitterId string
		err       error
		request   Request
		setupData *entities.SetupData
		player    *entities.Player
		twitter   *anaconda.TwitterApi
	)

	if err = websocket.JSON.Receive(ws, &request); err != nil {
		return nil, nil, err
	}

	if len(request.Username) <= 0 || len(request.TwitterID) <= 0 {
		return nil, nil, errors.New("Incomplete credentials")
	}

	if cfg.Twitter.SecureLogin {
		var ok bool
		anaconda.SetConsumerKey(cfg.Twitter.ConsumerKey)
		anaconda.SetConsumerSecret(cfg.Twitter.ConsumerSecret)
		twitter = anaconda.NewTwitterApi(request.AccessToken, request.AccessTokenSecret)
		if ok, err = twitter.VerifyCredentials(); !ok {
			return nil, nil, err
		}
	}

	serverParamsMessage := response.NewServerParams()
	if err = websocket.JSON.Send(ws, &serverParamsMessage); err != nil {
		return nil, nil, err
	}

	nickname = request.Username
	twitterId = request.TwitterID

	entity, _ := entities.Get(fmt.Sprintf("player.%s", nickname))
	if entity == nil {
		setupData, err = FetchSetupData(ws)
		if err != nil {
			return nil, nil, err
		}
		player = register(setupData, nickname, twitterId, twitter)
	} else {
		player = entity.(*entities.Player)
	}
	return player, twitter, nil
}
Beispiel #27
0
func isTweeted(subject string, api anaconda.TwitterApi) bool {
	tweets, err := api.GetUserTimeline(nil)
	if err != nil {
		fmt.Println("Getting User timeline failed! Error : ", err)
		os.Exit(1)
	}
	for _, tweet := range tweets {
		fmt.Println(tweet.Text)
		fmt.Println("searching subject :" + subject)
		found := strings.Contains(tweet.Text, subject)

		if found {
			return true
		}
	}
	return false
}
Beispiel #28
0
func blockUser(user User, api *anaconda.TwitterApi) (twitterUser anaconda.User, err error) {

	// userIDが0かuserIDの長さが10でないと気はscreenNameでブロックする
	if user.id == 0 || len(user.screenName) != 10 {
		// screen_name の時
		if twitterUser, err = api.BlockUser(user.screenName, nil); err == nil {
			return twitterUser, nil
		}
	} else {

		// Id の時
		if _, err := api.BlockUserId(user.id, nil); err == nil {
			return twitterUser, nil
		}
	}

	return
}
Beispiel #29
0
func GetFollowing(api *anaconda.TwitterApi, account string) []int64 {
	v := url.Values{}
	v.Set("screen_name", account)
	v.Set("count", "5000")
	var Following []int64
	var id int64
	pages := api.GetFriendsIdsAll(v)
	counter := 0
	for page := range pages {
		//Print the current page of "Friends"
		for _, id = range page.Ids {
			counter++
			Following = append(Following, id)
			log.Debug("["+strconv.Itoa(counter)+"] Getting another Following", id)
		}
	}
	return Following
}
Beispiel #30
-1
func GetMentions(api *anaconda.TwitterApi, db *sql.DB) (retrieved_tweets []anaconda.Tweet) {
	var lastMention int64
	v := url.Values{}
	v.Add("count", "200")
	v.Add("include_rts", "1")
	err := db.QueryRow("SELECT ID FROM tweet ORDER BY ID DESC LIMIT 1;").Scan(&lastMention)

	if err == nil {
		lastMentionStr := strconv.FormatInt(lastMention, 10)
		v.Add("since_id", lastMentionStr)
	}

	retrieved_tweets, err = api.GetMentionsTimeline(v)
	iffy.PanicIf(err)
	return
}