Exemple #1
0
// OpenIssue registers a handler that will cause the bot to open a github issue
// based on the event text.
//
// The handler is registered as a "Respond", not a "Listen" (see the docs for
// github.com/ajm188/slack for the difference). The pattern which will cause
// the handler to fire has the form 'issue me // <owner>/<repo> "<title>"
// ("<body>" ("<assignee>")?)?'.
//
// The function takes as arguments the bot to which it should register the
// handler, and a reference to a client that can authenticate with Github. If
// no client is provided, then OpenIssue will fall back to using the
// package-wide SharedClient.
//
// Users should note that an attempt to assign an issue to a Github user that
// is not a "contributor" on the repository will result in a 422 returned by
// the Github API. This will prevent the issue from being created.
//
// When an issue has successfully been created, the bot will reply to the user
// which triggered the handler with a link to the issue.
func OpenIssue(bot *slack.Bot, client *github.Client) {
	repoRe := regexp.MustCompile("issue me ([^/ ]+)/([^/ ]+)")
	argsRe := regexp.MustCompile("(\".*?[^\\\\]\")")
	if client == nil {
		client = SharedClient
	}
	issues := client.Issues

	handler := func(b *slack.Bot, event map[string]interface{}) (*slack.Message, slack.Status) {
		text := event["text"].(string)
		owner, repo, err := extractOwnerAndRepo(text, repoRe)
		if err != nil {
			return nil, slack.Continue
		}
		issueRequest, err := extractIssueArgs(text, argsRe)
		if err != nil {
			return nil, slack.Continue
		}
		userID := event["user"].(string)
		user, ok := b.Users[userID]
		if !ok {
			return nil, slack.Continue
		}
		fullName := user.FullName()
		name := user.Nick
		if fullName != "" {
			name += fmt.Sprintf(" (%s)", fullName)
		}
		issueCreationMessage := fmt.Sprintf(
			"\n\n Issue created via slack on behalf of %s",
			name,
		)
		issueBody := (*issueRequest.Body) + issueCreationMessage
		issueRequest.Body = &issueBody
		issue, _, err := issues.Create(owner, repo, issueRequest)
		channel := event["channel"].(string)
		if err != nil {
			message := fmt.Sprintf(
				"I had some trouble opening an issue. Here was the error I got:\n%v",
				err)
			return bot.Mention(userID, message, channel), slack.Continue
		}

		message := fmt.Sprintf(
			"I created that issue for you. You can view it here: %s",
			*issue.HTMLURL,
		)
		return bot.Mention(userID, message, channel), slack.Continue
	}

	bot.RespondRegexp(repoRe, handler)
}