package discourse import ( "encoding/json" "fmt" "io/ioutil" "net/http" "strings" "time" "github.com/sirupsen/logrus" ) // GetUser - Get a discourse user func GetUser(config APIConfig, username string) (User, error) { url := fmt.Sprintf("%s/users/%s.json", config.Endpoint, username) fmt.Println(url) req, _ := newGetRequest(config, url) client := getClient(rl) response, _ := client.Do(req) var result *UserResponse json.NewDecoder(response.Body).Decode(&result) if result.ErrorType != "" { return User{}, fmt.Errorf("Failed to get discourse user. Error: %s", strings.Join(result.Errors, "; ")) } return result.User, nil } func GetUserByID(config APIConfig, userID int) (User, error) { url := fmt.Sprintf("%s/admin/users/%d.json", config.Endpoint, userID) req, _ := newGetRequest(config, url) client := getClient(rl) response, _ := client.Do(req) if response.StatusCode != http.StatusOK { var errorResult *UserResponse json.NewDecoder(response.Body).Decode(&errorResult) if errorResult.ErrorType != "" { return User{}, fmt.Errorf("failed to get discourse user. Error: %s", strings.Join(errorResult.Errors, "; ")) } } var result *User json.NewDecoder(response.Body).Decode(&result) return *result, nil } func GetUsersByMinTrustLevel(config APIConfig, minTrustLevel int64) ([]User, error) { page := 1 getMoreResults := true var users []User for getMoreResults { var pageResults, _ = GetUsersPage(config, page) if len(pageResults) > 0 { for _, v := range pageResults { if v.Staged == false && v.TrustLevel >= minTrustLevel { u, err := GetUser(config, v.Username) if err != nil { return nil, err } users = append(users, u) } } page++ } else { getMoreResults = false } } return users, nil } func GetUsersPage(config APIConfig, page int) ([]User, error) { url := fmt.Sprintf("%s/admin/users/list/active.json?page=%d&?filter=&show_emails=false", config.Endpoint, page) fmt.Println(url) req, _ := newGetRequest(config, url) client := getClient(rl) response, _ := client.Do(req) time.Sleep(1 * time.Second) bodyBytes, err := ioutil.ReadAll(response.Body) if err != nil { logrus.Fatal(err) } var users []User json.Unmarshal(bodyBytes, &users) return users, nil }