6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Go7Advent Calendar 2019

Day 7

GoでtwitterAPI触ってみた

Last updated at Posted at 2019-12-06

Goの勉強も含めて、Twitter APIを利用して、「アオキ大好き!最高!」とツイートしている人を全員フォローしてみせます。

anacondaというパッケージを使います。

##anacondaとは
Pythonのあれじゃないです。

anacondaとは、Twitter APIにアクセスするためのGoパッケージです。便利!

Twitter APIの利用申請

間違いなく一番めんどくさい過程。
こちらを見ながら頑張りましょう。結構テキトーでも通ります。

##実装

main.go
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/url"
	"strconv"

	"github.com/ChimeraCoder/anaconda"
)

type TwitterAccount struct {
	AccessToken       string `json:"accessToken"`
	AccessTokenSecret string `json:"accessTokenSecret"`
	ConsumerKey       string `json:"consumerKey"`
	ConsumerSecret    string `json:"consumerSecret"`
}

func main() {
	raw, error := ioutil.ReadFile("./twitterAccount.json")
	if error != nil {
		fmt.Println(error.Error())
		return
	}

	var twitterAccount TwitterAccount
	json.Unmarshal(raw, &twitterAccount)

	api := anaconda.NewTwitterApiWithCredentials(twitterAccount.AccessToken, twitterAccount.AccessTokenSecret, twitterAccount.ConsumerKey, twitterAccount.ConsumerSecret)
	v := url.Values{}
	v.Set("count","10000")
	// v.Set("exclude","retweets")
	searchResult, _ := api.GetSearch(`"アオキ大好き!最高!"`, v)
	fmt.Println(strconv.Itoa(len(searchResult.Statuses))+"件ヒットしました!!")
	for _, tweet := range searchResult.Statuses {
		fmt.Printf("%d\n", tweet.User.Id)
		api.FollowUserId(tweet.User.Id,v)
		fmt.Println("--------------------------------------------------------------")
	}
}

twitterAccount.json
{
  "accessToken": "*****************",
  "accessTokenSecret": "*****************",
  "consumerKey": "*****************",
  "consumerSecret": "*****************"
}
結果
   0件ヒットしました!!

今回作成したリポジトリはこちらから

参考:
anaconda github
anaconda Doc

6
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?