Example #1
0
func (t *TwitterUtil) SetLocation(e *irc.Event, txt string) {
	if txt == "" {
		t.Location = TweetLocation{}
		t.LocationMode = 0

		e.Connection.Privmsgf(e.Arguments[0], "[%s] Tweet location set to: random", e.Nick)
	} else {
		t.LocationMode = 1
		anaconda.SetConsumerKey(opt.TwitterAppKey)
		anaconda.SetConsumerSecret(opt.TwitterAppSecret)
		api := anaconda.NewTwitterApi(opt.TwitterAuthKey, opt.TwitterAuthSecret)

		vals := url.Values{}
		vals.Add("query", url.QueryEscape(txt))

		pl, ple := api.GeoSearch(vals)
		if ple == nil && len(pl.Result.Places) > 0 && len(pl.Result.Places[0].Centroid) == 2 {
			t.Location.result = pl
			t.Location.err = nil

			t.Location.lat = fmt.Sprintf("%.4f", pl.Result.Places[0].Centroid[1])
			t.Location.long = fmt.Sprintf("%.4f", pl.Result.Places[0].Centroid[0])

			e.Connection.Privmsgf(e.Arguments[0], "[%s] Tweet location set to: %s (https://www.google.com/maps?q=%s,%s)", e.Nick, pl.Result.Places[0].FullName, t.Location.lat, t.Location.long)
		} else {
			e.Connection.Privmsgf(e.Arguments[0], "[%s] Tweet location error: %s", e.Nick, ple)
		}
		api.Close()
	}
}
Example #2
0
func twitterSearch(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	query := r.URL.Query().Get("q")
	hash := r.URL.Query().Get("h")
	log.Debugf(ctx, "Twitter search", string(query))
	anaconda.SetConsumerKey("cW0kdWCjgnE8vpJGOvUxe4epL")
	anaconda.SetConsumerSecret("GEcenuc4kLzZLAfYddfC3PovRVdAu3CL3n9sc61zikH4wK2eDw")
	api := anaconda.NewTwitterApi("", "")
	api.HttpClient.Transport = &urlfetch.Transport{Context: ctx}
	v := url.Values{
		"result_type":      {"mixed"},
		"count":            {"1000"},
		"include_entities": {"false"},
	}
	if hash == "true" {
		query = "#" + query
	} else {
		query = "@" + query
	}
	searchResult, _ := api.GetSearch(url.QueryEscape(string(query)), v)
	js, err := json.Marshal(searchResult.Statuses[rand.Intn(len(searchResult.Statuses))])
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	w.Write(js)
}
Example #3
0
func Listen(cfg *string, quit chan bool) {
	creds := shared.ReadCreds(cfg)
	send_chan := make(chan anaconda.Tweet)
	conn, _ := shared.MakeConn(send_chan)
	conn.BindSendChan("tweets", send_chan)

	anaconda.SetConsumerKey(creds["consumer_key"])
	anaconda.SetConsumerSecret(creds["consumer_secret"])
	api := anaconda.NewTwitterApi(creds["access_token"], creds["access_token_secret"])

	v := url.Values{}
	//s := api.UserStream(v)
	s := api.PublicStreamSample(v)
	go func() {
		<-quit
		fmt.Print("Caught an interrupt...cleanign up")
		s.Interrupt()
		s.End()
		conn.Close()
	}()

	for {
		select {
		case o := <-s.C:
			switch twt := o.(type) {
			case anaconda.Tweet:
				send_chan <- twt
				//fmt.Printf("twt: %s\n", twt.Text)
				//spew.Dump(twt.Entities.User_mentions)
			}
		}
	}
}
Example #4
0
func main() {
	log.SetFlags(0)

	// Load ET time zone
	TZ_ET, _ = time.LoadLocation("America/New_York")

	// Init the Twitter API
	anaconda.SetConsumerKey(CONSUMER_KEY)
	anaconda.SetConsumerSecret(CONSUMER_SECRET)
	api := anaconda.NewTwitterApi(ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

	// Fetch it once
	if err := fetchStats(api); err != nil {
		log.Fatal(err)
	}

	// Start the web interface
	go startWeb()

	// Keep updating the stats every minute
	for {
		time.Sleep(time.Minute)
		fetchStats(api)
	}
}
Example #5
0
// Initialize an client library for a given user.
// This only needs to be done *once* per user
func (src *SourceTwitter) InitializeClient() *anaconda.TwitterApi {
	anaconda.SetConsumerKey(src.cfg.GetTwitterConsumerKey())
	anaconda.SetConsumerSecret(src.cfg.GetTwitterConsumerSecret())
	api := anaconda.NewTwitterApi(src.cfg.GetTwitterAccessToken(), src.cfg.GetTwitterAccessSecret())
	fmt.Println(*api.Credentials)
	return api
}
Example #6
0
func (self *Readtweets) Save(database, collection, words, limit string) bool {

	session, err := mgo.Dial("localhost")
	if err != nil {
		panic(err)
	}

	defer session.Close()
	session.SetMode(mgo.Monotonic, true)

	tweets_collection := session.DB(database).C(collection)

	anaconda.SetConsumerKey(self.consumerkey)
	anaconda.SetConsumerSecret(self.consumersecret)

	api := anaconda.NewTwitterApi(self.accesstoken, self.accessecret)

	config := url.Values{}
	config.Set("count", limit)

	search, _ := api.GetSearch(words, config)

	for _, tweet := range search {

		reg := regexp.MustCompile("<a[^>]*>(.*?)</a>")
		source := reg.FindAllStringSubmatch(tweet.Source, 1)
		real_source := source[0][1]

		media_list := []string{}
		hashtag_list := []string{}

		for _, media := range tweet.Entities.Media {
			media_list = append(media_list, media.Media_url_https)
		}

		for _, hashtag := range tweet.Entities.Hashtags {
			hashtag_list = append(hashtag_list, hashtag.Text)
		}

		t := &Tweet{
			tweet.Id,
			tweet.User.ScreenName,
			tweet.User.ProfileImageUrlHttps,
			tweet.User.FollowersCount,
			tweet.User.Lang,
			tweet.User.Location,
			tweet.InReplyToScreenName,
			real_source,
			media_list,
			hashtag_list,
			tweet.Text,
			tweet.CreatedAt,
		}

		tweets_collection.Insert(t)

	}

	return true
}
Example #7
0
func sendTweet(c context.Context, spreadsheetsID string, sheetID string, title string, path string, tags []string) error {
	sheet, error := gapps.GetSpreadsheet(c, spreadsheetsID, sheetID)
	if error != nil {
		return error
	}
	log.Infof(c, title)
	consumerKey := sheet.Table.Rows[1].C[0].V
	consumerSecret := sheet.Table.Rows[1].C[1].V
	accessToken := sheet.Table.Rows[1].C[2].V
	accessTokenSecret := sheet.Table.Rows[1].C[3].V

	tagString := ""
	for _, tag := range tags {
		tagString += " #" + tag
	}

	anaconda.SetConsumerKey(consumerKey)
	anaconda.SetConsumerSecret(consumerSecret)
	api := anaconda.NewTwitterApi(accessToken, accessTokenSecret)
	api.HttpClient.Transport = &urlfetch.Transport{Context: c}
	_, error = api.PostTweet(title+" "+path+tagString, nil)
	if error != nil {
		log.Infof(c, error.Error())
	}
	return nil
}
Example #8
0
func GetAuth() (*anaconda.TwitterApi, error) {
	file, err := os.Open("auth.json")
	if err != nil {
		return nil, err
	}
	decoder := json.NewDecoder(file)
	info := AuthInfo{}
	err = decoder.Decode(&info)
	if err != nil {
		return nil, err
	}

	anaconda.SetConsumerKey(info.ConsumerKey)
	anaconda.SetConsumerSecret(info.ConsumerSecret)
	api := anaconda.NewTwitterApi(info.Token, info.Secret)

	ok, err := api.VerifyCredentials()
	if err != nil {
		return nil, err
	}
	if !ok {
		return nil, errors.New("Invalid Credentials")
	}
	return api, nil
}
Example #9
0
func main() {
	alchemy_credentials, _ := util.GenFileHash("credentials/alchemy_credentials")
	twitter_credentials, _ := util.GenFileHash("credentials/twitter_credentials")

	anaconda.SetConsumerKey(twitter_credentials["CONSUMER_KEY"])
	anaconda.SetConsumerSecret(twitter_credentials["CONSUMER_SECRET"])
	api := anaconda.NewTwitterApi(twitter_credentials["ACCESS_TOKEN"], twitter_credentials["ACCESS_TOKEN_SECRET"])

	c := bass.NewRDB()
	countries := bass.GetCountries(c)
	for _, country := range countries {
		var sentiment_val float64
		var pos_words []string
		var neg_words []string
		searchResult, _ := api.GetSearch(country, nil)
		for _, tweet := range searchResult {
			x, y, z := alchemy.GetSentimentalWords(alchemy_credentials, tweet.Text)
			sentiment_val += x
			pos_words = append(pos_words, y...)
			neg_words = append(neg_words, z...)
		}
		bass.PushRDB(c, country, sentiment_val, pos_words, neg_words)
	}

	bass.CloseRDB(c)
}
Example #10
0
func main() {
	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")

	anaconda.SetConsumerKey(consumerKey)
	anaconda.SetConsumerSecret(consumerSecret)
	api := anaconda.NewTwitterApi(accessToken, accessTokenSecret)

	user, err := api.GetSelf(nil)
	if err != nil {
		panic(err)
	}

	fmt.Printf("Logged in as @%s\n", user.ScreenName)
	go doNotify("Twitter", "Logged in as @"+user.ScreenName, user.ProfileImageURL)

	stream := api.UserStream(nil)

	for {
		select {
		case data := <-stream.C:

			if tweet, ok := data.(anaconda.Tweet); ok {
				fmt.Printf("@%s: %s\n", tweet.User.ScreenName, tweet.Text)
				go doNotify("@"+tweet.User.ScreenName, tweet.Text, tweet.User.ProfileImageURL)
			}
		}
	}

	fmt.Println("exiting")
}
Example #11
0
func main() {

	var err error

	c, err = redis.Dial("tcp", REDIS_ADDRESS)
	if err != nil {
		panic(err)
	}
	defer c.Close()
	log.Print("Successfully dialed Redis database")

	auth_result, err := c.Do("AUTH", REDIS_PASSWORD)

	if err != nil {
		panic(err)
	}

	if auth_result == "OK" {
		log.Print("Successfully authenticated Redis database")
	}

	log.Print("Successfully created Redis database connection")

	anaconda.SetConsumerKey(TWITTER_CONSUMER_KEY)
	anaconda.SetConsumerSecret(TWITTER_CONSUMER_SECRET)
	api := anaconda.NewTwitterApi(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)

	for {
		go checkForTweets(api)
		log.Printf("Sleeping for %d seconds", SLEEP_INTERVAL)
		time.Sleep(SLEEP_INTERVAL * time.Second)
	}

}
Example #12
0
File: main.go Project: samthor/twit
func main() {
	flag.Parse()
	var v url.Values

	api := anaconda.NewTwitterApi(TWITTER_BOT_ACCESS_TOKEN, TWITTER_BOT_ACCESS_SECRET)
	mm := NewMarkovModel()

	// Fetch tweets for user, add to MM.
	v = make(url.Values)
	if *tweetsFromUser != "" {
		v.Set("screen_name", *tweetsFromUser)
		v.Set("count", fmt.Sprintf("%d", *tweetCount))
		timeline, err := api.GetUserTimeline(v)
		if err != nil {
			log.Fatalf("couldn't search, err=%v", err)
		}
		log.Printf("got %d tweets from user: %s", len(timeline), *tweetsFromUser)
		addTweets(mm, timeline)
	}

	// Fetch tweets matching search term, add to MM.
	if *searchTerm != "" {
		v = make(url.Values)
		v.Set("count", fmt.Sprintf("%d", *tweetCount))
		searchResult, err := api.GetSearch(*searchTerm, v)
		if err != nil {
			log.Fatalf("couldn't search, err=%v", err)
		}
		log.Printf("got %d tweets from search: %s", len(searchResult.Statuses), *searchTerm)
		addTweets(mm, searchResult.Statuses)
	}

	// Build actual tweet line.
	var tweetWords []string
	var safeCount int
	for len(tweetWords) < 20 && safeCount < 20 {
		tweetWords = mm.Generate(25)
		safeCount++
	}
	tweetLine := strings.Join(tweetWords, " ")

	// Insert searchTerm, if not already there (yes, this might cause a loop..).
	if !strings.Contains(tweetLine, *searchTerm) {
		tweetLine = fmt.Sprintf("%s %s", *searchTerm, tweetLine)
	}

	tweetLine = TrimLine(tweetLine, TWITTER_MAX)

	// Post!
	if *post && tweetLine != "" {
		v = make(url.Values)
		_, err := api.PostTweet(tweetLine, v)
		if err != nil {
			log.Fatalf("couldn't tweet, err=%v", err)
		}
		log.Printf("tweet ok, was: %v", tweetLine)
	} else {
		log.Printf("didn't tweet, would be: %v", tweetLine)
	}
}
Example #13
0
func NewStream(name string) (*Stream, error) {
	anaconda.SetConsumerKey(consumer_key)
	anaconda.SetConsumerSecret(consumer_secret)

	api := anaconda.NewTwitterApi(access_token, access_token_secret)
	api.SetLogger(anaconda.BasicLogger)
	api.ReturnRateLimitError(true)

	api.Log.Debugf("Fetching user %s...", name)
	u, err := api.GetUsersShow(name, nil)
	if err != nil {
		return nil, errwrap.Wrapf(fmt.Sprintf("Failed to getUserShow() for %s: {{err}}", name), err)
	}
	api.Log.Debugf("Found user with id %d", u.Id)

	vals := url.Values{}
	vals.Set("follow", strconv.FormatInt(u.Id, 10))

	return &Stream{
		api:        api,
		fstream:    api.PublicStreamFilter(vals),
		user:       u,
		events:     make(chan Event),
		vulnerable: map[int64]*Vulnerable{},
	}, nil
}
Example #14
0
func (t *TwitterUtil) SendTweetResponse(e *irc.Event, q string, tid string) {
	anaconda.SetConsumerKey(opt.TwitterAppKey)
	anaconda.SetConsumerSecret(opt.TwitterAppSecret)
	api := anaconda.NewTwitterApi(opt.TwitterAuthKey, opt.TwitterAuthSecret)

	vals := url.Values{}

	pl := t.GetLoc(api)
	if pl.err == nil {
		vals.Add("lat", pl.lat)
		vals.Add("long", pl.long)
		vals.Add("place_id", pl.result.Result.Places[0].ID)
	}

	vals.Add("in_reply_to_status_id", tid)

	tm, twe := t.GetNewTweetMedia(q)
	if tm.MediaID != 0 {
		vals.Add("media_ids", tm.MediaIDString)
	}
	tw, ter := api.PostTweet(twe, vals)
	if ter == nil {
		e.Connection.Privmsgf(e.Arguments[0], "[%s] Tweet sent [ https://twitter.com/%s/status/%s ]", e.Nick, tw.User.ScreenName, tw.IdStr)
	} else {
		e.Connection.Privmsgf(e.Arguments[0], "[%s] Tweet send failed: %s", e.Nick, ter)
	}

	api.Close()
}
Example #15
0
func main() {
	at := os.Getenv("ACCESSTOKEN")
	as := os.Getenv("ACCESSSECRET")

	if at == "" || as == "" {
		panic("Cannot have empty API key/secret/token")
	}

	api := anaconda.NewTwitterApi(at, as)

	api.EnableThrottling(5*time.Minute, 100)
	api.SetDelay(5 * time.Minute)

	ticker := time.NewTicker(6 * time.Hour)
	quit := make(chan struct{})

	var wg sync.WaitGroup
	wg.Add(1)
	go func() {
		for {
			select {
			case <-ticker.C:
				fmt.Println("collecting images")
				CollectImages(api)
			case <-quit:
				ticker.Stop()
				return
			}
		}
	}()
	wg.Wait()
}
Example #16
0
func main() {
	sigCh := make(chan os.Signal, 1)
	signal.Notify(sigCh,
		syscall.SIGTERM,
		syscall.SIGINT)

	api := anaconda.NewTwitterApi(c.AccessToken, c.AccessTokenSecret)

	c := cron.New()
	c.AddFunc("0 0 7 * * *", func() {
		log.Print("**** START ****")

		f := weather.GetWeatherForecast()
		if needUmbrella(f) {
			m := USER + " 傘持って行ってね♡"
			tweet, _ := api.PostTweet(m, nil)
			log.Print(tweet.Text)
		}

		log.Print("**** END ****")
	})
	c.Start()

	select {
	case s := <-sigCh:
		log.Printf("Recv: %v\n", s)
		os.Exit(0)
	}
}
func main() {
	log.Print("Running updated version")
	anaconda.SetConsumerKey(TWITTER_CONSUMER_KEY)
	anaconda.SetConsumerSecret(TWITTER_CONSUMER_SECRET)
	api := anaconda.NewTwitterApi(TWITTER_ACCESS_TOKEN, TWITTER_ACCESS_TOKEN_SECRET)

	d := 60 * time.Second
	api.EnableThrottling(d, 4)
	api.SetLogger(anaconda.BasicLogger)

	log.Printf("Rate limiting with a token added every %s", d.String())

	followers_pages := api.GetFollowersListAll(nil)

	i := 0
	for page := range followers_pages {
		if page.Error != nil {
			log.Printf("ERROR: received error from GetFollowersListAll: %s", page.Error)
		}

		followers := page.Followers
		for _, follower := range followers {
			fmt.Printf("%+v\n", follower.ScreenName)
		}
		i++
	}
	log.Printf("Finished logging all %d followers -- exiting", i)
}
Example #18
0
// newStreamManager creates new stream manager with the provided TwitterManagerConfig
func newStreamManager(config TwitterManagerConfig) *StreamManager {
	anaconda.SetConsumerKey(config.ConsumerKey)
	anaconda.SetConsumerSecret(config.ConsumerSecret)
	api := anaconda.NewTwitterApi(config.AccessToken, config.AccessTokenSecret)

	return &StreamManager{config, api}
}
Example #19
0
func GetTwitter(conf *config.Configuration) *anaconda.TwitterApi {

	anaconda.SetConsumerKey(conf.TwitterConsumerKey)
	anaconda.SetConsumerSecret(conf.TwitterConsumerSecret)
	api := anaconda.NewTwitterApi(conf.TwitterAccessToken, conf.TwitterAccessTokenSecret)
	return api
}
Example #20
0
func main() {
	var apiConf ApiConf
	{
		// コマンドラインからフラグ付きで渡す
		apiConfPath := flag.String("conf", "config.json", "API Config File")
		flag.Parse()
		data, err_file := ioutil.ReadFile(*apiConfPath)
		check(err_file)
		err_json := json.Unmarshal(data, &apiConf)
		check(err_json)
	}

	anaconda.SetConsumerKey(apiConf.ConsumerKey)
	anaconda.SetConsumerSecret(apiConf.ConsumerSecret)
	api := anaconda.NewTwitterApi(apiConf.AccessToken, apiConf.AccessTokenSecret)

	twitterStream := api.PublicStreamSample(nil)
	for {
		x := <-twitterStream.C
		switch tweet := x.(type) {
		case anaconda.Tweet:
			fmt.Println(tweet.Text)
			fmt.Println("-------")
		case anaconda.StatusDeletionNotice:
			// pass
		default:
			fmt.Printf("unknown type(%T) : %v \n", x, x)
		}
	}
}
Example #21
0
func Tweets(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	if len(creds) <= 4 {
		credentials, err := loadKeys()

		if err != nil {
			http.Error(w, err.Error(), 500)
		}

		creds = credentials
	}

	anaconda.SetConsumerKey(creds["ConsumerKey"])
	anaconda.SetConsumerSecret(creds["ConsumerSecret"])
	api := anaconda.NewTwitterApi(creds["AccessToken"], creds["AccessSecret"])

	searchResult, err := api.GetSearch("rlrbatcave", nil)
	tweets := searchResult.Statuses
	if err != nil {
		http.Error(w, err.Error(), 500)
	}

	json, err := json.Marshal(tweets)
	if err != nil {
		http.Error(w, err.Error(), 500)
	}

	fmt.Fprintf(w, "%s", string(json))
}
//getTweets gets all tweets from twitter with the speified keyword
func (tr TweetRetriever) getTweets(query string,
	cutoff time.Time,
	wg *sync.WaitGroup) {

	defer wg.Done()

	log.Infof(tr.context, "Downloading Tweets.")
	anaconda.SetConsumerKey(consumerKey)
	anaconda.SetConsumerSecret(consumerSecretKey)

	api := anaconda.NewTwitterApi(accessToken, accessTokenSecret)

	api.HttpClient.Transport = &urlfetch.Transport{Context: tr.context}

	result, err := api.GetSearch(query, nil)

	if err != nil {
		log.Errorf(tr.context, "Harvester- getTweets: %v", err.Error())
		return
	}
	cont := true

	for cont {
		cont = tr.addIfNewerThan(cutoff, result)
		cont = false
		if cont {
			result, err = result.GetNext(api)
			//log.Infof(c, "Getting more tweets!")
			if err != nil {
				log.Errorf(tr.context, "Harvester- getTweets: %v", err.Error())
			}
		}
	}
	close(tr.out)
}
Example #23
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)
}
Example #24
0
func main() {
	// устанавливаем соединение
	port, err := sio.Open("/dev/ttyACM0", syscall.B9600)
	if err != nil {
		log.Fatal(err)
	}

	time.Sleep(2 * time.Second)

	anaconda.SetConsumerKey(consumerKey)
	anaconda.SetConsumerSecret(consumerSecret)
	api := anaconda.NewTwitterApi(key, secretKey)
	var twitt string
	var searchResult []anaconda.Tweet

	for {

		searchResult, _ = api.GetSearch("#golang", nil)
		twitt = " -- " + searchResult[0].Text
		fmt.Println(twitt)

		// отправляем данные
		_, err = port.Write([]byte(twitt))
		if err != nil {
			log.Fatal(err)
		}

		time.Sleep(120 * time.Second)
	}
}
Example #25
0
func authCallbackHandler(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	c := NewTwitterClient(ctx)
	token := r.FormValue("oauth_token")
	verificationCode := r.FormValue("oauth_verifier")
	log.Debugf(ctx, "oauth_token:%v oauth_verifier:%v", token, verificationCode)
	requestToken := FindRequest(ctx, token)
	if requestToken == nil {
		fmt.Fprint(w, "token not found")
		w.WriteHeader(500)
		return
	}
	accessToken, err := c.AuthorizeToken(requestToken, verificationCode)
	if err != nil {
		fmt.Fprint(w, err)
		w.WriteHeader(500)
		return
	}
	fmt.Fprintln(w, accessToken.AdditionalData)
	api := anaconda.NewTwitterApi(accessToken.Token, accessToken.Secret)
	api.HttpClient = urlfetch.Client(ctx)
	ok, err := api.VerifyCredentials()
	if err != nil {
		fmt.Fprint(w, err)
		w.WriteHeader(500)
		return
	}
	fmt.Fprintln(w, ok)
}
Example #26
0
func main() {
	// Initialise boltdb
	db, err := bolt.Open("friends.db", 0600, &bolt.Options{Timeout: 1 * time.Second})
	if err != nil {
		log.Fatal(err)
	}
	defer db.Close()

	// setup twitter api
	ana.SetConsumerKey("Uub6rxnlkmCuf7WW4Xg0HDPJs")
	ana.SetConsumerSecret("5efz1p3T33kIrRIiBN6FiiabJ8DB21OhzGAefWLVPTzornlcuW")
	api := ana.NewTwitterApi("1409403655-9pFsvIJ3frI4g4jJQBqYDZ8GMflKkjDcpdSkHwZ", "0c5zM4fmtIuLVn2eg6wVxD6cYBWlG62FQNfylCrc6yZuh")

	va := url.Values{}
	va.Set("count", "5000")
	friends, _ := api.GetFriendsIds(va)

	// write data to boltdb
	for key, value := range friends.Ids {
		k := []byte(strconv.Itoa(key))
		v := []byte(strconv.FormatInt(value, 16))
		err = db.Update(func(tx *bolt.Tx) error {
			bucket, err := tx.CreateBucketIfNotExists(twitterfriends)
			if err != nil {
				return err
			}

			err = bucket.Put(k, v)
			if err != nil {
				return err
			}
			return nil

		})
	}

	if err != nil {
		log.Fatal(err)
	}

	// retrieve data from boltdb
	err = db.View(func(tx *bolt.Tx) error {
		bucket := tx.Bucket(twitterfriends)
		if bucket == nil {
			return fmt.Errorf("Bucket %q not found!", twitterfriends)
		}

		for key := range friends.Ids {
			val := bucket.Get([]byte(strconv.Itoa(key)))
			fmt.Println(string(val))
		}

		return nil
	})

	if err != nil {
		log.Fatal(err)
	}

}
Example #27
0
func sendTweet(c context.Context, title string, path string, tags []string) error {
	spreadsheetsID := "1Vk83CXQacadLSBgguE9UJ1_l5_qX072cmy4ieiwh7HU"
	sheetID := "1373105893"
	sheet, err := gapps.GetSpreadsheet(c, spreadsheetsID, sheetID)
	if err != nil {
		return err
	}
	log.Infof(c, title)
	consumerKey := sheet.Table.Rows[1].C[0].V
	consumerSecret := sheet.Table.Rows[1].C[1].V
	accessToken := sheet.Table.Rows[1].C[2].V
	accessTokenSecret := sheet.Table.Rows[1].C[3].V

	tagString := ""
	for _, tag := range tags {
		if strings.HasPrefix(tag, "@") {
			tagString += " " + tag
		} else {
			tagString += " #" + tag
		}
	}

	anaconda.SetConsumerKey(consumerKey)
	anaconda.SetConsumerSecret(consumerSecret)
	api := anaconda.NewTwitterApi(accessToken, accessTokenSecret)
	api.HttpClient.Transport = &urlfetch.Transport{Context: c}
	_, err = api.PostTweet(title+" "+path+tagString, nil)
	if err != nil {
		log.Infof(c, err.Error())
	}

	return nil
}
Example #28
0
//getFriendsAsUsers returns twitter friends as a slice of users sorted by User ID
func getFriendsAsUsers() []User {
	anaconda.SetConsumerKey(conf.TwitterConsumerKey)
	anaconda.SetConsumerSecret(conf.TwitterConsumerSecret)
	api := anaconda.NewTwitterApi(conf.TwitterAccessToken, conf.TwitterAccessTokenSecret)
	result := make(chan anaconda.UserCursor, 1000000) //YOLO

	logger.Println("getting friends")

	v := url.Values{}
	v.Set("screen_name", conf.TwitterScreenName)
	getFriends(api, result, v)

	logger.Println("got em")

	users := []User{}

	for uc := range result {
		for _, u := range uc.Users {
			users = append(users, User{u.Id, u.Name, u.ScreenName, u.Description, u.Location})
		}
	}

	sort.Sort(ById(users))
	return users
}
Example #29
0
func getTweetFromAPI(sinceID string) (tweets []Tweet, err error) {
	api := anaconda.NewTwitterApi(os.Getenv("ACCESS_TOKEN"), os.Getenv("ACCESS_TOKEN_SECRET"))
	v := url.Values{}
	v.Add("screen_name", "habomaijiro")
	v.Add("count", "200")
	if sinceID != "" {
		v.Add("since_id", sinceID)
	}
	tl, err := api.GetUserTimeline(v)
	if err != nil {
		return
	}

	jst, err := time.LoadLocation("Asia/Tokyo")
	if err != nil {
		return
	}
	tweets = make([]Tweet, len(tl))
	for i, v := range tl {
		var t Tweet
		t.ID = v.IdStr
		if parsedT, err := time.Parse(time.RubyDate, v.CreatedAt); err == nil {
			t.Date = parsedT.In(jst)
		}
		t.ImageURLs = make([]string, len(v.Entities.Media))
		for j, m := range v.Entities.Media {
			t.ImageURLs[j] = m.Media_url_https
		}
		analizeText(&t, v.Text)
		tweets[i] = t
	}
	return
}
Example #30
0
func (t *TwitterUtil) GetNewTweetMedia(txt string) (anaconda.Media, string) {
	rx, _ := regexp.Compile("(http|https):\\/\\/([\\w.\\-\\/\\%#]+)")
	rxm := rx.FindAllStringSubmatch(txt, -1)
	if len(rxm) > 0 {
		for i := 0; i < len(rxm); i++ {
			rxm_i := rxm[i]
			ml := rxm_i[0]

			ht := new(HttpUtils)
			mt := ht.GetContentType(ml)

			if strings.Index(mt, "image") >= 0 {
				anaconda.SetConsumerKey(opt.TwitterAppKey)
				anaconda.SetConsumerSecret(opt.TwitterAppSecret)
				api := anaconda.NewTwitterApi(opt.TwitterAuthKey, opt.TwitterAuthSecret)

				bimg := ht.GetRemoteImageBase64(ml)
				med, mer := api.UploadMedia(bimg)
				api.Close()
				if mer == nil {
					return med, strings.Replace(txt, ml, "", -1)
				} else {
					fmt.Println(mer)
				}
			}
		}
	}
	return anaconda.Media{}, txt
}