本文整理汇总了Golang中github.com/ChimeraCoder/anaconda.NewTwitterApi函数的典型用法代码示例。如果您正苦于以下问题:Golang NewTwitterApi函数的具体用法?Golang NewTwitterApi怎么用?Golang NewTwitterApi使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewTwitterApi函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: SetLocation
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()
}
}
示例2: twitterSearch
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)
}
示例3: Listen
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)
}
}
}
}
示例4: main
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)
}
}
示例5: InitializeClient
// 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
}
示例6: Save
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
}
示例7: sendTweet
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
}
示例8: GetAuth
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
}
示例9: main
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)
}
示例10: main
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")
}
示例11: main
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)
}
}
示例12: main
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)
}
}
示例13: NewStream
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
}
示例14: SendTweetResponse
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()
}
示例15: main
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()
}