Skip to content

Instantly share code, notes, and snippets.

@tarekbadrsh
Last active July 4, 2021 19:19
Show Gist options
  • Save tarekbadrsh/f4f61f40a4b0353f400ce53078914767 to your computer and use it in GitHub Desktop.
Save tarekbadrsh/f4f61f40a4b0353f400ce53078914767 to your computer and use it in GitHub Desktop.
Merge two Twitter lists using twitter-api
package main
import (
"fmt"
"net/url"
"github.com/tarekbadrshalaan/anaconda"
)
func main() {
ConsumerKey := ""
ConsumerSecret := ""
AccessToken := ""
AccessTokenSecret := ""
twAPI := anaconda.NewTwitterApiWithCredentials(AccessToken, AccessTokenSecret, ConsumerKey, ConsumerSecret)
var list1 int64 = 1396726685433843712
var list2 int64 = 1386252949513461761
count := commonUsersCount(twAPI, list1, list2)
fmt.Printf("Common Users count %v\n", count)
err := mergeTwoLists(twAPI, list1, list2)
if err != nil {
fmt.Println(err)
}
}
// getUsersListIds: return all Users-ids in list.
func getUsersListIds(twAPI *anaconda.TwitterApi, listId int64) map[int64]bool {
v := url.Values{}
usersIds := make(map[int64]bool)
cursor, err := twAPI.GetListMembers("", listId, v)
if err != nil {
fmt.Printf("error 35: %v\n", err)
return nil
}
nextCursor := "-1"
for {
fmt.Printf("Current Cursor %v\n", nextCursor)
v.Set("cursor", nextCursor)
cursor, err = twAPI.GetListMembers("", listId, v)
if err != nil {
fmt.Printf("error 45: %v\n", err)
return nil
}
for _, user := range cursor.Users {
usersIds[user.Id] = true
}
nextCursor = cursor.Next_cursor_str
if nextCursor == "0" {
break
}
}
return usersIds
}
// mergeTwoLists: Add users in list1 to list 2,
// Note duplicate users will be ignored by twitter.
func mergeTwoLists(twAPI *anaconda.TwitterApi, listId1 int64, listId2 int64) error {
v := url.Values{}
cursor, err := twAPI.GetListMembers("", listId1, v)
if err != nil {
fmt.Printf("error 65: %v\n", err)
return err
}
nextCursor := "-1"
for {
fmt.Printf("Current Cursor %v\n", nextCursor)
screenNames := []string{}
v.Set("cursor", nextCursor)
cursor, err = twAPI.GetListMembers("", listId1, v)
if err != nil {
fmt.Printf("error 76: %v\n", err)
return err
}
for _, user := range cursor.Users {
screenNames = append(screenNames, user.ScreenName)
}
_, err := twAPI.AddMultipleUsersToList(screenNames, listId2, nil)
if err != nil {
fmt.Printf("error 84: %v\n", err)
return err
}
fmt.Printf("Cursor <%v> done successfully\n", nextCursor)
nextCursor = cursor.Next_cursor_str
if nextCursor == "0" {
break
}
}
return nil
}
// commonUsersCount: get the count of common users in two list.
func commonUsersCount(twAPI *anaconda.TwitterApi, listId1 int64, listId2 int64) int {
list1Ids := getUsersListIds(twAPI, listId1)
print(list1Ids)
list2Ids := getUsersListIds(twAPI, listId2)
print(list2Ids)
counter := 0
for k := range list1Ids {
if list2Ids[k] {
counter++
}
}
return counter
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment