Esempio n. 1
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)
}
Esempio n. 2
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)
	}
}
//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)
}
Esempio n. 4
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)
		}
	}
}
Esempio n. 5
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)
	}
}
Esempio n. 6
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
}
Esempio n. 7
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
}
Esempio n. 8
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
}
Esempio n. 9
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)
	}

}
Esempio n. 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")
}
Esempio n. 11
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
}
Esempio n. 12
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()
}
Esempio n. 13
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()
	}
}
Esempio n. 14
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
}
Esempio n. 15
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
}
Esempio n. 16
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)
	}

}
Esempio n. 17
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)
}
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)
}
Esempio n. 19
0
func init() {
	log.Print("**** Load Config ****")
	c = utils.NewConfig()
	c.Load()
	anaconda.SetConsumerKey(c.ConsumerKey)
	anaconda.SetConsumerSecret(c.ConsumerSecret)
}
Esempio n. 20
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
}
Esempio n. 21
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}
}
Esempio n. 22
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))
}
Esempio n. 23
0
func main() {
	if testCredentials() == false {
		fmt.Printf("CONSUMER_KEY and CONSUMER_SECRET need to be set!\n")
		return
	}

	anaconda.SetConsumerKey(CONSUMER_KEY)
	anaconda.SetConsumerSecret(CONSUMER_SECRET)
	initUi()

	c := cli.NewCLI("gogobird", "0.0.1")
	c.Args = os.Args[1:]
	c.Commands = map[string]cli.CommandFactory{
		"auth":      factoryAuth,
		"search":    factorySearch,
		"post":      factoryPost,
		"followers": factoryGetFollowers,
	}

	if len(c.Args) >= 1 && os.Args[1] != "auth" {
		if initTwitterApi() == false {
			ui.Error("init twitter api failed.")
			return
		}
	}

	exitStatus, err := c.Run()
	if err != nil {
		log.Println(err)
	}

	os.Exit(exitStatus)
}
Esempio n. 24
0
func main() {

	var p = flag.Bool("p", false, "Add place info in detail")
	flag.Parse()

	anaconda.SetConsumerKey(os.Getenv("CONSUMER_KEY"))
	anaconda.SetConsumerSecret(os.Getenv("CONSUMER_SECRET"))

	tweets, err := getTweetFromFile()
	if err != nil {
		panic(err)
	}

	tweetsFromAPI, err := getTweetFromAPI(tweets[0].ID)
	if err != nil {
		panic(err)
	}
	tweets = append(tweets, tweetsFromAPI...)

	if *p {
		getPlace(tweets)
	}

	dump(tweets, "data/habomai.json")
}
Esempio n. 25
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)
			}
		}
	}
}
Esempio n. 26
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
}
Esempio n. 27
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)
}
Esempio n. 28
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
}
Esempio n. 29
0
func getTwitterData(DB *bolt.DB) {
	anaconda.SetConsumerKey("KmxA5PMS1WaVdSnJrYtq5XANb")
	anaconda.SetConsumerSecret("yt7ydv2qFt7BpyHrMK3UzIj7HXGGv7ezcVTnELxhgh2WMGj9IA")
	api := anaconda.NewTwitterApi(
		"268263175-deYL6a9YyDMy8YRDQI0p9NDBoKuZScRKG24Dpqkj",
		"PrFnSYOzsZjPYc5zhN9qeviyyHH0x1sKkiOYSSyPdWrnS")

	tweets, err := api.GetHomeTimeline(url.Values{
		"count": {"10"},
	})
	if err != nil {
		// TODO -- Handle timeouts here
		panic(err)
	}

	Tx, err := DB.Begin(true)
	if err != nil {
		// TODO -- Handle this gracely
		panic(err)
	}
	Bucket := Tx.Bucket([]byte("tweets"))
	for _, t := range tweets {

		tweetText := t.Text
		if t.RetweetedStatus != nil {
			tweetText = t.RetweetedStatus.Text
		}
		tweetText = replaceURLS(tweetText, func(s string) string {
			fmt.Println("Replacing ", s)
			for retries := 0; retries < 3; retries++ {
				newS, err := getRedirectedURL(s)
				if err != nil {
					time.Sleep(time.Duration(1+retries) * time.Second)
					continue
				}
				return newS
			}
			return s
		})
		if t.RetweetedStatus != nil {
			t.RetweetedStatus.Text = tweetText
		} else {
			t.Text = tweetText
		}
		data, err := json.Marshal(t)
		if err != nil {
			Tx.Rollback()
			DB.Sync()
			panic(err)
		}
		key := []byte(strconv.FormatInt(t.Id, 16))
		if err = Bucket.Put(key, data); err != nil {
			Tx.Rollback()
			DB.Sync()
			panic(err)
		}
	}
	Tx.Commit()
}
Esempio n. 30
0
func (*TwitterUtil) ListenToUserStream(i *irc.Connection, auth TwitterAuthToken) {
	anaconda.SetConsumerKey(opt.TwitterAppKey)
	anaconda.SetConsumerSecret(opt.TwitterAppSecret)
	api := anaconda.NewTwitterApi(auth.OauthToken, auth.OauthTokenSecret)

	stream := api.UserStream(url.Values{})
	if stream != nil {
		for {
			tw := <-stream.C
			switch st := tw.(type) {
			case anaconda.Tweet:
				{
					//Check if the tweet is at us, otherwise spam #twitterspam
					hasMention := false
					for x := 0; x < len(st.Entities.User_mentions); x++ {
						ent := st.Entities.User_mentions[x]
						if ent.Screen_name == auth.ScreenName {
							hasMention = true
						}
					}

					tweet_txt := strings.Replace(st.Text, "\n", "", -1)

					if hasMention {
						i.Privmsgf("#twitter", "Tweet from @%s [%s]: %s", st.User.ScreenName, st.IdStr, tweet_txt)
					} else {
						i.Privmsgf("#twitterspam", "@%s [%s]: %s", st.User.ScreenName, st.IdStr, tweet_txt)
					}
					break
				}
			case anaconda.DirectMessage:
				{
					dm_txt := strings.Replace(st.Text, "\n", "", -1)
					if st.SenderScreenName != auth.ScreenName {
						i.Privmsgf("#twitter", "DM from @%s [%s]: %s", st.SenderScreenName, st.IdStr, dm_txt)
					}
					break
				}
			case anaconda.EventTweet:
				{
					tweet_txt := strings.Replace(st.TargetObject.Text, "\n", "", -1)
					if st.Event.Event == "favorite" && st.Source.ScreenName != auth.ScreenName {
						i.Privmsgf("#twitter", "Tweet favorited by @%s [%s]: %s", st.Source.ScreenName, tweet_txt)
					}
					break
				}
			case anaconda.Event:
				{
					if st.Event == "follow" && st.Source.ScreenName != auth.ScreenName {
						i.Privmsgf("#twitter", "@%s is now following you", st.Source.ScreenName)
					}
					break
				}
			}
		}
	}

	api.Close()
}