Best Testkube code snippet using slacknotifier.SendMessage
plugin.go
Source:plugin.go
...18 msg = fmt.Sprintf(`-bash-4.1$ %s\n%s\n%s\n`, cmd, stdout, stderr)19 } else {20 msg = fmt.Sprintf("Hit issue: %s %s", err.Error(), stderr)21 }22 slack.SendMessage(msg)23}24func RunDbcCommand(cmds string, slack *slacknotifier.Notifier) {25 go SimulateDbc(cmds, slack)26 slack.SendMessage("Executing command, maybe occurs delay...")27}28func TriggerFastSvs(cln string, slack *slacknotifier.Notifier, fast bool) {29 var triggerCmd string30 if fast{31 triggerCmd = fmt.Sprintf("./mts/git/vsan-tools/bin/fastsvs -c %s", cln)32 }else{33 triggerCmd = fmt.Sprintf(".svs precheckin -q -c %s", cln)34 }35 go SimulateDbc(triggerCmd, slack)36 slack.SendMessage("It may cost about 3 minutes,when job done,result will be sent soon.")37}38func TriggerGoBuild(cln string, slack *slacknotifier.Notifier, opt string) {39 var triggerCmd string40 switch opt{41 case "server":42 triggerCmd = fmt.Sprintf(".gobuild sandbox queue server --changeset %s --branch=main --buildtype release --accept-defaults --store-tree", cln)43 case "vcenter-all":44 triggerCmd = fmt.Sprintf(".gobuild sandbox queue vcenter-all --changeset %s --branch=main --buildtype release --accept-defaults --store-tree", cln)45 }46 go SimulateDbc(triggerCmd, slack)47 slack.SendMessage("It may cost minutes,when job done,result will be sent soon.")48}49func TriggerRemoteCommand(cmds, opt string, slack *slacknotifier.Notifier){50 var pwd string51 user := "root"52 switch opt{53 case "esxi":54 pwd = "ca$hc0w"55 case "vc":56 pwd = "vmware"57 }58 cmdArr := strings.Split(cmds, ".")59 var msg string60 cmd := strings.Join(cmdArr[1:], ".")61 remoteCmds := strings.Split(cmd, " ")62 if len(remoteCmds) < 3{63 slack.SendMessage("USAGE: .sshhost 10.0.0.127 ls -l")64 return65 }66 host := remoteCmds[1]67 rcs := remoteCmds[2:]68 rc := strings.Join(rcs, " ")69 if models.CheckBlackList(rcs[0]){70 msg = fmt.Sprintf("Cmd : %s can not be executed in remote server.\n", rc)71 slack.SendMessage(msg)72 return73 }74 fmt.Println(pwd)75 if err, stdout,_ := tools.ExecuteRemoteCommand(host, user, pwd, rc); err == nil {76 msg = fmt.Sprintf(`-bash-4.1$ ssh %s@%s: %s\n%s\n`, user, host, rc, stdout)77 } else {78 msg = fmt.Sprintf("Hit issue: %s", err.Error())79 }80 slack.SendMessage(msg)81}82func QueryTestbedsOfUsers(slack *slacknotifier.Notifier) {83 var msg string84 user := slack.Name85 url := fmt.Sprintf("http://10.161.184.86:8080/slackcommand/api/testbed/list/%s", user)86 result, err := models.QueryDataFromSlackApi(url)87 if err == nil {88 if result.Ok {89 msg = "*Testbed* *Vc* *Expired*\n"90 for _, tb := range result.TA {91 msg += fmt.Sprintf("%s %s %s\n", tb.TestbedName, tb.Vcip, tb.Lifetime)92 }93 } else {94 msg = result.TA[0].Exception95 }96 } else {97 msg = fmt.Sprintf("Hit issue:%s", err.Error())98 }99 slack.SendMessage(msg)100}101func ShowPoolDetailInfo(id string, slack *slacknotifier.Notifier) {102 var msg string103 url := fmt.Sprintf("http://10.161.184.86:8080/slackcommand/api/pool/show/%s", id)104 result, err := models.QueryDataFromSlackApi(url)105 if err == nil {106 if result.Ok {107 msg = fmt.Sprintf("Id:%d\nTitle:%s\nCapacity:%d\nAvailable:%d\n", result.PA[0].Id, result.PA[0].Title, result.PA[0].Capacity, result.PA[0].Available)108 } else {109 msg = result.PA[0].Exception110 }111 } else {112 msg = fmt.Sprintf("Hit issue:%s", err.Error())113 }114 slack.SendMessage(msg)115}116func GetTestbedFromPool(id string, slack *slacknotifier.Notifier) {117 var msg string118 url := fmt.Sprintf("http://10.161.184.86:8080/slackcommand/api/testbed/get/%s/%s", slack.Name, id)119 result, err := models.QueryDataFromSlackApi(url)120 if err == nil {121 if result.Ok {122 messageTemplate := `123 Dear %s, you got a deployed testbed,124 *Testbed Name*: %s125 *VC Host*: %s126 *Esxi Host*: %s127 *VC Build*: %s128 *Expired in*: %s129 DUE TO NIMBUS RESOURCE CONSTRAINED, PLEASE GET TESTBED ON DEMAND, DO NOT WASTE THEM.130 Thanks for your understanding and great support!!!131 `132 msg = fmt.Sprintf(messageTemplate, slack.Name, result.TA[0].TestbedName, result.TA[0].Vcip, result.TA[0].Esxips, result.TA[0].Vcbuild, result.TA[0].Lifetime)133 } else {134 msg = result.TA[0].Exception135 }136 } else {137 msg = fmt.Sprintf("Hit issue:%s", err.Error())138 }139 slack.SendMessage(msg)140}141func ShowHelpMessage(cmdhelp map[string]string, slack *slacknotifier.Notifier) {142 msg := ""143 for k, v := range cmdhelp {144 msg += fmt.Sprintf("%s -> %s\n", k, v)145 }146 slack.SendMessage(msg)147}148func ListAllPools(slack *slacknotifier.Notifier) {149 var msg string150 url := "http://10.161.184.86:8080/slackcommand/api/pool/get/"151 result, err := models.QueryDataFromSlackApi(url)152 if err == nil {153 if result.Ok {154 msg = fmt.Sprintf("You also can visit web page:<%s|Testbed Pool>\n", "http://10.161.154.52:8080/")155 for _, mypool := range result.PA {156 msg += fmt.Sprintf("%d %s\n", mypool.Id, mypool.Title)157 }158 } else {159 msg = result.TA[0].Exception160 }161 } else {162 msg = fmt.Sprintf("Hit issue:%s", err.Error())163 }164 slack.SendMessage(msg)165}166/*167Dev can define Handler function here, which to be called in config.go168It's better to receive *slacknotifier.Notifier as a handler to send message to slack169Suggest do not write business or service code here, instead of use rest api to deal with request170When need to parse the json from rest api, you can call similar function models.QueryDataFromSlackApi(url171 func QueryDataFromSlackApi(url string) (megaData *MegaData, err error) {172dev can extend the MegaData struct to fill new request173MegaData struct:174type MegaData struct {175 Ok bool `json:"ok"`176 PA []PoolApi `json:"pools"`177 TA []TestbedApi `json:"testbeds"`178}...
notify.go
Source:notify.go
...11)12// Notifier is interface of notification13type Notifier interface {14 Notify(state State, s Source) error15 SendMessage(msg string) error16}17// SlackNotifier handles notification to slack18type SlackNotifier struct {19 hc *http.Client20 tok string21 channel string22 // url -> current state23 statesMu sync.Mutex24 states map[string]State25}26func NewSlackNotifier(hc *http.Client, tok string, channel string) *SlackNotifier {27 return &SlackNotifier{28 hc: hc,29 tok: tok,30 channel: channel,31 states: make(map[string]State),32 }33}34func (n *SlackNotifier) Notify(state State, s Source) error {35 defer func() {36 n.statesMu.Lock()37 n.states[s.URL] = state38 n.statesMu.Unlock()39 }()40 n.statesMu.Lock()41 oldState, ok := n.states[s.URL]42 n.statesMu.Unlock()43 if !ok && state == SOLDOUT {44 return nil45 }46 if oldState == state {47 log.Printf("same state: %v url=%v name=%v", state, s.URL, s.Name)48 return nil49 }50 channel := ""51 if state == AVAILABLE {52 channel = "<!channel|channel> "53 }54 msg := fmt.Sprintf("%s%v: %v (%v)", channel, state, s.URL, s.Name)55 return n.SendMessage(msg)56}57func (n *SlackNotifier) SendMessage(msg string) error {58 v := url.Values{}59 v.Set("token", n.tok)60 v.Set("channel", n.channel)61 v.Set("text", msg)62 r, err := http.NewRequest("POST", "https://slack.com/api/chat.postMessage", strings.NewReader(v.Encode()))63 if err != nil {64 return err65 }66 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")67 res, err := n.hc.Do(r)68 if err != nil {69 return err70 }71 defer res.Body.Close()72 return err73}74// LineNotifier handles notification to LINE.75type LineNotifier struct {76 hc *http.Client77 tok string78 statesMu sync.Mutex79 states map[string]State80}81func NewLineNotifier(hc *http.Client, token string) *LineNotifier {82 return &LineNotifier{83 hc: hc,84 tok: token,85 states: make(map[string]State),86 }87}88func (n *LineNotifier) Notify(state State, s Source) error {89 defer func() {90 n.statesMu.Lock()91 n.states[s.URL] = state92 n.statesMu.Unlock()93 }()94 n.statesMu.Lock()95 oldState, ok := n.states[s.URL]96 n.statesMu.Unlock()97 if ok && oldState == state {98 log.Printf("same state: %v url=%v name=%v", state, s.URL, s.Name)99 return nil100 }101 if state != AVAILABLE {102 log.Printf("(do not notify) %v url=%v name=%v", state, s.URL, s.Name)103 return nil104 }105 msg := fmt.Sprintf("%v: %v (%v)", state, s.URL, s.Name)106 return n.SendMessage(msg)107}108func (n *LineNotifier) SendMessage(msg string) error {109 v := url.Values{}110 v.Set("message", msg)111 r, err := http.NewRequest("POST", "https://notify-api.line.me/api/notify", strings.NewReader(v.Encode()))112 if err != nil {113 return err114 }115 r.Header.Set("Content-Type", "application/x-www-form-urlencoded")116 r.Header.Set("Authorization", "Bearer "+n.tok)117 res, err := n.hc.Do(r)118 if err != nil {119 return err120 }121 defer res.Body.Close()122 return nil123}124// SlackWebhookNotifier handles notification to slack incoming webhook.125type SlackWebhookNotifier struct {126 hc *http.Client127 url string128 channel string129 // url -> current state130 statesMu sync.Mutex131 states map[string]State132}133func NewSlackWebhookNotifier(hc *http.Client, url, channel string) *SlackWebhookNotifier {134 return &SlackWebhookNotifier{135 hc: hc,136 url: url,137 channel: channel,138 states: make(map[string]State),139 }140}141type slackWebhookRequest struct {142 Channel string `json:"channel"`143 Username string `json:"username"`144 Text string `json:"text"`145}146func (n *SlackWebhookNotifier) Notify(state State, s Source) error {147 defer func() {148 n.statesMu.Lock()149 n.states[s.URL] = state150 n.statesMu.Unlock()151 }()152 n.statesMu.Lock()153 oldState, ok := n.states[s.URL]154 n.statesMu.Unlock()155 if !ok && state == SOLDOUT {156 return nil157 }158 if oldState == state {159 log.Printf("same state: %v url=%v name=%v", state, s.URL, s.Name)160 return nil161 }162 channel := ""163 if state == AVAILABLE {164 channel = "<!channel|channel> "165 }166 msg := fmt.Sprintf("%s%v: %v (%v)", channel, state, s.URL, s.Name)167 return n.SendMessage(msg)168}169func (n *SlackWebhookNotifier) SendMessage(msg string) error {170 req := &slackWebhookRequest{171 Channel: n.channel,172 Username: "switch-checker",173 Text: msg,174 }175 bs, err := json.Marshal(req)176 if err != nil {177 return err178 }179 r, err := http.NewRequest("POST", n.url, bytes.NewReader(bs))180 if err != nil {181 return err182 }183 r.Header.Set("Content-Type", "application/json")...
slackNotifier.go
Source:slackNotifier.go
...30 return SlackNotifier{SlackToken: env.SlackToken, SlackChannel: env.SlackChannel}31}32func (notifier SlackNotifier) Notify(detailsUrl string, vehiclePlateNumber string) bool {33 var slackMessage = notifier.GetNotificationMessage(detailsUrl, vehiclePlateNumber)34 notifier.SendMessage(slackMessage)35 return true36}37func (notifier SlackNotifier) GetNotificationMessage(detailsUrl string, vehiclePlateNumber string) SlackMessage {38 var slackMessage SlackMessage39 messageString := fmt.Sprintf(":warning: Alert, Your vehicle *%s* has just been impounded. Visit %s to get details :warning:", vehiclePlateNumber, detailsUrl)40 slackMessage.Text = messageString41 slackMessage.Channel = notifier.SlackChannel42 return slackMessage43}44func (notifier SlackNotifier) SendMessage(message SlackMessage) []byte {45 jsonBody, err := json.Marshal(message)46 if err != nil {47 log.Fatal(err)48 }49 slackUrl := fmt.Sprintf("%s/%s", "https://slack.com/api/", "chat.postMessage")50 client := &http.Client{}51 req, err := http.NewRequest("POST", slackUrl, bytes.NewBuffer(jsonBody))52 req.Header.Add("Authorization", fmt.Sprintf("Bearer %v", notifier.SlackToken))53 req.Header.Add("Content-Type", "application/json")54 res, err := client.Do(req)55 if err != nil {56 log.Fatal(err)57 }58 defer res.Body.Close()...
SendMessage
Using AI Code Generation
1import (2func main() {3 err := sn.SendMessage("This is a test message")4 if err != nil {5 fmt.Println("Error:", err)6 }7}
SendMessage
Using AI Code Generation
1import (2func main() {3 fmt.Println("Hello, playground")4 slacknotifier.SendMessage("Hello World")5}6import (7func main() {8 fmt.Println("Hello, playground")9 slacknotifier.Send("Hello World")10}11import (12func main() {13 fmt.Println("Hello, playground")14 slacknotifier.Send("Hello World")15 slacknotifier.SendMessage("Hello World")16}
SendMessage
Using AI Code Generation
1import (2func main() {3 slacknotifier.SendMessage("Hello World")4 fmt.Println("Message sent successfully")5}6import (7func main() {8 slacknotifier.SendAttachment("Hello World")9 fmt.Println("Attachment sent successfully")10}11import (12func main() {13 slacknotifier.SendAttachment("Hello World")14 fmt.Println("Attachment sent successfully
SendMessage
Using AI Code Generation
1import (2func main() {3 slackNotifier := SlackNotifier.SlackNotifier{}4 err := slackNotifier.SendMessage("Hello World")5 if err != nil {6 log.Fatal(err)7 }8 fmt.Println("Message sent successfully")9}
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!