CustomJS is a flexible solution that allows you to run JavaScript to create custom automations and integrations. With CustomJS, you can set up automated actions to create a simple Slack bot that writes new welcome messages to new members and integrate it with various platforms.
Here is an example code that sends a predefined slack message to each new slack user. In this example it is sent in my name but you can also use a bot token to send it in the name of your bot. You still have to create the variable token and add it to your token. You can find out how to do this in the integration instructions.
const axios = require("axios");
const userToken = variables.token;
const text =
"Welcome! I am Henrik, the founder of CustomJS. If you need help with getting CustomJS up an running just write me a message.";
if (input.event.type === "team_join") {
await sendMessageToUser(input.event.user.id);
}
return input.challenge;
/////////
async function sendMessageToUser(userId) {
try {
const imResponse = await axios.post(
"https://slack.com/api/conversations.open",
{
users: userId,
},
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${userToken}`,
},
}
);
if (!imResponse.data.ok) {
throw new Error(imResponse.data.error);
}
const channelId = imResponse.data.channel.id;
const messageResponse = await axios.post(
"https://slack.com/api/chat.postMessage",
{
channel: channelId,
text: text,
},
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${userToken}`,
},
}
);
if (messageResponse.data.ok) {
console.log("Message sent successfully:", messageResponse.data);
} else {
console.log("Error sending message:", messageResponse.data.error);
}
} catch (error) {
console.log("Error:", error);
}
}
Learn more about how to create a Slack app and connect it with CustomJS.
How to create a Slack App.