當前位置: 首頁>>代碼示例>>Golang>>正文


Golang PostMessageParameters.Attachments方法代碼示例

本文整理匯總了Golang中github.com/nlopes/slack.PostMessageParameters.Attachments方法的典型用法代碼示例。如果您正苦於以下問題:Golang PostMessageParameters.Attachments方法的具體用法?Golang PostMessageParameters.Attachments怎麽用?Golang PostMessageParameters.Attachments使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在github.com/nlopes/slack.PostMessageParameters的用法示例。


在下文中一共展示了PostMessageParameters.Attachments方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: Fire

func (hook *SlackHook) Fire(sourceEntry *logrus.Entry) error {
	hook.client = slack.New(hook.token)

	params := slack.PostMessageParameters{
		Username:  hook.Username,
		IconURL:   hook.IconURL,
		IconEmoji: hook.IconEmoji,
	}

	var messageFields []slack.AttachmentField

	for key, value := range sourceEntry.Data {
		message := slack.AttachmentField{
			Title: key,
			Value: value.(string),
			Short: true,
		}

		messageFields = append(messageFields, message)
	}

	attachment := slack.Attachment{
		Color:      getColor(sourceEntry.Level),
		AuthorName: hook.AuthorName,
		Fields:     messageFields,
		Text:       sourceEntry.Message,
	}

	params.Attachments = []slack.Attachment{attachment}
	_, _, err := hook.client.PostMessage(hook.Channel, "", params)

	return err
}
開發者ID:kucuny,項目名稱:slackrus,代碼行數:33,代碼來源:slackrus.go

示例2: SendMessage

// SendMessage reads the configuration file, and posts a message about Kocho's invocation to Slack.
func SendMessage(version, build string) error {
	expanded, err := homedir.Expand(configPath)
	if err != nil {
		return err
	}
	if _, err := os.Stat(expanded); os.IsNotExist(err) {
		return errgo.Mask(ErrNotConfigured, errgo.Any)
	}

	slackConfiguration := SlackConfiguration{
		NotificationUsername: "KochoBot",
		EmojiIcon:            ":robot_face:",
	}

	configFile, err := os.Open(expanded)
	if err != nil {
		return errgo.WithCausef(err, ErrInvalidConfiguration, "couldn't open Slack configuration file")
	}
	defer configFile.Close()

	if err := json.NewDecoder(configFile).Decode(&slackConfiguration); err != nil {
		return errgo.WithCausef(err, ErrInvalidConfiguration, "couldn't decode Slack configuration")
	}

	client := slack.New(slackConfiguration.Token)

	params := slack.PostMessageParameters{}
	params.Attachments = []slack.Attachment{
		slack.Attachment{
			Color: "#2484BE",
			Text:  fmt.Sprintf("*Kocho*: %s ran `%s`", slackConfiguration.Username, strings.Join(os.Args, " ")),
			Fields: []slack.AttachmentField{
				slack.AttachmentField{
					Title: "Kocho Version",
					Value: version,
					Short: true,
				},
				slack.AttachmentField{
					Title: "Kocho Build",
					Value: build,
					Short: true,
				},
			},
			MarkdownIn: []string{"text"},
		},
	}
	params.Username = slackConfiguration.NotificationUsername
	params.IconEmoji = slackConfiguration.EmojiIcon

	if _, _, err := client.PostMessage(slackConfiguration.NotificationChannel, "", params); err != nil {
		return err
	}

	return nil
}
開發者ID:giantswarm,項目名稱:kocho,代碼行數:56,代碼來源:slack.go

示例3: main

func main() {
	api := slack.New(os.Getenv("SLACK_TOKEN"))
	params := slack.PostMessageParameters{
		Username:  "qcicbot",
		IconEmoji: ":eye:", // or :ghost:, :eyes:
	}

	// https://api.slack.com/docs/attachments
	attachment := slack.Attachment{
		Color: "#439FE0", // good, warning, danger, or any hex color code (eg. #439FE0)

		AuthorName:    "Author Name",
		AuthorSubname: "Author Subname",

		Title:     "Title",
		TitleLink: "TitleLink",
		Pretext:   "Attachment pretext",
		Text:      "Attachment Text (with markup).\n*bold* `code` _italic_",
		// ImageURL:  "http://daniel-lauzon.com/img/about-me-trans.png",
		ThumbURL: "https://en.gravatar.com/userimage/2562383/0a6632e59a6821599a51eace02d754ea.jpeg",

		MarkdownIn: []string{"text"}, // ["text", "pretext","fields"]

		// Uncomment the following part to send a field too
		Fields: []slack.AttachmentField{
			slack.AttachmentField{
				Title: "Reported by",
				Value: "Snookr",
				Short: true,
			},
			slack.AttachmentField{
				Title: "Priority",
				Value: "Must Respond",
				Short: true,
			},
		},
	}
	params.Attachments = []slack.Attachment{attachment}
	channelID, timestamp, err := api.PostMessage("#qcic", "Some text mentioning @daniel", params)
	if err != nil {
		fmt.Printf("%s\n", err)
		return
	}
	fmt.Printf("Message successfully sent to channel %s at %s\n", channelID, timestamp)
}
開發者ID:daneroo,項目名稱:go-qcic,代碼行數:45,代碼來源:slack.go

示例4: onMessage

func (s *Slack) onMessage(message *Message) error {
	postMessage := slack.PostMessageParameters{
		Username:  message.Name,
		LinkNames: 1,
	}

	re := regexp.MustCompile("^:.*:$")
	if re.MatchString(message.Icon) {
		postMessage.IconEmoji = message.Icon
	} else {
		postMessage.IconURL = message.Icon
	}

	if message.Attachment != nil {
		attachment := slack.Attachment{
			Fallback:   message.Attachment.Fallback,
			Color:      message.Attachment.Color,
			Pretext:    message.Attachment.Pretext,
			AuthorName: message.Attachment.AuthorName,
			AuthorLink: message.Attachment.AuthorLink,
			AuthorIcon: message.Attachment.AuthorIcon,
			Title:      message.Attachment.Title,
			TitleLink:  message.Attachment.TitleLink,
			Text:       message.Attachment.Text,
			ImageURL:   message.Attachment.ImageURL,
			MarkdownIn: []string{"text", "pretext", "fields"},
		}
		if len(message.Attachment.Fields) > 0 {
			fields := make([]slack.AttachmentField, len(message.Attachment.Fields))
			for i := range fields {
				fields[i].Title = message.Attachment.Fields[i].Title
				fields[i].Value = message.Attachment.Fields[i].Value
				fields[i].Short = message.Attachment.Fields[i].Short
			}
			attachment.Fields = fields
		}
		postMessage.Attachments = []slack.Attachment{attachment}
	}

	_, _, err := s.Client.PostMessage(message.Channel, message.Message, postMessage)
	return err
}
開發者ID:intfrr,項目名稱:takosan,代碼行數:42,代碼來源:slack.go

示例5: sendMessage

func sendMessage(issue Issue, channel string) error {
	params := slack.PostMessageParameters{}
	text := fmt.Sprintf("*%s*\n\n *Assignee* %s *Priority* %s ", issue.Fields.Summary, issue.Fields.Assignee.DisplayName, issue.Fields.Priority.Name)
	attachment := slack.Attachment{
		Title:      issue.Key,
		TitleLink:  fmt.Sprintf("%s/browse/%s", jiraHostURL, issue.Key),
		Text:       text,
		Color:      getColor(issue.Fields.Status.Name),
		MarkdownIn: []string{"text", "pretext"},
	}
	params.Attachments = []slack.Attachment{attachment}
	params.IconURL = jiraIcon
	params.Username = "Jira"
	_, _, err := Slack.PostMessage(channel, "", params)
	if err != nil {
		fmt.Printf("%s\n", err)
		return err
	}
	return nil

}
開發者ID:MaTriXy,項目名稱:go-slackjira,代碼行數:21,代碼來源:main.go

示例6: post

func post(rtm *slack.RTM, channel string, message Message, debug bool) {
	t := time.Now()
	ts := t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")
	params := slack.PostMessageParameters{
		Username: "redshift",
	}
	attachment := slack.Attachment{
		Pretext: message.Subject,
		Text:    message.Detail,
	}
	params.Attachments = []slack.Attachment{attachment}

	title := fmt.Sprintf("Alert *%s* with Severity %d (Magnitude: %d, Floater: %.4f)", message.Subject, message.Severity, message.Magnitude, message.Floater)
	channelID, timestamp, err := rtm.PostMessage(channel, title, params)
	if err != nil {
		fmt.Printf("[%s] ERROR Error received: %s\n", ts, err)
		return
	}
	if debug {
		fmt.Printf("[%s] INFO Message %+v successfully sent to channel %s at %s", ts, message, channelID, timestamp)
	}
}
開發者ID:cullenbass,項目名稱:redshift,代碼行數:22,代碼來源:slack.go

示例7: main

func main() {
	api := slack.New("YOUR_TOKEN_HERE")
	params := slack.PostMessageParameters{}
	attachment := slack.Attachment{
		Pretext: "some pretext",
		Text:    "some text",
		// Uncomment the following part to send a field too
		/*
			Fields: []slack.AttachmentField{
				slack.AttachmentField{
					Title: "a",
					Value: "no",
				},
			},
		*/
	}
	params.Attachments = []slack.Attachment{attachment}
	channelID, timestamp, err := api.PostMessage("CHANNEL_ID", "Some text", params)
	if err != nil {
		fmt.Printf("%s\n", err)
		return
	}
	fmt.Printf("Message successfully sent to channel %s at %s", channelID, timestamp)
}
開發者ID:Ripleather,項目名稱:starter-go-bot,代碼行數:24,代碼來源:messages.go

示例8: ReplyWithAttachments

// ReplyWithAttachments replys to a message event with a Slack Attachments message.
func (b *Bot) ReplyWithAttachments(channel string, attachments []slack.Attachment, typing bool) {
	params := slack.PostMessageParameters{AsUser: true}
	params.Attachments = attachments

	b.Client.PostMessage(channel, "", params)
}
開發者ID:RobotsAndPencils,項目名稱:slack-salesforce-bot,代碼行數:7,代碼來源:bot.go

示例9: createMessage

// createMessage generates the message to post to Slack.
func createMessage(p Plugin, user *slack.User) slack.PostMessageParameters {
	var messageOptions MessageOptions
	var color string
	var messageTitle string

	// Determine if the build was a success
	if p.Build.Status == "success" {
		messageOptions = p.Config.Success
		color = "good"
		messageTitle = "Build succeeded"
	} else {
		messageOptions = p.Config.Failure
		color = "danger"
		messageTitle = "Build failed"
	}

	// setup the message
	messageParams := slack.PostMessageParameters{
		Username: messageOptions.Username,
	}

	if strings.HasPrefix(messageOptions.Icon, "http") {
		log.Info("Icon is a URL")
		messageParams.IconURL = messageOptions.Icon
	} else {
		log.Info("Icon is an emoji")
		messageParams.IconEmoji = messageOptions.Icon
	}

	// setup the payload
	payload := templatePayload{
		Build:     p.Build,
		Repo:      p.Repo,
		BuildLast: p.BuildLast,
		User:      user,
	}

	messageText, err := template.Render(messageOptions.Template, &payload)

	if err != nil {
		log.Error("Could not parse template")
	}

	// create the attachment
	attachment := slack.Attachment{
		Color:     color,
		Text:      messageText,
		Title:     messageTitle,
		TitleLink: p.Build.Link,
	}

	// Add image if any are provided
	imageCount := len(messageOptions.ImageAttachments)

	if imageCount > 0 {
		log.WithFields(log.Fields{
			"count": imageCount,
		}).Info("Choosing from images")
		rand.Seed(time.Now().UTC().UnixNano())
		attachment.ImageURL = messageOptions.ImageAttachments[rand.Intn(imageCount)]
	}

	messageParams.Attachments = []slack.Attachment{attachment}

	return messageParams
}
開發者ID:drone-plugins,項目名稱:drone-slack-blame,代碼行數:67,代碼來源:plugin.go

示例10: ReplyWithAttachments

// ReplyWithAttachments replys to a message event with a Slack Attachments message.
func (b *Bot) ReplyWithAttachments(evt *slack.MessageEvent, attachments []slack.Attachment, typing bool) {
	params := slack.PostMessageParameters{AsUser: true}
	params.Attachments = attachments

	b.Client.PostMessage(evt.Msg.Channel, "", params)
}
開發者ID:Ripleather,項目名稱:starter-go-bot,代碼行數:7,代碼來源:bot.go

示例11: pull

func pull(rtm *slack.RTM, o Opts) {
	/*
		Using a FIFO queue
	*/
	t := time.Now()
	ts := t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")
	rc, err := cluster.NewCluster(o.redis_connection)

	if err != nil {
		fmt.Printf("[%s] ERROR Redis connection error: %s\n", ts, err)
		os.Exit(1)
	}
	r := rc.Cmd("SELECT", o.redis_db)

	for {
		t = time.Now()
		ts = t.Format("Mon Jan 2 15:04:05 -0700 MST 2006")
		r = rc.Cmd("RPOP", o.redis_list)

		switch r.Type {
		case redis.ErrorReply:
			fmt.Printf("[%s] ERROR ErrorReply received: %s\n", ts, r.Err.Error())
		case redis.NilReply:
			if o.debug {
				fmt.Printf("[%s] INFO NilReply reply received\n", ts)
			}
		case redis.StatusReply:
			if o.debug {
				fmt.Printf("[%s] INFO StatusReply reply received: not processing\n", ts)
			}
		case redis.BulkReply:
			// Send to Slack
			data, err := r.Bytes()
			if err != nil {
				fmt.Printf("[%s] ERROR Error received: %s\n", ts, err)
			} else {
				if o.json {
					type Message struct {
						Name   string
						Source string
						Detail string
					}
					var message Message
					err := json.Unmarshal(data, &message)
					if err != nil {
						fmt.Printf("[%s] ERROR Error received: %s\n", ts, err)
					}
					params := slack.PostMessageParameters{
						Username: "hal9000",
					}
					attachment := slack.Attachment{
						Pretext: message.Source,
						Text:    message.Detail,
					}
					params.Attachments = []slack.Attachment{attachment}

					channelID, timestamp, err := rtm.PostMessage(o.slack_channel, string(message.Name), params)
					if err != nil {
						fmt.Printf("[%s] ERROR Error received: %s\n", ts, err)
						return
					}
					if o.debug {
						fmt.Printf("[%s] INFO Message %+v successfully sent to channel %s at %s", ts, message, channelID, timestamp)
					}
				} else {
					if o.debug {
						fmt.Printf("[%s] INFO BulkReply reply received: %s\n", ts, data)
					}
					rtm.SendMessage(rtm.NewOutgoingMessage(string(data), o.slack_channel))
				}
			}
		case redis.MultiReply:
			if o.debug {
				fmt.Printf("[%s] INFO MultiReply reply received: not processing\n", ts)
			}
		case redis.IntegerReply:
			if o.debug {
				fmt.Printf("[%s] INFO IntegerReply reply received: not processing\n", ts)
			}
		default:
			if o.debug {
				fmt.Printf("[%s] INFO Unknown reply received: not processing\n", ts)
			}
		}

		time.Sleep(time.Duration(o.watch_interval) * time.Millisecond)
	}
}
開發者ID:andrew-sledge,項目名稱:hal,代碼行數:88,代碼來源:hal.go

示例12: postDigest

// Post summary to Slack channel
func postDigest() {

	channel := os.Getenv("DIGEST_CHANNEL")
	botToken := os.Getenv("BOT_TOKEN")

	if botToken == "" {
		log.Fatal("No token provided")
		os.Exit(1)
	}

	s := slack.New(botToken)
	users, err := s.GetUsers()

	if err != nil {
		log.Fatal("Cannot get users")
		os.Exit(1)
	}

	ctx, err := db.NewContext()
	if err != nil {
		panic(err)
	}

	defer ctx.Close()

	log.Info("Preparing data")
	// If count > 0, it means there is data to show
	count := 0
	title := " >> Yesterday I did: "
	params := slack.PostMessageParameters{}
	fields := []slack.AttachmentField{}

	yesterday := arrow.Yesterday().UTC()
	toDate := time.Date(yesterday.Year(), yesterday.Month(), yesterday.Day(), 0, 0, 0, 0, time.UTC)

	// Prepare attachment of done items
	for _, user := range users {

		if user.IsBot || user.Deleted {
			continue
		}

		// log.Info("Process user: " + user.Name + " - " + user.Id)

		// Query done items from Database
		var values string
		var items []Item

		err = ctx.C("items").Find(bson.M{"$and": []bson.M{
			bson.M{"user_id": user.Id},
			bson.M{"created_at": bson.M{"$gt": toDate}},
		},
		}).All(&items)

		if err != nil {
			log.Fatal("Cannot query done items.")
			os.Exit(1)
		}

		for _, item := range items {
			values = values + " + " + item.Text + "\n\t"
		}

		// <@U024BE7LH|bob>
		if len(items) > 0 {

			count = count + 1
			field := slack.AttachmentField{
				Title: "@" + user.Name,
				Value: values,
			}

			fields = append(fields, field)
		}
	}

	params.Attachments = []slack.Attachment{
		slack.Attachment{
			Color:  "#7CD197",
			Fields: fields,
		},
	}

	params.IconURL = "http://i.imgur.com/fLcxkel.png"
	params.Username = "oshin"

	if count > 0 {
		s.PostMessage(channel, title, params)
	}
}
開發者ID:dwarvesf,項目名稱:working-on,代碼行數:91,代碼來源:main.go

示例13:

					Value: sensuhandler.DefineSensuEnv(sensuEnv.Sensu.Environment),
					Short: true,
				},
				slack.AttachmentField{
					Title: "Check Event ID",
					Value: sensuEvent.ID,
					Short: true,
				},
				slack.AttachmentField{
					Title: "Check Output",
					Value: sensuhandler.CleanOutput(sensuEvent.Check.Output),
					Short: true,
				},
			},
		}
		params.Attachments = []slack.Attachment{attachment}
		_, _, err := api.PostMessage(channelID, "", params)
		if err != nil {
			syslogLog.WithFields(logrus.Fields{
				"check":   "sensupluginsslack",
				"client":  host,
				"version": version.AppVersion(),
				"error":   err,
			}).Error(`Slack attachment could not be sent`)
			sensuutil.Exit("RUNTIMEERROR")
		}
		syslogLog.WithFields(logrus.Fields{
			"check":   "sensupluginsslack",
			"client":  host,
			"version": version.AppVersion(),
		}).Error(`Slack attachment has been sent`)
開發者ID:yieldbot,項目名稱:sensupluginsslack,代碼行數:31,代碼來源:handlerSlack.go

示例14: sendMessage

func (s *Client) sendMessage(issue *redmine.Issue, channel string) (err error) {
	params := slackapi.PostMessageParameters{}
	params.IconURL = botLogo
	params.Username = "Redmine Bot"

	fields := make([]slackapi.AttachmentField, 6)
	var idx int = 3

	fields[0] = slackapi.AttachmentField{
		Title: "Project",
		Value: issue.Project.Name,
		Short: true,
	}
	fields[1] = slackapi.AttachmentField{
		Title: "Status",
		Value: issue.Status.Name,
		Short: true,
	}
	fields[2] = slackapi.AttachmentField{
		Title: "Author",
		Value: issue.Author.Name,
		Short: true,
	}
	if issue.AssignedTo != nil {
		fields[idx] = slackapi.AttachmentField{
			Title: "Assigned To",
			Value: issue.AssignedTo.Name,
			Short: true,
		}
		idx += 1
	}
	if issue.Category != nil {
		fields[idx] = slackapi.AttachmentField{
			Title: "Category",
			Value: issue.Category.Name,
			Short: true,
		}
		idx += 1
	}
	if issue.Version != nil {
		fields[idx] = slackapi.AttachmentField{
			Title: "Version",
			Value: issue.Version.Name,
			Short: true,
		}
	}

	var title string
	if issue.Tracker != nil {
		title = fmt.Sprintf("%s #%d: %s", issue.Tracker.Name, issue.Id, issue.Subject)
	} else {
		title = fmt.Sprintf("#%d: %s", issue.Id, issue.Subject)
	}

	attachment := slackapi.Attachment{
		Title:     title,
		TitleLink: s.redmine.GetIssueUrl(issue),
		Fields:    fields,
	}

	if s.redmine.IssueIsClosed(issue) {
		attachment.Color = "good"
	} else if s.redmine.IssueInHighPriority(issue) {
		attachment.Color = "danger"
	}

	params.Attachments = []slackapi.Attachment{attachment}

	_, _, err = s.slack.PostMessage(channel, "", params)

	return err
}
開發者ID:muxx,項目名稱:slack-redmine-bot,代碼行數:72,代碼來源:slack.go

示例15: main

func main() {
	fmt.Printf("Drone Slack Blame Plugin built at %s\n", buildDate)

	repo := plugin.Repo{}
	build := plugin.Build{}
	system := plugin.System{}
	vargs := Slack{}

	plugin.Param("build", &build)
	plugin.Param("system", &system)
	plugin.Param("repo", &repo)
	plugin.Param("vargs", &vargs)

	// parse the parameters
	if err := plugin.Parse(); err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	// setup the message
	buildLink := fmt.Sprintf("%s/%s/%d", system.Link, repo.FullName, build.Number)
	var messageOptions MessageOptions
	var color string
	var messageText string
	var channelText string

	// Determine if the build was a success
	if build.Status == "success" {
		messageOptions = vargs.Success
		color = "good"
		messageText = fmt.Sprintf("Build succeeded at %s", buildLink)
		channelText = "Thanks"
	} else {
		messageOptions = vargs.Failure
		color = "danger"
		messageText = fmt.Sprintf("Build failed at %s", buildLink)
		channelText = "Blame"
	}

	// set default values
	if len(messageOptions.Username) == 0 {
		messageOptions.Username = "drone"
	}

	if len(messageOptions.Icon) == 0 {
		messageOptions.Icon = ":drone:"
	}

	if len(messageOptions.ImageAttachments) == 0 {
		messageOptions.ImageAttachments = []string{""}
	}

	// setup the message
	messageParams := slack.PostMessageParameters{
		Username:  messageOptions.Username,
		IconEmoji: messageOptions.Icon,
	}

	imageCount := len(messageOptions.ImageAttachments)
	rand.Seed(time.Now().UTC().UnixNano())

	attachment := slack.Attachment{
		Color:    color,
		Text:     messageText,
		ImageURL: messageOptions.ImageAttachments[rand.Intn(imageCount)],
	}

	messageParams.Attachments = []slack.Attachment{attachment}

	// get the commit author
	commitAuthor := build.Email

	// create the slack api
	api := slack.New(vargs.Token)

	// get the users
	//
	// Slack doesn't let you search by email so just need to get
	// everything and find the user in question
	var blameUser *slack.User

	users, _ := api.GetUsers()

	for _, user := range users {
		if user.Profile.Email == commitAuthor {
			fmt.Printf("%s\n", user.Name)
			fmt.Printf("%s\n", user.Profile.Email)
			blameUser = &user
			break
		}
	}

	// notify the user if possible
	var userAt string

	if blameUser != nil {
		userAt = fmt.Sprintf("@%s", blameUser.Name)

		// send the message to the user's channel
		//
//.........這裏部分代碼省略.........
開發者ID:dearing,項目名稱:drone-slack-blame,代碼行數:101,代碼來源:main.go


注:本文中的github.com/nlopes/slack.PostMessageParameters.Attachments方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。