Best JavaScript code snippet using qawolf
provider.notifme.js
Source:provider.notifme.js
1'use strict';2const Notifme = require('notifme-sdk');3exports.init = function (api) {4 api.register('slack', {5 name: 'Slack',6 type: 'slack',7 fields: [{8 name: 'slackWebhookUrl',9 required: true,10 type: 'secret',11 description: 'Incoming Webhooks are a simple way to post messages from external sources into Slack.'12 }],13 sendAlert: exports.sendSlackAlert14 });15 api.register('twilio', {16 name: 'Twilio',17 type: 'twilio',18 fields: [{19 name: 'accountSid',20 required: true,21 type: 'secret',22 description: 'Twilio account ID'23 }, {24 name: 'authToken',25 required: true,26 type: 'secret',27 description: 'Twilio authentication token'28 }, {29 name: 'toNumber',30 required: true,31 description: 'The number to send the alert to'32 }, {33 name: 'fromNumber',34 required: true,35 description: 'The number to send the alert from'36 }],37 sendAlert: exports.sendTwilioAlert38 });39 api.register('email', {40 name: 'Email',41 type: 'email',42 fields: [{43 name: 'secure',44 type: 'checkbox',45 description: 'Send the email securely'46 }, {47 name: 'host',48 required: true,49 description: 'Email host'50 }, {51 name: 'port',52 required: true,53 description: 'Email port'54 }, {55 name: 'user',56 description: 'The username of the user sending the email'57 }, {58 name: 'password',59 type: 'secret',60 description: 'Password of the user sending the email'61 }, {62 name: 'from',63 required: true,64 description: 'Send the email from this address'65 }, {66 name: 'to',67 required: true,68 description: 'Send the email to this address'69 }, {70 name: 'subject',71 description: 'The subject of the email (defaults to "Parliament Alert")'72 }],73 sendAlert: exports.sendEmailAlert74 })75};76// Slack77exports.sendSlackAlert = function (config, message, links, cb) {78 if (!config.slackWebhookUrl) {79 console.error('Please add a Slack webhook URL on the Settings page to enable Slack notifications');80 return;81 }82 const slackNotifier = new Notifme.default({83 channels: {84 slack: {85 providers: [{86 type: 'webhook',87 webhookUrl: config.slackWebhookUrl88 }]89 }90 }91 });92 // add links to the slack alert93 let slackMsgObj = { slack: { text: message } };94 if (links && links.length) {95 slackMsgObj.slack.attachments = [];96 for (let link of links) {97 slackMsgObj.slack.attachments.push({98 fallback: `${link.text}: <${link.link}>`,99 actions: [{100 type: 'button',101 text: link.text,102 url: link.url103 }]104 });105 }106 }107 slackNotifier.send(slackMsgObj)108 .then((response) => { if (cb) { cb(response); } });109};110// Twilio111exports.sendTwilioAlert = function (config, message, links, cb) {112 if (!config.accountSid || !config.authToken || !config.toNumber || !config.fromNumber) {113 console.error('Please fill out the required fields for Twilio notifications on the Settings page.');114 return;115 }116 const twilioNotifier = new Notifme.default({117 channels: {118 sms: {119 providers: [{120 type: 'twilio',121 accountSid: config.accountSid,122 authToken: config.authToken123 }]124 }125 }126 });127 if (links && links.length) {128 for (let link of links) {129 message += `\n${link.text}: ${link.url}`;130 }131 }132 twilioNotifier.send({133 sms: {134 from: config.fromNumber,135 to: config.toNumber,136 text: message137 }138 }).then((response) => { if (cb) { cb(response); } });139};140// Email141exports.sendEmailAlert = function (config, message, links, cb) {142 if (!config.host || !config.port || !config.to || !config.from) {143 console.error('Please fill out the required fields for Email notifications on the Settings page.');144 return;145 }146 if (!config.secure) {147 config.secure = false;148 }149 const emailNotifier = new Notifme.default({150 channels: {151 email: {152 providers: [{153 type: 'smtp',154 host: config.host,155 port: config.port,156 secure: config.secure,157 auth: {158 user: config.user,159 pass: config.password160 }161 }]162 }163 }164 });165 if (links && links.length) {166 for (let link of links) {167 message += `<br><a href="${link.url}">${link.text}</a>`;168 }169 }170 emailNotifier.send({171 email: {172 html: message,173 to: config.to,174 from: config.from,175 subject: config.subject || 'Parliament Alert'176 }177 }).then((response) => { if (cb) { cb(response); } });...
index.js
Source:index.js
...6 return trigger["MetricName"] === "HTTPCode_Target_5XX_Count";7 }8 return false;9}10function sendSlackAlert(context, alertState, errorMessage, link) {11 console.log("Sending alert to Slack Channel: #" + process.env.slack_channel);12 var options = {13 hostname: 'hooks.slack.com',14 port: 443,15 path: process.env.slack_webhook_path,16 method: 'POST'17 };18 var payload =19 {20 "channel": "#" + process.env.slack_channel,21 "attachments": [22 {23 "title": alertState.NewStateReason,24 "pretext": alertState.AlarmDescription,25 "color": "#FF0000",26 "fields": [27 {28 "title": "Alarm",29 "value": alertState.AlarmName,30 "short": true31 },32 {33 "title": "StateChangeTime",34 "value": alertState.StateChangeTime,35 "short": true36 }37 ]38 }]39 };40 if (errorMessage !== "") {41 payload.attachments.push({42 "title": "Error Message",43 "text": errorMessage44 });45 }46 if (link !== "") {47 payload.attachments.push({48 "fallback": "View log message at " + link,49 "actions": [50 {51 "type": "button",52 "text": "View Log Message",53 "url": link54 }55 ]56 });57 }58 var req = https.request(options, function (res) {59 res.on("data", function () {60 console.log("Successfully sent alert to Slack Channel: #" + process.env.slack_channel);61 context.done(null, 'done!');62 });63 }).on('error', function (e) {64 console.log("Failed sending alert to Slack Channel: #" + process.env.slack_channel);65 console.error(e);66 context.done('error', e);67 });68 req.write(JSON.stringify(payload));69 req.end();70}71exports.handler = function (event, context) {72 console.log("event", event);73 console.log("sns", event.Records[0].Sns);74 var alertState = JSON.parse(event.Records[0].Sns.Message);75 var message = "";76 var link = "";77 if (is500Error(alertState)) {78 var dimensions = alertState["Trigger"]["Dimensions"];79 var logGroup = "";80 for (var i = 0; i < dimensions.length; i++) {81 var dimension = dimensions[i];82 if (dimension["name"] === "TargetGroup") {83 logGroup = dimension["value"].split("/")[1];84 break;85 }86 }87 if (logGroup !== "") {88 var cloudwatchlogs = new AWS.CloudWatchLogs();89 var params = {90 logGroupName: logGroup, /* required */91 endTime: Date.now(),92 filterPattern: "{$.status_code=500}",93 interleaved: true,94 startTime: (Date.now() - 1000 * 60 * 15) /* now minus 5 mins */95 };96 cloudwatchlogs.filterLogEvents(params, function (err, data) {97 if (err) {98 console.log(err, err.stack); // an error occurred99 } else {100 console.log(data); // successful response101 }102 var events = data["events"];103 if (events != null && events.length > 0) {104 message = JSON.stringify(JSON.parse(events[0].message), null, 2);105 link = "https://eu-west-1.console.aws.amazon.com/cloudwatch/home?" +106 "region=eu-west-1" + /* region */107 "#logEventViewer:group=" + logGroup +108 ";stream=" + events[0].logStreamName +109 ";refid=" + events[0].eventId +110 ";reftime=" + events[0].timestamp + ";";111 }112 sendSlackAlert(context, alertState, message, link);113 });114 } else {115 sendSlackAlert(context, alertState, message, link);116 }117 } else {118 sendSlackAlert(context, alertState, message, link);119 }...
healthcheck-lambda.js
Source:healthcheck-lambda.js
...6const port = 9933;7function statusIsValid(status) {8 return status.result && status.result.currentBlock && !isNaN(status.result.currentBlock);9}10async function sendSlackAlert(status, node) {11 const slackBlocks = {12 blocks: [13 {14 type: 'divider'15 },16 {17 type: 'header',18 text: {19 type: 'plain_text',20 text: `${node.network}`21 }22 }23 ],24 attachments: [{25 color: '#ff0000',26 blocks: [27 {28 type: 'section',29 text: {30 type: 'mrkdwn',31 text: `*<http://${node.url}|${node.name}>* reported an error. (AWS Region: ${node.region})`32 }33 }34 ]35 },36 {37 blocks: [38 {39 type: 'section',40 text: {41 type: 'mrkdwn',42 text: `Healthcheck: _${process.env.AWS_LAMBDA_FUNCTION_NAME} (${process.env.AWS_REGION})_`43 }44 }45 ]46 }]47 };48 if (status.error) {49 if (status.error.code) {50 slackBlocks.attachments[0].blocks.push({51 type: 'section',52 text: {53 type: 'mrkdwn',54 text: `*Code:* ${status.error.code}`,55 }56 });57 }58 if (status.error.message) {59 slackBlocks.attachments[0].blocks.push({60 type: 'section',61 text: {62 type: 'mrkdwn',63 text: `*Message:* ${status.error.message}`,64 }65 });66 }67 }68 console.log("Sending alert to slack...");69 try {70 await httpPOST(webhookUrl, slackBlocks, https);71 } catch (err) {72 console.log(`Sending to slack failed. ${err}`);73 }74}75function httpPOST(urlStr, jsonData, protocol) {76 const promise = new Promise((resolve, reject) => {77 const data = JSON.stringify(jsonData);78 const uri = url.parse(urlStr);79 const options = {80 hostname: uri.hostname,81 port: uri.port,82 path: `${uri.pathname}`,83 method: 'POST',84 headers: {85 'Content-Type': 'application/json',86 'Content-Length': data.length87 },88 timeout: 300089 };90 const req = protocol.request(options, res => {91 if (res.statusCode === 200) {92 res.on('data', d => {93 resolve(d.toString());94 });95 } else {96 reject(Error(`Unknown status: ${res.statusCode} ${urlStr}`));97 }98 });99 req.on('timeout', function () {100 req.abort();101 req.destroy();102 const msg = `Timeout after ${options.timeout} milliseconds. (uri: ${JSON.stringify(uri)})`;103 reject(new Error(msg, {104 message: msg,105 url: uri106 }));107 });108 req.on('error', error => {109 reject(new Error(error.message, error.options));110 });111 req.write(data);112 req.end();113 });114 return promise;115}116async function checkAPIStatus(node) {117 const blockNumberReq = {118 id: 1,119 jsonrpc: '2.0',120 method: 'system_syncState'121 };122 const status = await httpPOST(`http://${node.url}:${port}`, blockNumberReq, http)123 .then(async status => {124 console.log(`${node.network} - ${node.name} status: ${status}`);125 if (!statusIsValid(JSON.parse(status))) {126 await sendSlackAlert(status, node);127 }128 return { status, node };129 })130 .catch(async err => {131 console.log(`Error caught: ${err}`);132 const errStatus = {133 error: {134 message: err.message135 }136 };137 await sendSlackAlert(errStatus, node);138 return {139 status: errStatus,140 node141 };142 });143 return status;144}145exports.handler = async function (event) {146 const promises = [];147 const nodeUrls = JSON.parse(process.env.NODE_URLS);148 nodeUrls.forEach(node => {149 console.log(`checking ${node.network} - ${node.name}...`);150 promises.push(checkAPIStatus(node));151 });...
update-comment.ts
Source:update-comment.ts
1import { SlackUser, PullRequest } from "../../../models";2import { getPRLink } from "../../../github/parse";3import { createISO, sendCommentSlackAlert } from "../../time";4import { getSlackGroupAlt, getTeamOptionsAlt } from "../../../json/parse";5import { processCommentingUserReqChanges } from "./helpers/comment-changes-alerts";6import { DynamoGet, DynamoUpdate } from "../../../dynamo/api";7import { findPrInQueues } from "./helpers/find-pr-in-queues";8/**9 * @description Update DynamoDB table to add a comment10 * action to the PR11 * @param slackUserOwner Slack user who owns the queue12 * @param slackUserCommenting Slack user commenting13 * @param dynamoTableName Name of the dynamo table14 * @param event full event from GitHub webhook15 * @param json JSON config file16 * @returns boolean whether to send a slack notification17 * to slack team channel18 */19export async function updateComment(20 slackUserOwner: SlackUser,21 slackUserCommenting: SlackUser,22 dynamoTableName: string,23 event: any,24 json: any,25): Promise<boolean> {26 // Setup27 const dynamoGet = new DynamoGet();28 const dynamoUpdate = new DynamoUpdate();29 // GitHub PR Url30 const htmlUrl = getPRLink(event);31 // Team queue32 const ownerTeam = getSlackGroupAlt(slackUserOwner.Slack_Id, json);33 const teamQueue = await dynamoGet.getQueue(dynamoTableName, ownerTeam);34 // Check slackUserCommenting's queue35 const dynamoUserQueue = await dynamoGet.getQueue(36 dynamoTableName,37 slackUserCommenting,38 );39 // Get PR from user or team queues40 const foundPR = findPrInQueues(41 htmlUrl,42 slackUserCommenting,43 dynamoUserQueue,44 ownerTeam,45 teamQueue,46 );47 // Make timestamp for last updated time & Add new comment event from slackUserCommenting48 const currentTime = createISO();49 const newEvent = {50 user: slackUserCommenting,51 action: "COMMENTED",52 time: currentTime,53 };54 foundPR.events.push(newEvent);55 // Check whether to send a slack alert & update comment times56 const teamOptions = getTeamOptionsAlt(slackUserOwner, json);57 const sendSlackAlert = sendCommentSlackAlert(58 currentTime,59 teamOptions,60 slackUserCommenting,61 foundPR,62 );63 const updatedPR = sendSlackAlert.pr;64 // Update commented event on team queue65 await dynamoUpdate.updatePullRequest(66 dynamoTableName,67 ownerTeam,68 teamQueue,69 updatedPR,70 );71 // For all members and leads to alert, update each PR from each user queue72 const allAlertingUserIds = updatedPR.standard_leads_alert73 .concat(updatedPR.standard_members_alert)74 .concat(updatedPR.req_changes_leads_alert)75 .concat(updatedPR.req_changes_members_alert);76 await Promise.all(77 allAlertingUserIds.map(async (alertUser) => {78 const currentQueue = await dynamoGet.getQueue(dynamoTableName, alertUser);79 await dynamoUpdate.updatePullRequest(80 dynamoTableName,81 alertUser,82 currentQueue,83 updatedPR,84 );85 }),86 );87 return sendSlackAlert.alertSlack;...
Using AI Code Generation
1const { sendSlackAlert } = require('qawolf');2const { sendSlackAlert } = require('qawolf');3const { sendSlackAlert } = require('qawolf');4const { sendSlackAlert } = require('qawolf');5const { sendSlackAlert } = require('qawolf');6const { sendSlackAlert } = require('qawolf');7const { sendSlackAlert } = require('qawolf');8const { sendSlackAlert } = require('qawolf');9const { sendSlackAlert } = require('qawolf');10const { sendSlackAlert } = require('qawolf');11const { sendSlackAlert } = require('qawolf');12const { sendSlackAlert } = require('qawolf');13const { sendSlackAlert } = require('qawolf');14const { sendSlackAlert } = require('qawolf');15const { sendSlackAlert } = require('qawolf');16const { sendSlackAlert } = require('qawolf');17const { sendSlackAlert } = require('qawolf');18const { sendSlackAlert } = require('qawolf');19const { sendSlackAlert } = require('qawolf');20const { sendSlackAlert } = require('qawolf');21const { sendSlack
Using AI Code Generation
1const { sendSlackAlert } = require("qawolf");2const { test, expect } = require("@playwright/test");3test("Slack Alert", async ({ page }) => {4 const title = await page.title();5 expect(title).toBe("Google");6 await sendSlackAlert("test", "test", "test", "test", "test");7});8{9 "scripts": {10 },11 "devDependencies": {12 }13}
Using AI Code Generation
1const { sendSlackAlert } = require('qawolf');2const { test, expect } = require('@playwright/test');3test('sendSlackAlert', async ({ page }) => {4 await sendSlackAlert(page, {5 });6 await expect(page).toHaveText('This text does not exist');7});
Using AI Code Generation
1const { sendSlackAlert } = require("qawolf");2const webhookUrl = process.env.SLACK_WEBHOOK_URL;3const channel = process.env.SLACK_CHANNEL;4const username = process.env.SLACK_USERNAME;5const iconEmoji = process.env.SLACK_ICON_EMOJI;6const iconUrl = process.env.SLACK_ICON_URL;7const message = process.env.SLACK_MESSAGE;8const blocks = process.env.SLACK_BLOCKS;9const attachments = process.env.SLACK_ATTACHMENTS;10const threadId = process.env.SLACK_THREAD_ID;11const threadTs = process.env.SLACK_THREAD_TS;12const unfurlLinks = process.env.SLACK_UNFURL_LINKS;13const unfurlMedia = process.env.SLACK_UNFURL_MEDIA;14const linkNames = process.env.SLACK_LINK_NAMES;15const parse = process.env.SLACK_PARSE;16const replyBroadcast = process.env.SLACK_REPLY_BROADCAST;17const asUser = process.env.SLACK_AS_USER;18const mrkdwn = process.env.SLACK_MRKDWN;19const icon = process.env.SLACK_ICON;20const replyTo = process.env.SLACK_REPLY_TO;21const thread = process.env.SLACK_THREAD;22const unfurl = process.env.SLACK_UNFURL;23const username = process.env.SLACK_USERNAME;24const iconEmoji = process.env.SLACK_ICON_EMOJI;25const iconUrl = process.env.SLACK_ICON_URL;
Using AI Code Generation
1const { sendSlackAlert } = require("@qawolf/slack");2const { slackURL } = require("./slackURL");3const { slackMessage } = require("./slackMessage");4const { slackChannel } = require("./slackChannel");5const { slackBotName } = require("./slackBotName");6const { slackIconEmoji } = require("./slackIconEmoji");7const { slackIconURL } = require("./slackIconURL");8const { slackUsername } = require("./slackUsername");9const { slackBlocks } = require("./slackBlocks");10const { slackAttachments } = require("./slackAttachments");11const { slackText } = require("./slackText");12const { slackBlocks } = require("./slackBlocks");13const { slackAttachments } = require("./slackAttachments");14const { slackText } = require("./slackText");15const { slackBlocks } = require("./slackBlocks");16const { slackAttachments } = require("./slackAttachments");17const { slackText } = require("./slackText");18const { slackBlocks } = require("./slackBlocks");19const { slackAttachments } = require("./slackAttachments");20const { slackText } = require("./slackText");21const { slackBlocks } = require("./slackBlocks");22const { slackAttachments } = require("./slackAttachments");23const { slackText } = require("./slackText");24const { slackBlocks } = require("./slackBlocks");25const { slackAttachments } = require("./slackAttachments");26const { slackText } = require("./slackText");27const { slackBlocks } = require("./slackBlocks");
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!!