Example #1
0
// ChannelMembers gets all members of a specified channel.
func ChannelMembers(channel, token string) ([]string, error) {

	// Channels.info contains an array of members.
	chanURL := "https://slack.com/api/channels.info"

	// Token and channel are required URL params for a request.
	query := url.Values{}
	query.Add("token", fmt.Sprintf("%s", token))
	query.Add("channel", fmt.Sprintf("%s", channel))

	// Append url to log.
	log.Println(fmt.Sprintf("%s?%s", chanURL, query.Encode()))

	// Create our request.
	req, err := http.NewRequest("GET", fmt.Sprintf("%s?%s", chanURL, query.Encode()), nil)
	if err != nil {
		log.Printf("Error creating HTTP request: %s", err)
		return nil, err
	}

	client := &http.Client{}

	// Doing the request.
	var attempt int
	var res *http.Response
	for {
		res, err = client.Do(req)
		if err != nil {
			fmt.Printf("\nError performing request: %s", err)
			// TODO: Does this make sense?
			if !(web.ResponseCheck(res.StatusCode)) {
				log.Printf("Got a bad response: %d", res.StatusCode)
			}
			// Delays between attempts will be exponentially longer each time.
			attempt++
			delay := web.BackoffDuration(attempt)
			time.Sleep(delay)
		} else {
			break
		}
	}
	defer res.Body.Close()

	resBody, _ := ioutil.ReadAll(res.Body)

	chanInfo := ChannelInfo{}
	err = json.Unmarshal(resBody, &chanInfo)
	if err != nil {
		log.Printf("Error unmarshalling channel info: %s", err)
	}

	// All we care about is our list of member ID strings.
	members := chanInfo.Channel.Members

	return members, err
}
Example #2
0
// Message sends a payload to a specified Slack Channel.
func Message(nameAndArticle string, authURL, grader string) error {

	// dueDay is three days from today.
	dueDay := calculateDueDay()
	// TODO: Check if how to include markdown. Might not be possible for pretext.
	pretext := fmt.Sprintf("Hear ye! It's time for homework.\n")

	var textBody []string
	textBody = append(textBody, fmt.Sprintf("Please submit homework in the form of a Slack post in this channel.\n"+
		"The homework is due on %s.\n", dueDay))
	textBody = append(textBody, nameAndArticle)
	textBodyStr := strings.Join(textBody, "\n")

	attachments := []Attachments{
		Attachments{
			Fallback: "",
			Colour:   "#36a64f",
			Pretext:  pretext,
			// AuthorName: "Mikey J. Professor of Cantan foods, culture, and the greater Cantan region.",
			Title: "Here be the articles",
			// ImageURL: "",
			// ThumbURL: "",
			// TitleLink: "",
			Text: textBodyStr,
			// AuthorLink: "",
			// AuthorIcon: "",
			Fields: []Fields{
				{
					Title: "\nGrader",
					Value: fmt.Sprintf("%s", grader),
					Short: true,
				},
			},
		},
	}
	body := Body{
		Channel:  "#homework",
		Username: "******",
		// Text:        fmt.Sprintf("%s your homework is %s", "Name", articleURLs[0]),
		IconEmoji:   ":mortar_board:",
		Attachments: attachments,
	}

	var payloadJSON []byte
	payloadJSON, err := json.Marshal(body)
	if err != nil {
		log.Fatalf("Error marshalling JSON: %s", err)
	}

	// Append payload to log.
	log.Println(string(payloadJSON))

	req, err := http.NewRequest("POST", authURL, bytes.NewBuffer(payloadJSON))
	if err != nil {
		log.Printf("Error creating HTTP request: %s", err)
		return err
	}

	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}

	var res *http.Response
	res, err = client.Do(req)
	if err != nil {
		log.Fatalf("Error performing request: %s", err)
	}
	defer res.Body.Close()

	if !(web.ResponseCheck(res.StatusCode)) {
		log.Fatalf("Got a bad response: %d", res.StatusCode)
	}

	return err
}
Example #3
0
// GetRandomArticles uses the Wikipedia API to return IDs for
// random Wikipedia articles.
func GetRandomArticles(n int) ([]string, error) {

	wikiURL := "https://en.wikipedia.org/w/api.php"

	query := url.Values{}
	query.Add("action", fmt.Sprintf("%s", "query"))
	query.Add("list", fmt.Sprintf("%s", "random"))
	query.Add("format", fmt.Sprintf("%s", "json"))
	query.Add("rnnamespace", fmt.Sprintf("%d", 0))
	query.Add("rnlimit", fmt.Sprintf("%d", n))

	client := &http.Client{}

	req, err := http.NewRequest("GET", fmt.Sprintf("%s?%s", wikiURL, query.Encode()), nil)
	if err != nil {
		log.Printf("Error creating HTTP request: %s", err)
		return nil, err
	}

	log.Printf("Requesting %s", fmt.Sprintf("%s?%s", wikiURL, query.Encode()))

	// Doing the request.
	var attempt int
	var res *http.Response
	for {
		res, err = client.Do(req)
		if err != nil {
			// Does this make sense?
			if !(web.ResponseCheck(res.StatusCode)) {
				log.Printf("Got a bad response: %d", res.StatusCode)
			}
			fmt.Printf("\nError performing request: %s", err)
			// Delays between attempts will be exponentially longer each time.
			attempt++
			delay := web.BackoffDuration(attempt)
			time.Sleep(delay)
		} else {
			break
		}
	}

	defer res.Body.Close()

	body, err := ioutil.ReadAll(res.Body)
	if err != nil {
		log.Printf("Error reading response body: %s", err)
		return nil, err
	}

	response := Response{}
	err = json.Unmarshal(body, &response)
	if err != nil {
		log.Printf("Error unmarhsalling response JSON: %s", err)
		return nil, err
	}

	var articleIDs []string
	for _, article := range response.Query.Random {
		articleIDs = append(articleIDs, strconv.Itoa(article.ID))
	}

	return articleIDs, err
}