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


Golang slack.PostMessageParameters類代碼示例

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


在下文中一共展示了PostMessageParameters類的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: listenToMessages

func (sl slackService) listenToMessages(msg PortalMessage) {
	if msg.Kind == PORTAL_MESSAGE {
		params := slack.PostMessageParameters{}
		params.Username = msg.Author
		_, time, err := sl.api.PostMessage(sl.channel, msg.Data, params)
		if err != nil {
			fmt.Println(err)
		}
		sl.sent[time] = true
	}
}
開發者ID:spb-frontend,項目名稱:portal,代碼行數:11,代碼來源:slack.go

示例4: addItem

// Message will be passed to server with '-' prefix via various way
//	+ Direct message with the bots
//	+ Use slash command `/working <message>`
//	+ Use cli `working-on <message>`
//	+ Might use Chrome plugin
//	+ ...
// Token is secondary param to indicate the user
func addItem(c *gin.Context) {

	// Parse token and message
	var item Item

	text := c.PostForm("text")
	text = strings.TrimSpace(text)

	if text == "" {
		log.Fatalln("Message is nil")
		return
	}

	userID := c.PostForm("user_id")
	userName := c.PostForm("user_name")

	item.ID = bson.NewObjectId()
	item.CreatedAt = time.Now()
	item.Name = userName
	item.UserID = userID
	item.Text = text

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

	defer ctx.Close()

	// Add Item to database
	err = ctx.C("items").Insert(item)
	if err != nil {
		log.Fatalln(err)
	}

	// Repost to the target channel
	channel := os.Getenv("WORKING_CHANNEL")
	botToken := os.Getenv("BOT_TOKEN")

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

	s := slack.New(botToken)
	// <@U024BE7LH|bob>
	title := "*" + userName + "* is working on: " + text

	params := slack.PostMessageParameters{}
	params.IconURL = "http://i.imgur.com/fLcxkel.png"
	params.Username = "oshin"
	s.PostMessage(channel, title, params)
}
開發者ID:dwarvesf,項目名稱:working-on,代碼行數:60,代碼來源:main.go

示例5: 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

示例6: handleChat

func (s *Slack) handleChat(action string, params map[string]string) (interface{}, error) {
	var v interface{}
	var err error

	switch action {
	case "delete":
		ch, ts, err := s.s.DeleteMessage(params["channel"], params["ts"])
		if err != nil {
			return nil, err
		}
		v = map[string]string{
			"channel": ch,
			"ts":      ts,
		}
	case "postmessage":
		postParam := slack.PostMessageParameters{}
		postParam.Username = getStringParam(params, "username", slack.DEFAULT_MESSAGE_USERNAME)
		postParam.Parse = getStringParam(params, "parse", slack.DEFAULT_MESSAGE_PARSE)
		postParam.LinkNames = getIntParam(params, "link_names", slack.DEFAULT_MESSAGE_LINK_NAMES)

		postParam.UnfurlLinks = getBoolParam(params, "unfurl_links", slack.DEFAULT_MESSAGE_UNFURL_LINKS)
		postParam.UnfurlMedia = getBoolParam(params, "unfurl_media", slack.DEFAULT_MESSAGE_UNFURL_MEDIA)
		postParam.IconURL = getStringParam(params, "icon_url", slack.DEFAULT_MESSAGE_ICON_URL)
		postParam.IconEmoji = getStringParam(params, "icon_emoji", slack.DEFAULT_MESSAGE_ICON_EMOJI)

		if err = json.Unmarshal([]byte(getStringParam(params, "attachments", "[]")), &postParam.Attachments); err != nil {
			return nil, err
		}

		ch, ts, err := s.s.PostMessage(params["channel"], params["text"], postParam)
		if err != nil {
			return nil, err
		}

		v = map[string]string{
			"channel": ch,
			"ts":      ts,
		}
	case "update":
		ch, ts, text, err := s.s.UpdateMessage(params["channel"], params["ts"], params["text"])
		if err != nil {
			return nil, err
		}
		v = map[string]string{
			"channel": ch,
			"ts":      ts,
			"text":    text,
		}
	default:
		return nil, fmt.Errorf("invalid chat action %s", action)
	}

	return v, err
}
開發者ID:GenPage,項目名稱:slack-cli,代碼行數:54,代碼來源:slack.go

示例7: 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

示例8: 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

示例9: 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

示例10: notifier

func notifier() {
	api := slack.New(config.SlackToken)
	params := slack.PostMessageParameters{}
	if len(config.SlackUserName) >= 0 {
		params.Username = config.SlackUserName
	}
	params.Markdown = true

	for {
		select {
		case notification := <-nChan:
			_, _, err := api.PostMessage(config.SlackChannel, notification.Body, params)
			if err != nil {
				log.Println("Error while sending Slack message:\n", notification.Body)
				log.Println("Detail:\n", err)
				// TODO: Add a message queue for retry sending
				continue
			}
			log.Println("Message successfully sent")
		}
	}
}
開發者ID:kfei,項目名稱:ptt-watcher,代碼行數:22,代碼來源:slack.go

示例11: 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

示例12: 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

示例13: main

func main() {
	flag.Parse()

	// Read config block
	config := &configStruct{}
	userJSON, err := ioutil.ReadFile(*configFile)
	if err != nil {
		panic("ReadFile json failed")
	}
	if err = json.Unmarshal(userJSON, &config); err != nil {
		panic("Unmarshal json failed")
	}

	api := slack.New(config.Token)
	api.SetDebug(config.Debug)

	rtm := api.NewRTM()
	go rtm.ManageConnection()

	postParams := slack.PostMessageParameters{}
	postParams.Username = "dutybot"
	postParams.Parse = "full"
	postParams.IconEmoji = ":runner:"

	// Get Duty users

Loop:
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			switch ev := msg.Data.(type) {
			case *slack.HelloEvent:

			case *slack.ConnectedEvent:
				fmt.Println("Infos:", ev.Info)
				fmt.Println("Connection counter:", ev.ConnectionCount)

				botID = ev.Info.User.ID

				updateDutyGroup(api, config.DutyGroup)

			case *slack.MessageEvent:

				if ev.SubType == "channel_leave" || ev.SubType == "channel_join" {
					updateDutyGroup(api, config.DutyGroup)
					fmt.Printf("%s %s\n", ev.SubType, ev.User)
				}

				if strings.Contains(ev.Text, botID) {
					if onDuty.Name != "" {
						_, _, err := rtm.PostMessage(ev.Channel, fmt.Sprintf(config.MessageDuty, onDuty.Name), postParams)
						if err != nil {
							fmt.Printf("%s\n", err)
						}
					} else {
						_, _, err := rtm.PostMessage(ev.Channel, config.MessageNoDuty, postParams)
						if err != nil {
							fmt.Printf("%s\n", err)
						}
					}

				} else if strings.Contains(ev.Text, "@onduty") {

					slackUser, err := rtm.GetUserInfo(ev.User)
					if err != nil {
						fmt.Printf("%s\n", err)
					}

					if stringInSlice(slackUser.ID, dutyMembers) {

						onDuty = *slackUser
						_, _, err = rtm.PostMessage(ev.Channel, fmt.Sprintf(config.MessageOnDuty, onDuty.Name), postParams)
						if err != nil {
							fmt.Printf("%s\n", err)
						}

					} else {

						_, _, err = rtm.PostMessage(ev.Channel, fmt.Sprintf(config.MessageNotInDutyGroup, slackUser.Name), postParams)
						if err != nil {
							fmt.Printf("%s\n", err)
						}
					}

				} else if strings.Contains(ev.Text, "@offduty") {

					slackUser, err := rtm.GetUserInfo(ev.User)
					if err != nil {
						fmt.Printf("%s\n", err)
					}

					if onDuty.ID == ev.User {
						_, _, err := rtm.PostMessage(ev.Channel, fmt.Sprintf(config.MessageOffDuty, onDuty.Name), postParams)
						if err != nil {
							fmt.Printf("%s\n", err)
						}
						onDuty = slack.User{}
					} else {
						_, _, err := rtm.PostMessage(ev.Channel, fmt.Sprintf(config.MessageNotDuty, slackUser.Name), postParams)
						if err != nil {
//.........這裏部分代碼省略.........
開發者ID:ewok,項目名稱:tools,代碼行數:101,代碼來源:main.go

示例14: sendMessage

func sendMessage(api slack.Client, channel string, message string) error {
	params := slack.PostMessageParameters{}
	params.LinkNames = 1
	_, _, err := api.PostMessage(channel, message, params)
	return err
}
開發者ID:IBM-Bluemix,項目名稱:slack-pester-non-2fa-users,代碼行數:6,代碼來源:slack-disable-2fa.go

示例15: 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


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