@venturialstd/slack
v0.1.31
Published
Slack Client
Keywords
Readme
@venturialstd/slack
A comprehensive NestJS module for Slack Web API, developed by Venturial, that provides full integration with Slack's platform. This module enables seamless messaging, file management, user interactions, and webhook handling for Slack workspaces.
Features
- Chat Operations: Post, update, delete, and schedule messages with full Block Kit support
- Conversation Management: Create, list, archive, and manage channels and conversations
- User Management: List users, get user info, manage profiles, and handle presence
- File Operations: Upload, download, list, and manage files with remote file support
- Reactions: Add, remove, and manage emoji reactions on messages
- Pins: Pin important messages to channels
- Reminders: Create and manage reminders for users
- Search: Search messages and files across the workspace
- Team Information: Access team details, billing info, and access logs
- Views & Modals: Open, publish, push, and update Slack views and modals
- Webhooks: Built-in webhook controller for receiving Slack events
- DND Management: Manage Do Not Disturb settings
- Emoji Management: List custom emojis in the workspace
- Type Safety: Full TypeScript support with comprehensive type definitions
- Flexible Configuration: Support for per-request configuration or global settings
Installation
npm install @venturialstd/slack
# or
yarn add @venturialstd/slackPeer Dependencies
This package requires the following peer dependencies:
npm install @nestjs/common@^9 || ^10 || ^11 @nestjs/event-emitter@^3.0.0 @venturialstd/core@^2.0.0The package also requires @slack/web-api as a dependency, which is automatically installed.
Basic Usage
1. Import the Module
import { Module } from '@nestjs/common';
import { SlackModule } from '@venturialstd/slack';
@Module({
imports: [
SlackModule,
],
})
export class AppModule {}2. Inject and Use Services
import { Injectable } from '@nestjs/common';
import {
SlackChatService,
SlackConversationsService,
SlackUsersService,
SlackFilesService,
} from '@venturialstd/slack';
@Injectable()
export class NotificationService {
constructor(
private readonly chatService: SlackChatService,
private readonly conversationsService: SlackConversationsService,
private readonly usersService: SlackUsersService,
private readonly filesService: SlackFilesService,
) {}
async sendNotification(channelId: string, message: string) {
// Send a message to a channel
const result = await this.chatService.postMessage(null, {
channel: channelId,
text: message,
});
return result;
}
async listChannels() {
// List all channels
const result = await this.conversationsService.list(null, {
types: 'public_channel,private_channel',
});
return result;
}
async getUserInfo(userId: string) {
// Get user information
const result = await this.usersService.info(null, {
user: userId,
});
return result;
}
}3. Using Custom Configuration
You can pass a custom configuration for each request:
import { SlackConfig } from '@venturialstd/slack';
@Injectable()
export class MultiWorkspaceService {
constructor(private readonly chatService: SlackChatService) {}
async sendToWorkspace(workspaceToken: string, channelId: string, message: string) {
const config: SlackConfig = {
botToken: workspaceToken,
};
return await this.chatService.postMessage(config, {
channel: channelId,
text: message,
});
}
}Configuration
Settings-Based Configuration
The module uses @venturialstd/core SettingsModule for configuration. Configure the bot token in your settings:
Setting Key: GLOBAL:SLACK:GENERAL:BOT_TOKEN
Setting Type: SECRET
Description: Bot User OAuth Token for Slack API authentication. Required for all API requests.
Environment Variables
You can also configure the bot token through your application's settings system. The module will automatically use the configured token when no custom config is provided.
Custom Configuration
For multi-workspace scenarios or dynamic token management, you can pass a SlackConfig object to any service method:
const config: SlackConfig = {
botToken: 'xoxb-your-bot-token',
};
await chatService.postMessage(config, { channel: 'C123', text: 'Hello' });API Reference
All service methods follow the pattern:
async methodName(config: SlackConfig | null = null, args: MethodArguments)The config parameter is optional. If null or not provided, the module uses the token from settings.
SlackChatService
Handles all chat-related operations.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| postMessage(config, args) | Post a message to a channel | ChatPostMessageArguments |
| update(config, args) | Update an existing message | ChatUpdateArguments |
| delete(config, args) | Delete a message | ChatDeleteArguments |
| scheduleMessage(config, args) | Schedule a message for later | ChatScheduleMessageArguments |
| getPermalink(config, args) | Get a permalink for a message | ChatGetPermalinkArguments |
| unfurl(config, args) | Unfurl links in a message | ChatUnfurlArguments |
| scheduledMessagesList(config, args) | List scheduled messages | ChatScheduledMessagesListArguments |
| deleteScheduledMessage(config, args) | Delete a scheduled message | ChatDeleteScheduledMessageArguments |
Example:
await chatService.postMessage(null, {
channel: 'C1234567890',
text: 'Hello, world!',
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: 'This is a *formatted* message',
},
},
],
});SlackConversationsService
Manages channels and conversations.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| list(config, args) | List conversations | ConversationsListArguments |
| create(config, args) | Create a new conversation | ConversationsCreateArguments |
| history(config, args) | Get conversation history | ConversationsHistoryArguments |
| replies(config, args) | Get thread replies | ConversationsRepliesArguments |
| info(config, args) | Get conversation info | ConversationsInfoArguments |
| invite(config, args) | Invite users to conversation | ConversationsInviteArguments |
| kick(config, args) | Remove user from conversation | ConversationsKickArguments |
| join(config, args) | Join a conversation | ConversationsJoinArguments |
| leave(config, args) | Leave a conversation | ConversationsLeaveArguments |
| members(config, args) | Get conversation members | ConversationsMembersArguments |
| open(config, args) | Open a direct message | ConversationsOpenArguments |
| rename(config, args) | Rename a conversation | ConversationsRenameArguments |
| setPurpose(config, args) | Set conversation purpose | ConversationsSetPurposeArguments |
| setTopic(config, args) | Set conversation topic | ConversationsSetTopicArguments |
| archive(config, args) | Archive a conversation | ConversationsArchiveArguments |
| unarchive(config, args) | Unarchive a conversation | ConversationsUnarchiveArguments |
| mark(config, args) | Mark conversation as read | ConversationsMarkArguments |
Example:
// List all public channels
const channels = await conversationsService.list(null, {
types: 'public_channel',
limit: 100,
});
// Create a new channel
const newChannel = await conversationsService.create(null, {
name: 'my-new-channel',
is_private: false,
});SlackUsersService
Manages user information and profiles.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| list(config, args) | List all users | UsersListArguments |
| info(config, args) | Get user information | UsersInfoArguments |
| lookupByEmail(config, args) | Find user by email | UsersLookupByEmailArguments |
| setPhoto(config, args) | Set user photo | UsersSetPhotoArguments |
| setPresence(config, args) | Set user presence | UsersSetPresenceArguments |
| getPresence(config, args) | Get user presence | UsersGetPresenceArguments |
| identity(config, args) | Get user identity | UsersIdentityArguments |
| profileGet(config, args) | Get user profile | UsersProfileGetArguments |
| profileSet(config, args) | Set user profile | UsersProfileSetArguments |
| deletePhoto(config, args) | Delete user photo | UsersDeletePhotoArguments |
Example:
// Get user info
const user = await usersService.info(null, {
user: 'U1234567890',
});
// Lookup user by email
const userByEmail = await usersService.lookupByEmail(null, {
email: '[email protected]',
});SlackFilesService
Handles file operations.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| upload(config, args) | Upload a file (⚠️ Deprecated - Use getUploadURLExternal + completeUploadExternal instead. Retired Nov 12, 2025) | FilesUploadArguments |
| info(config, args) | Get file information | FilesInfoArguments |
| list(config, args) | List files | FilesListArguments |
| delete(config, args) | Delete a file | FilesDeleteArguments |
| revokePublicURL(config, args) | Revoke public URL | FilesRevokePublicURLArguments |
| sharedPublicURL(config, args) | Share public URL | FilesSharedPublicURLArguments |
| getUploadURLExternal(config, args) | Get external upload URL | FilesGetUploadURLExternalArguments |
| completeUploadExternal(config, args) | Complete external upload | FilesCompleteUploadExternalArguments |
| remoteInfo(config, args) | Get remote file info | FilesRemoteInfoArguments |
| remoteList(config, args) | List remote files | FilesRemoteListArguments |
| remoteAdd(config, args) | Add remote file | FilesRemoteAddArguments |
| remoteUpdate(config, args) | Update remote file | FilesRemoteUpdateArguments |
| remoteRemove(config, args) | Remove remote file | FilesRemoteRemoveArguments |
| remoteShare(config, args) | Share remote file | FilesRemoteShareArguments |
Example:
// Upload a file using the new recommended method
// Step 1: Get upload URL
const uploadUrl = await filesService.getUploadURLExternal(null, {
filename: 'document.pdf',
length: fileSize,
});
// Step 2: Upload file to the URL (using fetch or similar)
await fetch(uploadUrl.upload_url, {
method: 'POST',
body: fileBuffer,
headers: uploadUrl.headers,
});
// Step 3: Complete the upload
const file = await filesService.completeUploadExternal(null, {
files: [{
id: uploadUrl.file_id,
title: 'Important Document',
}],
channel_id: 'C1234567890',
});
// Note: The old upload() method is deprecated and will be retired Nov 12, 2025SlackReactionsService
Manages emoji reactions.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| add(config, args) | Add a reaction | ReactionsAddArguments |
| get(config, args) | Get reactions for an item | ReactionsGetArguments |
| list(config, args) | List reactions by user | ReactionsListArguments |
| remove(config, args) | Remove a reaction | ReactionsRemoveArguments |
Example:
// Add a reaction
await reactionsService.add(null, {
channel: 'C1234567890',
timestamp: '1234567890.123456',
name: 'thumbsup',
});SlackRemindersService
Manages reminders.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| add(config, args) | Create a reminder | RemindersAddArguments |
| complete(config, args) | Complete a reminder | RemindersCompleteArguments |
| delete(config, args) | Delete a reminder | RemindersDeleteArguments |
| info(config, args) | Get reminder info | RemindersInfoArguments |
| list(config, args) | List reminders | RemindersListArguments |
SlackPinsService
Manages pinned messages.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| add(config, args) | Pin an item | PinsAddArguments |
| list(config, args) | List pinned items | PinsListArguments |
| remove(config, args) | Unpin an item | PinsRemoveArguments |
SlackDndService
Manages Do Not Disturb settings.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| info(config, args) | Get DND info | DndInfoArguments |
| setSnooze(config, args) | Set DND snooze | DndSetSnoozeArguments |
| endDnd(config, args) | End DND | DndEndDndArguments |
| endSnooze(config, args) | End DND snooze | DndEndSnoozeArguments |
| teamInfo(config, args) | Get team DND info | DndTeamInfoArguments |
SlackEmojiService
Manages emoji.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| list(config, args) | List custom emojis | EmojiListArguments |
SlackTeamService
Accesses team information.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| info(config, args) | Get team info | TeamInfoArguments |
| billableInfo(config, args) | Get billable info | TeamBillableInfoArguments |
| integrationLogs(config, args) | Get integration logs | TeamIntegrationLogsArguments |
| profileGet(config, args) | Get team profile | TeamProfileGetArguments |
| accessLogs(config, args) | Get access logs | TeamAccessLogsArguments |
SlackSearchService
Searches messages and files.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| messages(config, args) | Search messages | SearchMessagesArguments |
| files(config, args) | Search files | SearchFilesArguments |
| all(config, args) | Search all | SearchAllArguments |
Example:
// Search for messages
const results = await searchService.messages(null, {
query: 'important',
sort: 'timestamp',
count: 20,
});SlackViewsService
Manages views and modals.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| open(config, args) | Open a view | ViewsOpenArguments |
| publish(config, args) | Publish a view | ViewsPublishArguments |
| push(config, args) | Push a view | ViewsPushArguments |
| update(config, args) | Update a view | ViewsUpdateArguments |
SlackAuthService
Handles authentication.
| Method | Description | Arguments Type |
|--------|-------------|----------------|
| test(config, args) | Test authentication | AuthTestArguments |
| revoke(config, args) | Revoke token | AuthRevokeArguments |
Webhooks
The module includes a built-in webhook controller for receiving Slack events.
Endpoint
POST /general/slack/webhook
Configuration
Configure your Slack app's Event Subscriptions to point to this endpoint.
Event Handling
The controller automatically handles:
- URL Verification: Responds to Slack's challenge during setup
- Event Callbacks: Emits events via
@nestjs/event-emitter
Listening to Events
import { Injectable } from '@nestjs/common';
import { OnEvent } from '@nestjs/event-emitter';
import { EVENT_EMITTER_SLACK_EVENTS } from '@venturialstd/slack';
@Injectable()
export class SlackEventHandler {
@OnEvent(EVENT_EMITTER_SLACK_EVENTS.WEBHOOK_INCOMING_MESSAGE)
handleIncomingMessage(payload: { data: SlackMessageEvent }) {
console.log('New message:', payload.data);
// Handle the message
}
}Available Events
WEBHOOK_INCOMING_MESSAGE: Emitted when a message event is received
Types
SlackConfig
interface SlackConfig {
botToken?: string;
}SlackMessageEvent
interface SlackMessageEvent {
type: string;
user?: string;
text?: string;
channel: string;
ts: string;
thread_ts?: string;
bot_id?: string;
client_msg_id?: string;
team?: string;
event_ts?: string;
channel_type?: string;
blocks?: unknown[];
}All argument types are imported from @slack/web-api and are fully typed.
Notes
Rate Limiting
Slack API has rate limits. The module doesn't implement rate limiting internally. Consider implementing rate limiting in your application if you expect high-volume usage.
Error Handling
All service methods include error handling and logging. Errors are logged using the AppLogger and then re-thrown for your application to handle.
Token Management
- If no
configis provided, the module uses the token from settings - If
configis provided with abotToken, it uses that token for the request - The client caches the WebClient instance when using settings-based configuration
- Each request with a custom config creates a new client instance
Type Safety
All methods use TypeScript types from @slack/web-api, ensuring type safety and IntelliSense support.
Block Kit Support
The chat service fully supports Slack's Block Kit for rich message formatting. See Slack Block Kit documentation for details.
Deprecated Features
- files.upload: The
files.uploadmethod is deprecated by Slack. UsegetUploadURLExternalandcompleteUploadExternalinstead for better reliability with larger files. The method will be retired on November 12, 2025. For new apps created after May 16, 2024, this method is not available. See Slack's migration guide for details.
Removed Features
The following services have been removed from this module due to Slack API deprecation:
SlackStarsService: The Stars API was deprecated by Slack in favor of "Save it for Later" feature. There is no public API available for the new "Later" feature. The Stars API methods no longer reflect what users see in Slack's UI.
SlackWorkflowsService: The Workflows API methods (
stepCompleted,stepFailed,updateStep) were retired by Slack on September 26, 2024. Slack now uses custom functions in their new automation platform instead. See Slack's changelog for migration guidance.
Best Practices
- Use Settings for Default Token: Configure the bot token in settings for most use cases
- Custom Config for Multi-Workspace: Use
SlackConfigfor scenarios with multiple workspaces - Error Handling: Always wrap service calls in try-catch blocks
- Rate Limiting: Implement rate limiting for high-volume applications
- Webhook Security: Verify webhook requests using Slack's signing secret (implement in your application)
Related Documentation
License
MIT
Support
For issues and feature requests, please contact Venturial support or open an issue in the repository.
