Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async function sendRequestToSlack( fn ) {
try {
await fn();
} catch ( error ) {
// Check the code property and log the response
if (
error.code === ErrorCode.PlatformError ||
error.code === ErrorCode.RequestError ||
error.code === ErrorCode.RateLimitedError ||
error.code === ErrorCode.HTTPError
) {
console.log( error.data );
} else {
// Some other error, oh no!
console.log(
'The error occurred does not match an error we are checking for in this block.'
);
console.log( error );
}
}
}
async function sendRequestToSlack( fn ) {
try {
await fn();
} catch ( error ) {
// Check the code property and log the response
if (
error.code === ErrorCode.PlatformError ||
error.code === ErrorCode.RequestError ||
error.code === ErrorCode.RateLimitedError ||
error.code === ErrorCode.HTTPError
) {
console.log( error.data );
} else {
// Some other error, oh no!
console.log(
'The error occurred does not match an error we are checking for in this block.'
);
console.log( error );
}
}
}
async function sendRequestToSlack( fn ) {
try {
await fn();
} catch ( error ) {
// Check the code property and log the response
if (
error.code === ErrorCode.PlatformError ||
error.code === ErrorCode.RequestError ||
error.code === ErrorCode.RateLimitedError ||
error.code === ErrorCode.HTTPError
) {
console.log( error.data );
} else {
// Some other error, oh no!
console.log(
'The error occurred does not match an error we are checking for in this block.'
);
console.log( error );
}
}
}
async function sendRequestToSlack( fn ) {
try {
await fn();
} catch ( error ) {
// Check the code property and log the response
if (
error.code === ErrorCode.PlatformError ||
error.code === ErrorCode.RequestError ||
error.code === ErrorCode.RateLimitedError ||
error.code === ErrorCode.HTTPError
) {
console.log( error.data );
} else {
// Some other error, oh no!
console.log(
'The error occurred does not match an error we are checking for in this block.'
);
console.log( error );
}
}
}
// https://slack.dev/bolt/
const { App, ExpressReceiver } = require('@slack/bolt');
const expressReceiver = new ExpressReceiver({
signingSecret: process.env.SLACK_SIGNING_SECRET
});
const app = new App({
token: process.env.SLACK_BOT_TOKEN,
receiver: expressReceiver
});
module.exports.expressApp = expressReceiver.app;
// ------------------------------------------------------
// If you need to use API methods that are not listed on https://api.slack.com/bot-users#methods
// you need to use user api token instead like this:
const { WebClient } = require('@slack/web-api');
app.client = new WebClient(process.env.SLACK_API_TOKEN);
// ------------------------------------------------------
// React to "app_mention" events
app.event('app_mention', ({ event, say }) => {
app.client.users.info({ user: event.user })
.then(res => {
if (res.ok) {
say({
text: `Hi! <@${res.user.name}>`
});
} else {
console.error(`Failed because of ${res.error}`)
}
}).catch(reason => {
console.error(`Failed because ${reason}`)
import { WebClient } from "@slack/web-api";
import NotificationRequest from "../models/notificationRequest";
let slackClient;
if (!process.env.SLACK_TOKEN) {
console.log("SLACK_TOKEN is not set, Slack notifications will not be sent");
} else {
slackClient = new WebClient(process.env.SLACK_TOKEN);
}
export default async function sendSlackNotification(
notificationRequest: NotificationRequest,
) {
if (!process.env.SLACK_TOKEN) {
return;
}
const userResponse = await slackClient.users.lookupByEmail({
email: notificationRequest.user.email,
});
if (!userResponse.ok) {
// user probably doesn't have a Slack account, or e-mails don't match
return;
}
const { users, neighborhoods } = require('./models');
const axios = require('axios');
const bodyParser = require('body-parser');
// Read the signing secret and access token from the environment variables
const slackSigningSecret = process.env.SLACK_SIGNING_SECRET;
const slackAccessToken = process.env.SLACK_ACCESS_TOKEN;
if (!slackSigningSecret || !slackAccessToken) {
throw new Error('A Slack signing secret and access token are required to run this app.');
}
// Create the adapter using the app's signing secret
const slackInteractions = createMessageAdapter(slackSigningSecret);
// Create a Slack Web API client using the access token
const web = new WebClient(slackAccessToken);
// Initialize an Express application
const app = express();
// Attach the adapter to the Express application as a middleware
app.use('/slack/actions', slackInteractions.expressMiddleware());
// Attach the slash command handler
app.post('/slack/commands', bodyParser.urlencoded({ extended: false }), slackSlashCommand);
// Start the express application server
const port = process.env.PORT || 0;
http.createServer(app).listen(port, () => {
console.log(`server listening on port ${port}`);
});
setName: () => {},
debug: (msg: string) => {
// non-ideal way to detect calls to slack.
webLog.debug.bind(webLog);
if (!this.onRemoteCall) { return; }
const match = /apiCall\('([\w\.]+)'\) start/.exec(msg);
if (match && match[1]) {
this.onRemoteCall(match[1]);
}
webLog.debug(msg);
},
warn: webLog.warn.bind(webLog),
info: webLog.info.bind(webLog),
error: webLog.error.bind(webLog),
} as Logger,
logLevel: LogLevel.DEBUG,
...opts,
});
try {
const teamInfo = (await slackClient.team.info()) as TeamInfoResponse;
const auth = (await slackClient.auth.test()) as AuthTestResponse;
const user = (await slackClient.users.info({user: auth.user_id})) as UsersInfoResponse;
log.debug("Created new team client for", teamInfo.team.name);
return { slackClient, team: teamInfo.team, auth, user };
} catch (ex) {
throw Error("Could not create team client: " + ex.data.error);
}
}
}
constructor(opts: {main: Main, client_id: string, client_secret: string, redirect_prefix: string}) {
this.main = opts.main;
this.userTokensWaiting = new Map(); // token -> userId
this.clientId = opts.client_id;
this.clientSecret = opts.client_secret;
this.redirectPrefix = opts.redirect_prefix;
this.client = new WebClient();
}
private async createTeamClient(token: string) {
const opts = this.config ? this.config.slack_client_opts : undefined;
const slackClient = new WebClient(token, {
logger: {
getLevel: () => LogLevel.DEBUG,
setLevel: () => {}, // We don't care about these.
setName: () => {},
debug: (msg: string) => {
// non-ideal way to detect calls to slack.
webLog.debug.bind(webLog);
if (!this.onRemoteCall) { return; }
const match = /apiCall\('([\w\.]+)'\) start/.exec(msg);
if (match && match[1]) {
this.onRemoteCall(match[1]);
}
webLog.debug(msg);
},
warn: webLog.warn.bind(webLog),
info: webLog.info.bind(webLog),