LoginSignup
4
1

More than 5 years have passed since last update.

Twitterのリストを新規作成してユーザを追加するコードをGoで書いてみた

Posted at

使い方

  • 1. 依存ライブラリを取得
go get -v github.com/ChimeraCoder/anaconda
  • 2. ユーザの一覧を記載したテキストファイルを作成
cat USERS_FILE.txt
userA
userB
userC
  • 3. 実行

第1引数は作成するリストの名前、第2引数は作成するリストが公開か非公開か、第3引数はユーザの一覧を記載したテキストファイル

go run main.go NEWLIST_NAME NEWLIST_MODE(puclic or private) USERS_FILE.txt

TwitterのAPI Keyは各自取得して書き換えてください。

package main

import (
    "bufio"
    "fmt"
    "net/url"
    "os"
    "time"

    "github.com/ChimeraCoder/anaconda"
)

// Usage
// go get -v github.com/ChimeraCoder/anaconda
//
// cat USERS_FILE.txt
// userA
// userB
// ...
//
// go run main.go NEWLIST_NAME NEWLIST_MODE(puclic or private) USERS_FILE.txt

var (
    consumerKey       = ""
    consumerSecret    = ""
    accessToken       = ""
    accessTokenSecret = ""
)

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

    if len(os.Args) != 4 {
        fmt.Println("usage: go run main.go NEWLIST_NAME NEWLIST_MODE(puclic or private) USERS_FILE.txt")
        os.Exit(1)
    }

    listName := os.Args[1]
    fp, err := os.Open(os.Args[3])
    if err != nil {
        panic(err)
    }
    defer fp.Close()

    v := url.Values{}
    v.Set("mode", os.Args[2])
    list, err := api.CreateList(listName, "", v)
    if err != nil {
        panic(err)
    }
    fmt.Printf("Create success %v\n", list.Name)

    scanner := bufio.NewScanner(fp)
    if err := scanner.Err(); err != nil {
        panic(err)
    }

    fmt.Println("Wait 5 sec...")
    time.Sleep(time.Second * 5)

    for scanner.Scan() {
        user := scanner.Text()
        fmt.Printf("add %v to %v\n", user, listName)

        _, err = api.AddUserToList(user, list.Id, nil)
        if err != nil {
            panic(err)
        }
    }
}
4
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
4
1