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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dieugene/tg-messages-cache

v2.0.2

Published

Модуль кеширования сообщений Telegram с поддержкой CRUD операций и placeholder сообщений

Readme

Telegram Messages Cache

Модуль для кеширования сообщений Telegram ботов с поддержкой CRUD операций и управления placeholder сообщениями.

Возможности

  • ✅ Кеширование сообщений Telegram по пользователям и ботам
  • ✅ CRUD операции: добавление, получение, редактирование, удаление
  • ✅ Поддержка placeholder сообщений для индикации прогресса
  • ✅ Автоматическое управление подтверждающими сообщениями
  • ✅ Исключение placeholder из основного кеша
  • ✅ Хеширование идентификаторов для уникальности

Установка

npm install @dieugene/tg-messages-cache

Зависимости

  • @dieugene/key-value-db - для хранения данных
  • @dieugene/utils - утилиты для работы с Telegram

Использование

const cache = require('@dieugene/tg-messages-cache');

// Инициализация (автоматически вызывается при импорте)
cache.init();

// Добавление сообщения в кеш
await cache.add(ctx, {
    message_id: 123,
    text: 'Текст сообщения'
});

// Получение всех сообщений из кеша
const messages = await cache.get(ctx);

// Получение сообщений без placeholder
const messagesClean = await cache.get(ctx, true);

// Редактирование сообщения
await cache.edit(ctx, message_id, 'Новый текст');

// Удаление конкретного сообщения
await cache.del(ctx, message_id);

// Удаление всего кеша пользователя
await cache.del(ctx);

API

cache.add(ctx, options)

Добавляет сообщение в кеш.

Параметры:

  • ctx - контекст Telegram бота
  • options (опционально):
    • message_id - ID сообщения (по умолчанию из ctx)
    • text - текст сообщения (по умолчанию из ctx)

cache.get(ctx, excludePlaceholder)

Получает все сообщения из кеша.

Параметры:

  • ctx - контекст Telegram бота
  • excludePlaceholder - исключить placeholder сообщения (по умолчанию false)

cache.edit(ctx, message_id, text)

Редактирует текст сообщения в кеше.

Параметры:

  • ctx - контекст Telegram бота
  • message_id - ID сообщения для редактирования
  • text - новый текст сообщения

cache.del(ctx, message_id)

Удаляет сообщение из кеша.

Параметры:

  • ctx - контекст Telegram бота
  • message_id - ID сообщения (если не указан, удаляется весь кеш)

Работа с Placeholder

cache.cache_and_show_progress(ctx, options)

Кеширует сообщения и показывает прогресс через placeholder.

Параметры:

  • ctx - контекст Telegram бота
  • options:
    • show_placeholder - показывать placeholder (по умолчанию true)
    • placeholder_text - текст placeholder
    • message_id - ID сообщения
    • text - текст сообщения (может быть массивом)
    • placeholder_message_id - ID существующего placeholder

cache.put_placeholder(ctx, text)

Создает placeholder сообщение.

Параметры:

  • ctx - контекст Telegram бота
  • text - текст placeholder (по умолчанию "✍")

cache.del_placeholder(ctx, message_id)

Удаляет placeholder сообщение.

Параметры:

  • ctx - контекст Telegram бота
  • message_id - ID placeholder сообщения

cache.get_placeholder_message_id(ctx, cache)

Получает ID placeholder сообщения из кеша.

Параметры:

  • ctx - контекст Telegram бота
  • cache - кеш сообщений (опционально)

cache.exclude_placeholder(cache)

Исключает placeholder сообщения из массива.

Параметры:

  • cache - массив сообщений

Примеры использования

Простое кеширование

const { Telegraf } = require('telegraf');
const cache = require('@dieugene/tg-messages-cache');

const bot = new Telegraf(process.env.BOT_TOKEN);

bot.on('text', async (ctx) => {
    // Добавляем сообщение в кеш
    await cache.add(ctx);
    
    // Получаем историю сообщений
    const history = await cache.get(ctx, true); // без placeholder
    console.log('История:', history);
});

Использование с прогрессом

bot.command('process', async (ctx) => {
    // Начинаем процесс с показом прогресса
    await cache.cache_and_show_progress(ctx, {
        text: 'Начинаем обработку...',
        placeholder_text: '⏳ Обработка...'
    });
    
    // Выполняем длительную операцию
    await longRunningOperation();
    
    // Удаляем placeholder
    await cache.del_placeholder(ctx);
    
    await ctx.reply('Готово!');
});

Структура данных

Каждое сообщение в кеше имеет структуру:

{
    message_id: Number,  // ID сообщения в Telegram
    text: String        // Текст сообщения
}

Placeholder сообщения имеют специальный текст: '<<confirmation message>>'

Лицензия

ISC

Автор

Eugene Ditkovsky