How to use init method of slacknotifier Package

Best Testkube code snippet using slacknotifier.init

slack.go

Source:slack.go Github

copy

Full Screen

1package channels2import (3 "bytes"4 "context"5 "crypto/tls"6 "encoding/json"7 "fmt"8 "io"9 "net"10 "net/http"11 "net/url"12 "regexp"13 "strings"14 "time"15 "github.com/prometheus/alertmanager/config"16 "github.com/prometheus/alertmanager/template"17 "github.com/prometheus/alertmanager/types"18 "github.com/grafana/grafana/pkg/infra/log"19 "github.com/grafana/grafana/pkg/models"20 old_notifiers "github.com/grafana/grafana/pkg/services/alerting/notifiers"21 "github.com/grafana/grafana/pkg/setting"22)23// SlackNotifier is responsible for sending24// alert notification to Slack.25type SlackNotifier struct {26 old_notifiers.NotifierBase27 log log.Logger28 tmpl *template.Template29 URL *url.URL30 Username string31 IconEmoji string32 IconURL string33 Recipient string34 Text string35 Title string36 MentionUsers []string37 MentionGroups []string38 MentionChannel string39 Token string40}41var reRecipient *regexp.Regexp = regexp.MustCompile("^((@[a-z0-9][a-zA-Z0-9._-]*)|(#[^ .A-Z]{1,79})|([a-zA-Z0-9]+))$")42var SlackAPIEndpoint = "https://slack.com/api/chat.postMessage"43// NewSlackNotifier is the constructor for the Slack notifier44func NewSlackNotifier(model *NotificationChannelConfig, t *template.Template) (*SlackNotifier, error) {45 if model.Settings == nil {46 return nil, receiverInitError{Cfg: *model, Reason: "no settings supplied"}47 }48 slackURL := model.DecryptedValue("url", model.Settings.Get("url").MustString())49 if slackURL == "" {50 slackURL = SlackAPIEndpoint51 }52 apiURL, err := url.Parse(slackURL)53 if err != nil {54 return nil, receiverInitError{Cfg: *model, Reason: fmt.Sprintf("invalid URL %q", slackURL), Err: err}55 }56 recipient := strings.TrimSpace(model.Settings.Get("recipient").MustString())57 if recipient != "" {58 if !reRecipient.MatchString(recipient) {59 return nil, receiverInitError{Cfg: *model, Reason: fmt.Sprintf("recipient on invalid format: %q", recipient)}60 }61 } else if apiURL.String() == SlackAPIEndpoint {62 return nil, receiverInitError{Cfg: *model,63 Reason: "recipient must be specified when using the Slack chat API",64 }65 }66 mentionChannel := model.Settings.Get("mentionChannel").MustString()67 if mentionChannel != "" && mentionChannel != "here" && mentionChannel != "channel" {68 return nil, receiverInitError{Cfg: *model,69 Reason: fmt.Sprintf("invalid value for mentionChannel: %q", mentionChannel),70 }71 }72 mentionUsersStr := model.Settings.Get("mentionUsers").MustString()73 mentionUsers := []string{}74 for _, u := range strings.Split(mentionUsersStr, ",") {75 u = strings.TrimSpace(u)76 if u != "" {77 mentionUsers = append(mentionUsers, u)78 }79 }80 mentionGroupsStr := model.Settings.Get("mentionGroups").MustString()81 mentionGroups := []string{}82 for _, g := range strings.Split(mentionGroupsStr, ",") {83 g = strings.TrimSpace(g)84 if g != "" {85 mentionGroups = append(mentionGroups, g)86 }87 }88 token := model.DecryptedValue("token", model.Settings.Get("token").MustString())89 if token == "" && apiURL.String() == SlackAPIEndpoint {90 return nil, receiverInitError{Cfg: *model,91 Reason: "token must be specified when using the Slack chat API",92 }93 }94 return &SlackNotifier{95 NotifierBase: old_notifiers.NewNotifierBase(&models.AlertNotification{96 Uid: model.UID,97 Name: model.Name,98 Type: model.Type,99 DisableResolveMessage: model.DisableResolveMessage,100 Settings: model.Settings,101 }),102 URL: apiURL,103 Recipient: recipient,104 MentionUsers: mentionUsers,105 MentionGroups: mentionGroups,106 MentionChannel: mentionChannel,107 Username: model.Settings.Get("username").MustString("Grafana"),108 IconEmoji: model.Settings.Get("icon_emoji").MustString(),109 IconURL: model.Settings.Get("icon_url").MustString(),110 Token: token,111 Text: model.Settings.Get("text").MustString(`{{ template "default.message" . }}`),112 Title: model.Settings.Get("title").MustString(`{{ template "default.title" . }}`),113 log: log.New("alerting.notifier.slack"),114 tmpl: t,115 }, nil116}117// slackMessage is the slackMessage for sending a slack notification.118type slackMessage struct {119 Channel string `json:"channel,omitempty"`120 Username string `json:"username,omitempty"`121 IconEmoji string `json:"icon_emoji,omitempty"`122 IconURL string `json:"icon_url,omitempty"`123 Attachments []attachment `json:"attachments"`124 Blocks []map[string]interface{} `json:"blocks"`125}126// attachment is used to display a richly-formatted message block.127type attachment struct {128 Title string `json:"title,omitempty"`129 TitleLink string `json:"title_link,omitempty"`130 Text string `json:"text"`131 Fallback string `json:"fallback"`132 Fields []config.SlackField `json:"fields,omitempty"`133 Footer string `json:"footer"`134 FooterIcon string `json:"footer_icon"`135 Color string `json:"color,omitempty"`136 Ts int64 `json:"ts,omitempty"`137}138// Notify sends an alert notification to Slack.139func (sn *SlackNotifier) Notify(ctx context.Context, as ...*types.Alert) (bool, error) {140 msg, err := sn.buildSlackMessage(ctx, as)141 if err != nil {142 return false, fmt.Errorf("build slack message: %w", err)143 }144 b, err := json.Marshal(msg)145 if err != nil {146 return false, fmt.Errorf("marshal json: %w", err)147 }148 sn.log.Debug("Sending Slack API request", "url", sn.URL.String(), "data", string(b))149 request, err := http.NewRequestWithContext(ctx, http.MethodPost, sn.URL.String(), bytes.NewReader(b))150 if err != nil {151 return false, fmt.Errorf("failed to create HTTP request: %w", err)152 }153 request.Header.Set("Content-Type", "application/json")154 request.Header.Set("User-Agent", "Grafana")155 if sn.Token == "" {156 if sn.URL.String() == SlackAPIEndpoint {157 panic("Token should be set when using the Slack chat API")158 }159 } else {160 sn.log.Debug("Adding authorization header to HTTP request")161 request.Header.Set("Authorization", fmt.Sprintf("Bearer %s", sn.Token))162 }163 if err := sendSlackRequest(request, sn.log); err != nil {164 return false, err165 }166 return true, nil167}168// sendSlackRequest sends a request to the Slack API.169// Stubbable by tests.170var sendSlackRequest = func(request *http.Request, logger log.Logger) error {171 netTransport := &http.Transport{172 TLSClientConfig: &tls.Config{173 Renegotiation: tls.RenegotiateFreelyAsClient,174 },175 Proxy: http.ProxyFromEnvironment,176 DialContext: (&net.Dialer{177 Timeout: 30 * time.Second,178 }).DialContext,179 TLSHandshakeTimeout: 5 * time.Second,180 }181 netClient := &http.Client{182 Timeout: time.Second * 30,183 Transport: netTransport,184 }185 resp, err := netClient.Do(request)186 if err != nil {187 return err188 }189 defer func() {190 if err := resp.Body.Close(); err != nil {191 logger.Warn("Failed to close response body", "err", err)192 }193 }()194 body, err := io.ReadAll(resp.Body)195 if err != nil {196 return fmt.Errorf("failed to read response body: %w", err)197 }198 if resp.StatusCode/100 != 2 {199 logger.Warn("Slack API request failed", "url", request.URL.String(), "statusCode", resp.Status, "body", string(body))200 return fmt.Errorf("request to Slack API failed with status code %d", resp.StatusCode)201 }202 var rslt map[string]interface{}203 // Slack responds to some requests with a JSON document, that might contain an error204 if err := json.Unmarshal(body, &rslt); err == nil {205 if !rslt["ok"].(bool) {206 errMsg := rslt["error"].(string)207 logger.Warn("Sending Slack API request failed", "url", request.URL.String(), "statusCode", resp.Status,208 "err", errMsg)209 return fmt.Errorf("failed to make Slack API request: %s", errMsg)210 }211 }212 logger.Debug("Sending Slack API request succeeded", "url", request.URL.String(), "statusCode", resp.Status)213 return nil214}215func (sn *SlackNotifier) buildSlackMessage(ctx context.Context, as []*types.Alert) (*slackMessage, error) {216 alerts := types.Alerts(as...)217 var tmplErr error218 tmpl, _ := TmplText(ctx, sn.tmpl, as, sn.log, &tmplErr)219 ruleURL := joinUrlPath(sn.tmpl.ExternalURL.String(), "/alerting/list", sn.log)220 req := &slackMessage{221 Channel: tmpl(sn.Recipient),222 Username: tmpl(sn.Username),223 IconEmoji: tmpl(sn.IconEmoji),224 IconURL: tmpl(sn.IconURL),225 Attachments: []attachment{226 {227 Color: getAlertStatusColor(alerts.Status()),228 Title: tmpl(sn.Title),229 Fallback: tmpl(sn.Title),230 Footer: "Grafana v" + setting.BuildVersion,231 FooterIcon: FooterIconURL,232 Ts: time.Now().Unix(),233 TitleLink: ruleURL,234 Text: tmpl(sn.Text),235 Fields: nil, // TODO. Should be a config.236 },237 },238 }239 if tmplErr != nil {240 sn.log.Debug("failed to template Slack message", "err", tmplErr.Error())241 }242 mentionsBuilder := strings.Builder{}243 appendSpace := func() {244 if mentionsBuilder.Len() > 0 {245 mentionsBuilder.WriteString(" ")246 }247 }248 mentionChannel := strings.TrimSpace(sn.MentionChannel)249 if mentionChannel != "" {250 mentionsBuilder.WriteString(fmt.Sprintf("<!%s|%s>", mentionChannel, mentionChannel))251 }252 if len(sn.MentionGroups) > 0 {253 appendSpace()254 for _, g := range sn.MentionGroups {255 mentionsBuilder.WriteString(fmt.Sprintf("<!subteam^%s>", tmpl(g)))256 }257 }258 if len(sn.MentionUsers) > 0 {259 appendSpace()260 for _, u := range sn.MentionUsers {261 mentionsBuilder.WriteString(fmt.Sprintf("<@%s>", tmpl(u)))262 }263 }264 if mentionsBuilder.Len() > 0 {265 req.Blocks = []map[string]interface{}{266 {267 "type": "section",268 "text": map[string]interface{}{269 "type": "mrkdwn",270 "text": mentionsBuilder.String(),271 },272 },273 }274 }275 return req, nil276}277func (sn *SlackNotifier) SendResolved() bool {278 return !sn.GetDisableResolveMessage()279}...

Full Screen

Full Screen

notifier.go

Source:notifier.go Github

copy

Full Screen

1package slacknotifier2import (3 "context"4 "strings"5 "github.com/aws/aws-lambda-go/events"6 "github.com/common-fate/ddb"7 "github.com/common-fate/granted-approvals/pkg/gconfig"8 "github.com/pkg/errors"9 "github.com/slack-go/slack"10 "go.uber.org/zap"11)12const NotificationsTypeSlack = "slack"13// Notifier provides handler methods for sending notifications to slack based on events14type SlackNotifier struct {15 DB ddb.Storage16 FrontendURL string17 client *slack.Client18 apiToken gconfig.SecretStringValue19}20func (s *SlackNotifier) Config() gconfig.Config {21 return gconfig.Config{22 gconfig.SecretStringField("apiToken", &s.apiToken, "the Slack API token", gconfig.WithNoArgs("/granted/secrets/notifications/slack/token")),23 }24}25func (s *SlackNotifier) Init(ctx context.Context) error {26 s.client = slack.New(s.apiToken.Get())27 return nil28}29func (s *SlackNotifier) TestConfig(ctx context.Context) error {30 _, err := s.client.GetUsersContext(ctx)31 if err != nil {32 return errors.Wrap(err, "failed to list users while testing slack configuration")33 }34 return nil35}36func (n *SlackNotifier) HandleEvent(ctx context.Context, event events.CloudWatchEvent) (err error) {37 log := zap.S()38 log.Infow("received event", "event", event)39 if strings.HasPrefix(event.DetailType, "grant") {40 err = n.HandleGrantEvent(ctx, log, event)41 if err != nil {42 return err43 }44 } else if strings.HasPrefix(event.DetailType, "request") {45 err = n.HandleRequestEvent(ctx, log, event)46 if err != nil {47 return err48 }49 } else {50 log.Info("ignoring unhandled event type")51 }52 return nil53}...

Full Screen

Full Screen

test.go

Source:test.go Github

copy

Full Screen

1package slack2import (3 "fmt"4 "github.com/common-fate/granted-approvals/pkg/clio"5 "github.com/common-fate/granted-approvals/pkg/deploy"6 "github.com/common-fate/granted-approvals/pkg/gconfig"7 slacknotifier "github.com/common-fate/granted-approvals/pkg/notifiers/slack"8 "github.com/urfave/cli/v2"9)10var testSlackCommand = cli.Command{11 Name: "test",12 Description: "test slack integration",13 Flags: []cli.Flag{14 &cli.StringFlag{Name: "email", Usage: "A test email to send a private message to", Required: true},15 },16 Action: func(c *cli.Context) error {17 ctx := c.Context18 dc, err := deploy.ConfigFromContext(ctx)19 if err != nil {20 return err21 }22 currentConfig, ok := dc.Deployment.Parameters.NotificationsConfiguration[slacknotifier.NotificationsTypeSlack]23 if !ok {24 return fmt.Errorf("slack is not yet configured, configure it now by running 'gdeploy notifications slack configure'")25 }26 var slack slacknotifier.SlackNotifier27 cfg := slack.Config()28 err = cfg.Load(ctx, &gconfig.MapLoader{Values: currentConfig})29 if err != nil {30 return err31 }32 err = slack.Init(ctx)33 if err != nil {34 return err35 }36 err = slack.SendTestMessage(ctx, c.String("email"))37 if err != nil {38 return err39 }40 clio.Success("Successfully sent a slack test message to %s", c.String("email"))41 return nil42 },43}...

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 slacknotifier.Notify("hello world")4 fmt.Println("hello world")5}6import (7func main() {8 slacknotifier.Notify("hello world")9 fmt.Println("hello world")10}11import (12func main() {13 slacknotifier.Notify("hello world")14 fmt.Println("hello world")15}16import (17func main() {18 slacknotifier.Notify("hello world")19 fmt.Println("hello world")20}21import (22func main() {23 slacknotifier.Notify("hello world")24 fmt.Println("hello world")25}26import (27func main() {28 slacknotifier.Notify("hello world")29 fmt.Println("hello world")30}31import (32func main() {33 slacknotifier.Notify("hello world")34 fmt.Println("hello world")35}36import (37func main() {38 slacknotifier.Notify("hello world")39 fmt.Println("hello world")40}41import (42func main() {43 slacknotifier.Notify("hello world")44 fmt.Println("hello world")45}46import (

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1func main() {2 slacknotifier := slacknotifier.New()3 slacknotifier.SendSlackNotification("This is a test message from slacknotifier")4}5func main() {6 slacknotifier := slacknotifier.New()7 slacknotifier.SendSlackNotification("This is a test message from slacknotifier")8}9func main() {10 slacknotifier := slacknotifier.New()11 slacknotifier.SendSlackNotification("This is a test message from slacknotifier")12}13func main() {14 slacknotifier := slacknotifier.New()15 slacknotifier.SendSlackNotification("This is a test message from slacknotifier")16}17func main() {18 slacknotifier := slacknotifier.New()19 slacknotifier.SendSlackNotification("This is a test message from slacknotifier")20}21func main() {22 slacknotifier := slacknotifier.New()23 slacknotifier.SendSlackNotification("This is a test message from slacknotifier")24}25func main() {26 slacknotifier := slacknotifier.New()27 slacknotifier.SendSlackNotification("This is a test message from slacknotifier")28}29func main() {30 slacknotifier := slacknotifier.New()31 slacknotifier.SendSlackNotification("This is a test message from slacknotifier")32}33func main() {34 slacknotifier := slacknotifier.New()35 slacknotifier.SendSlackNotification("This is a test message from slacknotifier")36}

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 slacknotifier.SlackNotify("Hello from Go")4 fmt.Println("Hello from 2.go")5}6import (7func main() {8 slacknotifier.SlackNotify("Hello from Go")9 fmt.Println("Hello from 3.go")10}11import (12func main() {13 slacknotifier.SlackNotify("Hello from Go")14 fmt.Println("Hello from 4.go")15}16import (17func main() {18 slacknotifier.SlackNotify("Hello from Go")19 fmt.Println("Hello from 5.go")20}21import (22func main() {23 slacknotifier.SlackNotify("Hello from Go")24 fmt.Println("Hello from 6.go")25}26import (27func main() {28 slacknotifier.SlackNotify("Hello from Go")29 fmt.Println("Hello from 7.go")30}31import (32func main() {33 slacknotifier.SlackNotify("Hello from Go")34 fmt.Println("Hello from 8.go")35}36import (

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 slacknotifier.Send("Hello World")4 fmt.Println("Hello World")5}6import "github.com/anshul35/slacknotifier"7slacknotifier.Send("Hello World")

Full Screen

Full Screen

init

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 slacknotifier.SlackNotifier()5}6import (7func main() {8 fmt.Println("Hello, playground")9 slacknotifier.SlackNotifier()10}11import (12func main() {13 fmt.Println("Hello, playground")14 slacknotifier.SlackNotifier()15}16import (17func main() {18 fmt.Println("Hello, playground")19 slacknotifier.SlackNotifier()20}21import (22func main() {23 fmt.Println("Hello, playground")24 slacknotifier.SlackNotifier()25}26import (27func main() {28 fmt.Println("Hello, playground")29 slacknotifier.SlackNotifier()30}31import (32func main() {33 fmt.Println("Hello, playground")34 slacknotifier.SlackNotifier()35}36import (

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testkube automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful