npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

back-slack

v0.0.1

Published

Slack backend utilities/services for MPG platform.

Readme

Back Slack Service

Node.js TypeScript License

Service autonome pour gérer l'envoi de messages Slack avec respect du rate-limit et gestion de queue par canal.

🎯 Problématique

Slack impose des rate-limits stricts sur son API :

  • Messages : 60 par minute
  • Mises à jour : 50 par minute
  • Uploads de fichiers : 100 par minute

Quand plusieurs jobs/processus différents envoient des messages simultanément, il devient impossible de respecter ces limites. Ce service centralise toutes les demandes d'envoi et gère intelligemment les queues avec un système de rate-limiting adaptatif.

✨ Fonctionnalités

🚀 Core Features

  • Queue par canal : Chaque canal Slack a sa propre queue avec traitement séquentiel
  • Rate-limiting adaptatif : Délais différenciés selon le type d'opération
  • API REST simple : Interface HTTP intuitive pour tous les besoins Slack
  • Retour du timestamp : Le service retourne le ts du message pour permettre les updates
  • Upload de fichiers : Support complet de l'upload dans les threads Slack
  • Architecture légère : Pas de Redis ni BullMQ pour une maintenance facile

🔧 Technical Features

  • TypeScript : Code entièrement typé pour une meilleure maintenabilité
  • Express.js : API REST robuste et performante
  • fastq : Queue en mémoire ultra-rapide
  • PM2 Ready : Compatible avec PM2 pour la production
  • Health Check : Endpoint de monitoring intégré

📦 Installation

Prérequis

  • Node.js >= 22.21.0
  • npm ou yarn
  • Token bot Slack valide

Installation des dépendances

npm install

Configuration

Créez un fichier .env à la racine du projet :

# Service Configuration
HOSTNAME=localhost
PORT=3741
SERVICE_NAME=slack-service
NODE_ENV=development

# Slack Configuration
SLACK_BOT_TOKEN=xoxb-your-bot-token-here

# Optional Configuration
DISABLE_LOGS=false
DEBUG=false
LOCAL=true

🚀 Utilisation

Démarrage du service

# Mode développement (avec hot-reload)
npm run dev

# Mode production
npm run build
npm start

Vérification du service

# Health check
curl http://localhost:3741/ping
# Response: {"pong": true}

📡 API Reference

POST /slack/post

Envoie un message Slack ou met à jour un message existant.

Request Body:

{
  "channel": "#general",
  "text": "Hello World!",
  "blocks": [
    {
      "type": "section",
      "text": {
        "type": "mrkdwn",
        "text": "*Bold text*"
      }
    }
  ],
  "attachments": [],
  "icon": ":robot_face:",
  "username": "Bot",
  "ts": "1234567890.123456",
  "replyOrUpdate": "reply"
}

Response:

{
  "ts": "1234567890.123456",
  "channel": "C1234567890"
}

Parameters:

  • channel (required): Canal Slack (#general, @user, C1234567890)
  • text (optional): Texte du message
  • blocks (optional): Blocs Slack formatés
  • attachments (optional): Attachments Slack
  • icon (optional): Emoji pour l'icône du bot
  • username (optional): Nom d'utilisateur du bot
  • ts (optional): Timestamp pour update/reply
  • replyOrUpdate (optional): "reply" ou "update"

POST /slack/upload

Upload un fichier dans un thread Slack.

Request Body:

{
  "channel": "#general",
  "content": "Contenu du fichier...",
  "filename": "log.txt",
  "ts": "1234567890.123456",
  "incrementFileName": true
}

Response:

{
  "status": "success"
}

Parameters:

  • channel (required): Canal Slack
  • content (required): Contenu du fichier
  • filename (required): Nom du fichier
  • ts (required): Timestamp du thread parent
  • incrementFileName (optional): Incrémenter le nom si conflit

GET /ping

Vérifie l'état du service.

Response:

{
  "pong": true
}

💻 Client SDK

Installation du client

import SlackServiceClient from './modules/slackClient';

const client = new SlackServiceClient('http://localhost:3741');

Exemples d'utilisation

// Envoyer un message
const { ts, channel } = await client.postMessage({
  channel: '#general',
  text: 'Hello World!',
});

// Mettre à jour le message
await client.updateMessage(channel, ts, {
  text: 'Updated message',
});

// Répondre dans un thread
await client.replyToMessage(channel, ts, {
  text: 'This is a reply',
});

// Uploader un fichier dans le thread
await client.uploadFile({
  channel,
  filename: 'log.txt',
  content: 'Log entry 1\nLog entry 2',
  ts,
  incrementFileName: true,
});

Voir src/tests/exampleUsage.ts pour plus d'exemples complets.

🏗️ Architecture

graph TD
    A[Job A] -->|HTTP POST| B[Express API]
    C[Job B] -->|HTTP POST| B
    D[Job C] -->|HTTP POST| B

    B --> E[QueueManager]
    E --> F[Channel Queue #general]
    E --> G[Channel Queue #alerts]
    E --> H[Channel Queue #logs]

    F --> I[Rate Limiter]
    G --> I
    H --> I

    I --> J[Slack API]

    style B fill:#e1f5fe
    style E fill:#f3e5f5
    style I fill:#fff3e0
    style J fill:#e8f5e8

Composants

  1. Express API : Reçoit les requêtes HTTP et les route vers le QueueManager
  2. QueueManager : Gère les queues par canal et type d'opération
  3. Rate Limiter : Applique les délais selon les limites Slack
  4. Slack Client : Interface avec l'API Slack officielle

Types de queues

  • postMessage : Nouveaux messages (60/min)
  • updateMessage : Mises à jour de messages (50/min)
  • uploadFile : Upload de fichiers (100/min)

⚡ Rate-limiting

Le service respecte automatiquement les rate-limits de Slack :

| Opération | Limite | Délai minimum | |-----------|--------|---------------| | postMessage | 60/min | 1000ms | | updateMessage | 50/min | 1200ms | | uploadFile | 100/min | 600ms |

Mécanisme

  1. Queue par canal : Chaque canal a sa propre queue indépendante
  2. Calcul automatique : Le délai est calculé selon le type d'opération
  3. Traitement séquentiel : Une seule opération à la fois par canal
  4. Garantie de timing : Chaque opération prend au minimum le temps requis

🛠️ Développement

Scripts disponibles

# Build TypeScript
npm run build

# Clean build directory
npm run clean

# Type checking only
npm run typecheck

# Linting
npm run lint
npm run lint:fix

# Formatting
npm run format
npm run format:write

Structure du projet

src/
├── config/           # Configuration et variables d'environnement
├── modules/          # Modules principaux
│   ├── api.ts        # API Express et routes
│   ├── queueManager.ts # Gestion des queues et rate-limiting
│   ├── slack.ts      # Client Slack principal
│   ├── slackClient.ts # SDK client pour les jobs
│   └── utils.ts      # Utilitaires
├── tests/            # Exemples et tests
└── main.ts           # Point d'entrée

📊 Monitoring

Logs

Le service génère des logs détaillés pour chaque opération :

# Exemple de log
Sending message for request abc123 {
  channel: '#general',
  contents: { text: 'Hello World!' },
  icon: ':robot_face:',
  username: 'Bot'
}
Message sent for request abc123: { ts: '1234567890.123456', channel: 'C1234567890' }

Health Check

Utilisez l'endpoint /ping pour vérifier l'état du service dans vos monitoring tools.

🚀 Déploiement

PM2 (Recommandé)

# Installation PM2
npm install -g pm2

# Démarrage
pm2 start lib/main.js --name slack-service

# Monitoring
pm2 monit

Docker (Optionnel)

FROM node:22-alpine
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY lib/ ./lib/
EXPOSE 3741
CMD ["node", "lib/main.js"]

🤝 Contribution

  1. Fork le projet
  2. Créez une branche feature (git checkout -b feature/amazing-feature)
  3. Committez vos changements (git commit -m 'Add amazing feature')
  4. Push vers la branche (git push origin feature/amazing-feature)
  5. Ouvrez une Pull Request

📄 License

Ce projet est sous licence MIT. Voir le fichier LICENSE pour plus de détails.

🆘 Support

Pour toute question ou problème :

  1. Vérifiez les issues existantes
  2. Créez une nouvelle issue avec :
    • Description détaillée du problème
    • Logs d'erreur
    • Configuration utilisée
    • Étapes de reproduction

Développé avec ❤️ pour la plateforme MPG