Пример #1
0
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
}
Пример #2
0
// Publish Publishes messages to slack
func (x Slack) Publish(publishMsgs <-chan models.Message, connector models.Connector) {
	api := slack.New(connector.Key)
	for {
		message := <-publishMsgs
		msg := ""
		params := slack.NewPostMessageParameters()
		params.Username = connector.BotName
		params.IconEmoji = connector.Image
		if message.Out.Detail != "" {
			color := slackColorMe(message.Out.Status)
			attachment := slack.Attachment{
				Title:      message.Out.Text,
				TitleLink:  message.Out.Link,
				Text:       message.Out.Detail,
				Color:      color,
				MarkdownIn: []string{"text"},
			}
			params.Attachments = []slack.Attachment{attachment}
		} else {
			msg = message.Out.Text
		}
		for _, target := range strings.Split(message.Out.Target, ",") {
			if target == "*" {
				target = message.In.Target
			}
			if target != "" && target != "*" {
				api.PostMessage(target, msg, params)
			}
		}
	}
}
Пример #3
0
func main() {
	// api := slack.New("xoxb-14316137920-HnYQrHOS7pOtkLKEDRh1i30w")
	api := slack.New("xoxp-8035809824-8036215361-17780810228-8a32658b4c")
	params := slack.FileUploadParameters{
		Title:    "New Markdown Example",
		Filetype: "post",
		Filename: "example.md",
		// File: "example.md",
		Content:        "# hello world!\n*italics*\n**bold**\n`code`\n",
		InitialComment: "whoa, programmatic post creation!",
		Channels:       []string{"#hubotix"},
	}
	file, err := api.UploadFile(params)
	if err != nil {
		fmt.Printf("%s\n", err)
		return
	}
	fmt.Printf("%+v\n", file)

	/*
		err = api.DeleteFile(file.ID)
		if err != nil {
			fmt.Printf("%s\n", err)
			return
		}
		fmt.Printf("File %s deleted successfully.\n", file.Name)
	*/
}
Пример #4
0
// Run connects to slack RTM API using the provided token
func Run(token string) {
	api = slack.New(token)
	rtm = api.NewRTM()

	b := bot.New(&bot.Handlers{
		Response: responseHandler,
	})
	b.Disable([]string{"url"})

	go rtm.ManageConnection()

Loop:
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			switch ev := msg.Data.(type) {
			case *slack.MessageEvent:
				b.MessageReceived(ev.Channel, ev.Text, extractUser(ev.User))

			case *slack.RTMError:
				fmt.Printf("Error: %s\n", ev.Error())

			case *slack.InvalidAuthEvent:
				fmt.Printf("Invalid credentials")
				break Loop
			}
		}
	}
}
Пример #5
0
func main() {
	args, err := docopt.Parse(
		strings.Replace(usage, "$0", os.Args[0], -1),
		nil, true, "slack-topic-setter 1.0", false,
	)
	if err != nil {
		panic(err)
	}

	var additionalParameters map[string]interface{}
	if args["-i"].(bool) {
		stdinDecoder := json.NewDecoder(os.Stdin)
		err := stdinDecoder.Decode(&additionalParameters)
		if err != nil {
			log.Printf("error reading stdin: %s", err)
			return
		}
	}

	api := &API{
		slack.New(args["-k"].(string)),
		additionalParameters,
	}

	switch {
	case args["-C"]:
		err = api.handleChannelMode(args)
	}

	if err != nil {
		log.Printf("error: %s", err)
	}
}
Пример #6
0
// getChannels send a request to the slack with user's token & gets the channels
func getChannels(token string) (*SlackChannelsResponse, error) {
	api := slack.New(token)
	var groups []slack.Group
	var channels []slack.Channel
	var gerr, cerr error
	var wg sync.WaitGroup
	wg.Add(2)

	go func() {
		groups, gerr = api.GetGroups(true)
		wg.Done()
	}()

	go func() {
		channels, cerr = api.GetChannels(true)
		wg.Done()
	}()

	wg.Wait()

	if gerr != nil {
		return nil, gerr
	}

	if cerr != nil {
		return nil, cerr
	}

	return &SlackChannelsResponse{
		Groups:   groups,
		Channels: channels,
	}, nil
}
Пример #7
0
func main() {
	slackToken := os.Getenv("ARCHIVEBOT_SLACK_TOKEN")
	api := slack.New(slackToken)
	//api.SetDebug(true)

	channels, err := api.GetChannels(true)
	if err != nil {
		log.Printf("Error when loading channels: %s\n", err)
		return
	}

	var wg sync.WaitGroup
	wg.Add(2)

	go func(c []slack.Channel) {
		defer wg.Done()
		archiveEmptyChannels(api, c)
	}(channels)

	go func(c []slack.Channel) {
		defer wg.Done()
		archiveInactiveChannels(api, c)
	}(channels)

	wg.Wait()
}
Пример #8
0
// Listen Listens to slack messages in channels Jane is present in
func (x Slack) Listen(commandMsgs chan<- models.Message, connector models.Connector) {
	defer Recovery(connector)
	api := slack.New(connector.Key)
	api.SetDebug(connector.Debug)
	rtm := api.NewRTM()
	if connector.Debug {
		log.Print("Starting slack websocket api for " + connector.ID)
	}
	go rtm.ManageConnection()
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			switch ev := msg.Data.(type) {
			case *slack.MessageEvent:
				if ev.User != "" {

					if connector.Debug {
						log.Print("Evaluating incoming slack message")
					}

					var m models.Message
					m.In.ConnectorType = connector.Type
					m.In.ConnectorID = connector.ID
					m.In.Tags = connector.Tags
					m.In.Target = ev.Channel
					m.In.User = ev.User
					m.In.Text = html.UnescapeString(ev.Text)
					m.In.Process = true
					commandMsgs <- m

				}
			}
		}
	}
}
Пример #9
0
func doSlack(apiToken string) {
	api := slack.New(apiToken)
	rtm := api.NewRTM()
	go rtm.ManageConnection()

	mention := ""
	for msg := range rtm.IncomingEvents {
		switch ev := msg.Data.(type) {
		case *slack.ConnectedEvent:
			mention = "<@" + ev.Info.User.ID + ">"
			if ev.ConnectionCount == 1 {
				log.Printf("bot [%s] ready", ev.Info.User.Name)
				log.Print("hit ^C to exit")
			} else {
				log.Printf("bot [%s] reconnected", ev.Info.User.Name)
			}
		case *slack.MessageEvent:
			if strings.HasPrefix(ev.Msg.Text, mention) {
				t := strings.TrimPrefix(ev.Msg.Text, mention)
				go func(text, ch string) {
					r := process(text)
					rtm.SendMessage(rtm.NewOutgoingMessage(r, ch))
				}(t, ev.Msg.Channel)
			}
		case *slack.InvalidAuthEvent:
			log.Print("bad Slack API token")
			os.Exit(1)
		}
	}
}
Пример #10
0
func NewSlack(name, icon, token string) *Slack {
	return &Slack{
		Name:   name,
		Icon:   icon,
		Client: slack.New(token),
	}
}
Пример #11
0
// Notify is function to notify slack.
func (s *Slack) Notify(body string, attachments [][]*multipart.FileHeader) {
	// auth
	api := slack.New(s.Token)

	for _, tmp := range attachments {
		for _, attachment := range tmp {
			fileURL, err := upSlack(api, attachment)
			if err != nil {
				log.Errorf("upload slack error: %v", err)
			} else {
				// add url to body
				body += fmt.Sprintln(fileURL)
			}
		}
	}

	api.PostMessage(s.Channel, body, slack.PostMessageParameters{
		Username:    s.Username,
		AsUser:      s.AsUser,
		UnfurlLinks: s.UnfurlLinks,
		UnfurlMedia: s.UnfurlMedia,
		IconURL:     s.IconURL,
		IconEmoji:   s.IconEmoji,
	})

}
Пример #12
0
func StartBot() {
	log.Printf("stats-bot: v%v#%v", Version, Commit)

	go StartHTTPServer() // Has to run in a Goroutine.  Blocks
	bot := slack.New(Config.Token)

	Census = census.NewCensus("s:maximumtwang", "ps2ps4us:v2")
	CensusEU = census.NewCensus("s:maximumtwang", "ps2ps4eu:v2")

	StartPopGathering()

	t, err := bot.AuthTest()
	if err != nil {
		log.Printf("Error in auth test: [%v]", err.Error())
		return
	}

	log.Printf("Auth: %v on team %v", t.User, t.Team)

	rtm := bot.NewRTM()
	go rtm.ManageConnection()
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			switch m := msg.Data.(type) {
			case *slack.MessageEvent:
				Dispatch(&Context{Bot: bot, Ev: m, RTM: rtm})
			}
		}
	}
}
Пример #13
0
func (p *slackInput) Start() error {
	if len(p.token) == 0 {
		return errors.New("missing slack token")
	}

	p.Lock()
	defer p.Unlock()

	if p.running {
		return nil
	}

	api := slack.New(p.token)
	api.SetDebug(p.debug)

	// test auth
	_, err := api.AuthTest()
	if err != nil {
		return err
	}

	p.api = api
	p.exit = make(chan bool)
	p.running = true
	return nil
}
Пример #14
0
func (s *Slack) GetUsers() ([]*SlackUser, error) {
	log.WithFields(log.Fields{
		"account_id": s.AccountID,
		"token":      s.Token,
	}).Info("Bridges::Slack::GetUsers started")

	c := slack.New(s.Token)

	svcUsers, err := c.GetUsers()
	if err != nil {
		log.WithFields(log.Fields{
			"account_id": s.AccountID,
			"error":      err,
		}).Error("Bridges::Slack::GetUsers error")
	}

	var users []*SlackUser

	for _, u := range svcUsers {
		if u.Deleted || u.IsBot || u.IsRestricted || u.IsUltraRestricted {
			continue
		}

		users = append(users, &SlackUser{
			ID:    u.Id,
			Email: u.Profile.Email,
			Name:  u.Profile.RealName,
			Title: u.Profile.Title,
		})
	}

	return users, err
}
Пример #15
0
func main() {
	var wg sync.WaitGroup
	jiraHostURL = os.Getenv(jiraURL)
	jiraUserName = os.Getenv(jiraUser)
	jiraiUserPassword = os.Getenv(jiraPassword)
	slackAPIToken = os.Getenv(slackToken)
	url, _ := url.Parse(jiraHostURL)
	Client = NewClient(jiraUserName, jiraiUserPassword, url)
	Slack = slack.New(slackAPIToken)
	Slack.SetDebug(false)
	Client.GetProjects()
	buildPattern()
	rtm := Slack.NewRTM()
	go rtm.ManageConnection()

Loop:
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			switch ev := msg.Data.(type) {
			case *slack.MessageEvent:
				if ev.SubType != "bot_message" {
					wg.Add(1)
					go processEvents(ev.Text, ev.Channel, wg)
				}
			case *slack.InvalidAuthEvent:
				fmt.Printf("Invalid credentials")
				break Loop
			default:
				// Ignore other events..
			}
		}
	}
	wg.Wait()
}
Пример #16
0
func Record(authorID string, category string, text string, slackToken string) error {
	if len(strings.TrimSpace(text)) == 0 {
		return errors.New("Empty note given.")
	}

	var authorName, avatarURL string

	api := slack.New(slackToken)
	user, err := api.GetUserInfo(authorID)
	text, category = effectiveTextAndCategory(text, category)

	if err == nil {
		authorName = user.Profile.RealName
		avatarURL = user.Profile.Image48
	} else {
		fmt.Printf("Error getting author information from Slack: %s\n", err)
		authorName = authorID
		avatarURL = ""
	}

	text = strings.TrimSpace(strings.TrimPrefix(text, category))
	note := Note{authorName, avatarURL, category, text}

	AddNote(note)
	if len(os.Getenv("TESTING")) == 0 {
		notifyRoom(api, note)
	}
	return nil
}
Пример #17
0
func main() {
	api := slack.New(SLACK_TOKEN)
	rtm := api.NewRTM()

	go rtm.ManageConnection()

Loop:
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			fmt.Print("Event Received: ")
			switch ev := msg.Data.(type) {
			case *slack.TeamJoinEvent:
				welcomeUser(ev.User.ID, api)
			case *slack.LatencyReport:
				fmt.Printf("Current latency: %v\n", ev.Value)

			case *slack.RTMError:
				fmt.Printf("Error: %s\n", ev.Error())

			case *slack.InvalidAuthEvent:
				fmt.Printf("Invalid credentials")
				break Loop

			default:

				// Ignore other events..
				// fmt.Printf("Unexpected: %v\n", msg.Data)
			}
		}
	}
}
Пример #18
0
func NewSlackClient(ctx context.Context, name string, token string) context.Context {
	c := SlackClient{}
	c.Client = slack.New(token)
	c.Name = name
	c.Token = token
	return context.WithValue(ctx, slackClientKey, c)
}
Пример #19
0
func main() {
	var (
		debug            bool
		historyDaysLimit int
	)

	flag.Usage = usage
	flag.BoolVar(&debug, "debug", false, "Print debug information")
	flag.IntVar(&historyDaysLimit, "history-limit", 7, "History limit (in days)")
	flag.Parse()
	if len(flag.Args()) < 1 || historyDaysLimit < 1 {
		usage()
		os.Exit(1)
	}

	logrus.SetOutput(os.Stderr)
	if debug {
		logrus.SetLevel(logrus.DebugLevel)
	}

	api := slack.New(flag.Arg(0))
	api.SetDebug(debug)

	newArriba(api.NewRTM(), historyDaysLimit).run()
}
Пример #20
0
func (rt ReconTask) performTask(task ActionItemConfig, stringContext map[string]interface{}) {
	rt.log.Debug("Task Config - %v", task.Config)
	switch task.Type {
	case "sendToSlack":
		message := EvaluateTemplate(task.Config["message"].(string), stringContext)
		slackClient := slack.New(task.Config["slackKey"].(string))
		slackClient.PostMessage(task.Config["slackTo"].(string), message, slack.NewPostMessageParameters())
	case "executeMysql":
		query := EvaluateTemplate(task.Config["query"].(string), stringContext)
		params := task.Config["params"].([]interface{})
		paramValues := make([]interface{}, 0)
		for _, param := range params {
			paramValue := EvaluateTemplate(param.(string), stringContext)
			paramValues = append(paramValues, paramValue)
		}
		endPoint, err := NewMysqlDataProvider(task.Config["mysqlConfig"].(map[string]interface{}))
		if err != nil {
			rt.log.Error("Failed to connect to mysql - %v", err)
		}
		stmt, err := endPoint.db.Prepare(query)
		if err != nil {
			rt.log.Error("Failed to prepare statement- %v", err)
		}
		defer stmt.Close()
		rt.log.Info("Executing [%s] with params [%v]", query, paramValues)
		result, err := stmt.Exec(paramValues...)
		if err != nil {
			rt.log.Error("Failed to Execute query - %v", err)
		}
		count, _ := result.RowsAffected()
		if count < 1 {
			rt.log.Info("0 rows affected, might want to check - %v", stringContext)
		}
	}
}
Пример #21
0
func main() {
	api := slack.New(os.Getenv("SLACK_BOT_TOKEN"))
	api.SetDebug(true)
	rtm := api.NewRTM()
	go rtm.ManageConnection()
	handleMessage(rtm)
}
Пример #22
0
// New constructs a new Bot using the slackToken to authorize against the Slack service.
func New(slackToken string) *Bot {
	strg := &MemoryStorage{data: map[string]string{}}
	strg.load()
	b := &Bot{Client: slack.New(slackToken), StorageAdapter: strg}

	return b
}
Пример #23
0
func main() {
	token := os.Getenv("SLACK_TOKEN")
	if token == "" {
		log.Fatal("SLACK_TOKEN is required")
	}

	api := slack.New(token)
	bot := Bot{}

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

Loop:
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			switch ev := msg.Data.(type) {
			case *slack.ConnectedEvent:
				bot.setMe(ev.Info.User.ID)

			case *slack.MessageEvent:
				if bot.amIMentioned(ev.Msg.Text) {
					rtm.SendMessage(rtm.NewOutgoingMessage(bot.returnGreeting(ev.Msg.User), ev.Channel))
				}

			case *slack.RTMError:
				log.Printf("Error: %s\n", ev.Error())

			case *slack.InvalidAuthEvent:
				log.Fatal("Invalid credentials")
				break Loop
			}
		}
	}
}
Пример #24
0
// Init initialize slack API token
func Init(host Host) error {
	SlackToken = slack.New(host.TokenID)
	LogChannel = host.ChannelID
	tokenID = host.TokenID

	return nil
}
Пример #25
0
// RunSlack connects to slack RTM API using the provided token
func RunSlack(token string) {
	api := slack.New(token)

	conn := new(slackConnection)
	conn.rtm = api.NewRTM()
	go conn.rtm.ManageConnection()

Loop:
	for {
		select {
		case msg := <-conn.rtm.IncomingEvents:
			switch ev := msg.Data.(type) {
			case *slack.MessageEvent:
				messageReceived(ev.Channel, ev.Text, ev.User, conn)

			case *slack.RTMError:
				fmt.Printf("Error: %s\n", ev.Error())

			case *slack.InvalidAuthEvent:
				fmt.Printf("Invalid credentials")
				break Loop
			}
		}
	}
}
Пример #26
0
// Boot the upper part of the application.
func (p *Phabulous) Boot(c *cli.Context) {
	if c.GlobalString("config") != "" {
		err := p.Config.ReadPaths(c.GlobalString("config"))

		if err != nil {
			p.Logger.Panic(err)
		}

		p.Logger.Infoln(
			"Loaded alternate configuration file from: " +
				c.GlobalString("config") + ".",
		)
	}

	if p.Config.GetBool("server.debug") {
		p.Logger.Level = logrus.DebugLevel
		p.Logger.Debugln("Logger is debug level.")
	} else {
		p.Logger.Level = logrus.WarnLevel
	}

	p.Slacker.Slack = slack.New(
		p.Config.GetString("slack.token"),
	)

	p.Logger.Debugln("Booted upper layer.")
}
Пример #27
0
func NewSlack(token, channel, channelId string) slackService {
	api := slack.New(token)
	rtm := api.NewRTM()
	go rtm.ManageConnection()
	cache := make(map[string]*slack.User)
	return slackService{token, channel, channelId, "slack", api, rtm, cache, make(map[string]bool)}
}
Пример #28
0
func main() {
	token := os.Getenv(tokenKey)
	api := slack.New(token)
	//api.SetDebug(true)

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

	// Load the questionBot service
	q, e := questionBot.NewService(questionBot.Config{DataPath: "./questionnaires.toml"})
	if e != nil {
		log.Fatal(e)
	}
	qbot = q

Loop:
	for {
		select {
		case msg := <-rtm.IncomingEvents:
			fmt.Print("Event Received: ")
			switch ev := msg.Data.(type) {
			case *slack.HelloEvent:
				// Ignore hello

			case *slack.ConnectedEvent:
				info := rtm.GetInfo()
				fmt.Println("Connection counter:", ev.ConnectionCount)
				rtm.SendMessage(rtm.NewOutgoingMessage(info.User.Name+" reporting for duty!", ev.Info.Channels[0].ID))

			case *slack.MessageEvent:
				info := rtm.GetInfo()
				prefix := fmt.Sprintf("<@%s>: ", info.User.ID)
				log.Println("prefix: ", prefix, " msg: ", ev.Text)
				if ev.User != info.User.ID && strings.HasPrefix(ev.Text, prefix) {
					respond(rtm, ev, prefix)
					fmt.Printf("Message: %v\n", ev)
				}

			case *slack.PresenceChangeEvent:
				fmt.Printf("Presence Change: %v\n", ev)

			case *slack.LatencyReport:
				fmt.Printf("Current latency: %v\n", ev.Value)

			case *slack.RTMError:
				fmt.Printf("Error: %s\n", ev.Error())

			case *slack.InvalidAuthEvent:
				fmt.Printf("Invalid credentials")
				break Loop

			default:

				// Ignore other events..
				// fmt.Printf("Unexpected: %v\n", msg.Data)
			}
		}
	}
}
Пример #29
0
func New(token string, channelName string, userName string, iconURL string) Client {
	return client{
		Client:      slack.New(token),
		channelName: channelName,
		userName:    userName,
		iconURL:     iconURL,
	}
}
Пример #30
0
func NewSlack(token string) *SlackWrapper {
	return &SlackWrapper{
		token:    token,
		api:      slack.New(token),
		channels: map[string]string{},
		users:    map[string]string{},
	}
}