From 55b4ac192578a9ca8553486f0ab7dd3bda126086 Mon Sep 17 00:00:00 2001 From: Tema Smirnov Date: Wed, 11 Jan 2023 06:02:33 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=93=9D=20Improved=20code-examples=20/=20U?= =?UTF-8?q?pdated:=20README=20&=20LICENSE,=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- LICENSE | 2 +- README.md | 40 ++++----- docs/LocalSession.html | 108 +++++++++++++++--------- docs/global.html | 34 ++++++-- docs/index.html | 67 ++++++++------- docs/module-telegraf-session-local.html | 53 +++--------- docs/scripts/collapse.js | 19 +++++ docs/scripts/commonNav.js | 28 ++++++ docs/scripts/search.js | 16 ++++ docs/session.js.html | 7 +- docs/styles/jsdoc.css | 15 +++- docs/styles/prettify.css | 1 + examples/extra.js | 27 +++--- examples/simple.js | 6 +- 14 files changed, 255 insertions(+), 168 deletions(-) create mode 100644 docs/scripts/commonNav.js diff --git a/LICENSE b/LICENSE index 0bdbb35..83225b9 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ The MIT License (MIT) -Copyright (c) 2020 Tema Smirnov and contributors +Copyright (c) 2023 Tema Smirnov and contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index c52f0fc..a32c168 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,10 @@ [![NPM Version](https://img.shields.io/npm/v/telegraf-session-local.svg?style=flat-square)](https://www.npmjs.com/package/telegraf-session-local) [![Nodejs](https://img.shields.io/node/v/telegraf-session-local.svg?style=flat-square)](https://www.npmjs.com/package/telegraf-session-local) -[![npm](https://img.shields.io/npm/dm/telegraf-session-local.svg?style=flat-square)](https://npmcharts.com/compare/telegraf-session-local,telegraf-session-redis,telegraf-session-mysql,telegraf-session-mongo,telegraf-session-dynamodb?interval=30) -[![GitHub Actions Status](https://img.shields.io/github/workflow/status/RealSpeaker/telegraf-session-local/CI?style=flat-square)](https://github.com/RealSpeaker/telegraf-session-local/actions) +[![NPM downloads/month](https://img.shields.io/npm/dm/telegraf-session-local.svg?style=flat-square)](https://npmcharts.com/compare/telegraf-session-local,telegraf-session-redis,telegraf-session-dynamodb,telegraf-postgres-session,telegraf-session-mysql,telegraf-session-mongoose,telegraf-session-mongo,telegraf-session-rethinkdb?interval=30) +[![GitHub Actions Status](https://img.shields.io/github/actions/workflow/status/RealSpeaker/telegraf-session-local/ci.yml?style=flat-square)](https://github.com/RealSpeaker/telegraf-session-local/actions) [![Coveralls](https://img.shields.io/coveralls/github/RealSpeaker/telegraf-session-local/master.svg?style=flat-square)](https://coveralls.io/github/RealSpeaker/telegraf-session-local?branch=master) -[![LGTM Grade](https://img.shields.io/lgtm/grade/javascript/g/RealSpeaker/telegraf-session-local.svg?style=flat-square&?logo=lgtm&logoWidth=18)](https://lgtm.com/projects/g/RealSpeaker/telegraf-session-local/context:javascript) -[![David](https://img.shields.io/david/RealSpeaker/telegraf-session-local.svg?style=flat-square)](https://david-dm.org/RealSpeaker/telegraf-session-local) +![GitHub last commit](https://img.shields.io/github/last-commit/RealSpeaker/telegraf-session-local?style=flat-square) > Middleware for locally stored sessions & database @@ -43,16 +42,16 @@ bot.use((new LocalSession({ database: 'example_db.json' })).middleware()) bot.on('text', (ctx, next) => { ctx.session.counter = ctx.session.counter || 0 ctx.session.counter++ - ctx.replyWithMarkdown(`Counter updated, new value: \`${ctx.session.counter}\``) + ctx.replyWithMarkdownV2(`Counter updated, new value: \`${ctx.session.counter}\``) return next() }) bot.command('/stats', (ctx) => { - ctx.replyWithMarkdown(`Database has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`) + ctx.replyWithMarkdownV2(`Database has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`) }) bot.command('/remove', (ctx) => { - ctx.replyWithMarkdown(`Removing session from database: \`${JSON.stringify(ctx.session)}\``) + ctx.replyWithMarkdownV2(`Removing session from database: \`${JSON.stringify(ctx.session)}\``) // Setting session to null, undefined or empty object/array will trigger removing it from database ctx.session = null }) @@ -68,9 +67,6 @@ const LocalSession = require('telegraf-session-local') const bot = new Telegraf(process.env.BOT_TOKEN) // Your Bot token here -// Name of session property object in Telegraf Context (default: 'session') -const property = 'data' - const localSession = new LocalSession({ // Database name/path, where sessions will be located (default: 'sessions.json') database: 'example_db.json', @@ -94,30 +90,28 @@ localSession.DB.then(DB => { // console.log(DB.get('sessions').getById('1:1').value()) }) -// Telegraf will use `telegraf-session-local` configured above middleware with overrided `property` value: `data`, instead of `session` -bot.use(localSession.middleware(property)) +// Telegraf will use `telegraf-session-local` configured above middleware +bot.use(localSession.middleware()) bot.on('text', (ctx, next) => { - ctx[property].counter = ctx[property].counter || 0 - ctx[property].counter++ - ctx.replyWithMarkdown(`Counter updated, new value: \`${ctx[property].counter}\``) + ctx.session.counter = ctx.session.counter || 0 + ctx.session.counter++ + ctx.replyWithMarkdownV2(`Counter updated, new value: \`${ctx.session.counter}\``) // Writing message to Array `messages` into database which already has sessions Array - ctx[property + 'DB'].get('messages').push([ctx.message]).write() - // `property`+'DB' is a name of property which contains lowdb instance, default = `sessionDB`, in current example = `dataDB` - // ctx.dataDB.get('messages').push([ctx.message]).write() + ctx.sessionDB.get('messages').push([ctx.message]).write() + // `property`+'DB' is a name of ctx property which contains lowdb instance, default = `sessionDB` return next() }) bot.command('/stats', (ctx) => { - let msg = `Using session object from [Telegraf Context](http://telegraf.js.org/context.html) (\`ctx\`), named \`${property}\`\n` - msg += `Database has \`${ctx[property].counter}\` messages from @${ctx.from.username || ctx.from.id}` - ctx.replyWithMarkdown(msg) + ctx.replyWithMarkdownV2(`Session has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`) }) + bot.command('/remove', (ctx) => { - ctx.replyWithMarkdown(`Removing session from database: \`${JSON.stringify(ctx[property])}\``) + ctx.replyWithMarkdownV2(`Removing session from lowdb database: \`${JSON.stringify(ctx.session)}\``) // Setting session to null, undefined or empty object/array will trigger removing it from database - ctx[property] = null + ctx.session = null }) bot.launch() diff --git a/docs/LocalSession.html b/docs/LocalSession.html index cee75ec..e0a7556 100644 --- a/docs/LocalSession.html +++ b/docs/LocalSession.html @@ -20,6 +20,7 @@ + @@ -35,7 +36,9 @@ -

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

Global

+ +

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

+
@@ -53,7 +56,9 @@

LocalSession

- LocalSession + + LocalSession +

Represents a wrapper around locally stored session, it's middleware & lowdb

@@ -79,6 +84,7 @@

new Local
+
Source:
@@ -130,9 +136,7 @@

new Local - - -

Parameters:
+
Parameters:
@@ -168,6 +172,7 @@
Parameters:
Object + @@ -222,6 +227,7 @@
Properties
String + @@ -255,6 +261,7 @@
Properties
String + @@ -288,6 +295,7 @@
Properties
Object + @@ -321,6 +329,7 @@
Properties
function + @@ -354,6 +363,7 @@
Properties
Object + @@ -408,6 +418,7 @@
Properties
function + @@ -441,6 +452,7 @@
Properties
function + @@ -481,6 +493,7 @@
Properties
Object + @@ -535,6 +548,7 @@
Properties
function + @@ -568,6 +582,7 @@
Properties
function + @@ -621,7 +636,7 @@
Properties
-
Returns:
+
Returns:
@@ -655,13 +670,17 @@

Members

-

(readonly) .storagefileAsync

+

(readonly) .storagefileAsync

+ +
Description:
+
+
Source:
@@ -718,13 +737,17 @@

(readonly) -

(readonly) .storagefileSync

+

(readonly) .storagefileSync

+ +
Description:
+
+
Source:
@@ -798,6 +821,10 @@

getSession<
+ +
Description:
+
  • Get session by it's key in database

+
Source:
@@ -841,12 +868,6 @@

getSession< -
-

Get session by it's key in database

-
- - - @@ -855,7 +876,7 @@

getSession< -

Parameters:
+
Parameters:

@@ -889,6 +910,7 @@
Parameters:
String + @@ -918,7 +940,7 @@
Parameters:
-
Returns:
+
Returns:
@@ -936,6 +958,7 @@
Returns:
Object + @@ -956,6 +979,10 @@

getSessi
+ +
Description:
+
+
Source:
@@ -999,11 +1026,6 @@

getSessi -
-

Get session key from Telegraf Context

-
- - @@ -1012,8 +1034,7 @@

getSessi - -

Parameters:
+
Parameters:

@@ -1047,6 +1068,7 @@
Parameters:
Object + @@ -1076,7 +1098,7 @@
Parameters:
-
Returns:
+
Returns:
@@ -1094,6 +1116,7 @@
Returns:
String + @@ -1114,6 +1137,10 @@

middleware<
+ +
Description:
+
  • Session middleware for use in Telegraf

+
Source:
@@ -1157,11 +1184,6 @@

middleware< -
-

Session middleware for use in Telegraf

-
- - @@ -1170,8 +1192,7 @@

middleware< - -

Parameters:
+
Parameters:

@@ -1207,6 +1228,7 @@
Parameters:
String + @@ -1246,7 +1268,7 @@
Parameters:
-
Returns:
+
Returns:
@@ -1260,6 +1282,7 @@
Returns:
Promise + @@ -1272,7 +1295,7 @@
Returns:
-

(async) saveSession(key, data) → {Promise|function}

+

(async) saveSession(key, data) → {Promise|function}

@@ -1280,6 +1303,10 @@

(async) sa
+ +
Description:
+
  • Save session to database

+
Source:
@@ -1323,12 +1350,6 @@

(async) sa -
-

Save session to database

-
- - - @@ -1337,7 +1358,7 @@

(async) sa -

Parameters:
+
Parameters:

@@ -1371,6 +1392,7 @@
Parameters:
String + @@ -1394,6 +1416,7 @@
Parameters:
Object + @@ -1423,7 +1446,7 @@
Parameters:
-
Returns:
+
Returns:
@@ -1446,6 +1469,7 @@
Returns:
function + @@ -1473,7 +1497,7 @@
Returns:

diff --git a/docs/global.html b/docs/global.html index 276d1dd..71d1467 100644 --- a/docs/global.html +++ b/docs/global.html @@ -20,6 +20,7 @@ + @@ -35,7 +36,9 @@ -

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

Global

+ +

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

+
@@ -54,6 +57,8 @@

Global

+ +

@@ -66,6 +71,7 @@

+ @@ -127,13 +133,17 @@

Members

-

(readonly) LocalSession.storageBase

+

(readonly) LocalSession.storageBase

+ +
Description:
+
+
Source:
@@ -190,13 +200,17 @@

(rea -

(readonly) LocalSession.storageFileAsync

+

(readonly) LocalSession.storageFileAsync

+ +
Description:
+
+
Source:
@@ -253,13 +267,17 @@

(readonly) LocalSession.storageFileSync

+

(readonly) LocalSession.storageFileSync

+ +
Description:
+
+
Source:
@@ -316,13 +334,17 @@

-

(readonly) LocalSession.storageMemory

+

(readonly) LocalSession.storageMemory

+ +
Description:
+
  • lowdb storage/adapter named Memory

+
Source:
@@ -399,7 +421,7 @@

(r
diff --git a/docs/index.html b/docs/index.html index 4634285..0007f88 100644 --- a/docs/index.html +++ b/docs/index.html @@ -20,6 +20,7 @@ + @@ -35,7 +36,9 @@ -

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

Global

+ +

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

+
@@ -67,12 +70,11 @@

Telegraf Session local

NPM Version
-node
-npm
-Travis (.org) branch
-Coveralls github branch
-Codacy branch grade
-David

+Nodejs
+NPM downloads/month
+GitHub Actions Status
+Coveralls
+GitHub last commit

Middleware for locally stored sessions & database

@@ -93,11 +95,17 @@

⚡️ Features

🚀 Installation

-
$ npm install telegraf-session-local -S
+
$ npm install -S telegraf-session-local
 
-

Documentation & API

+
+

💡 TIP: We recommend pnpm package manager: npm i -g pnpm and then pnpm i -S telegraf-session-local.
+It's in-place replacement for npm, faster and better than npm/yarn, and saves your disk space.

+
+
+

📚 Documentation & API

+

👀 Quick-start example

-
const {Telegraf} = require('telegraf')
+
const { Telegraf } = require('telegraf')
 const LocalSession = require('telegraf-session-local')
 
 const bot = new Telegraf(process.env.BOT_TOKEN) // Your Bot token here
@@ -107,31 +115,28 @@ 

👀 Quick-start example

bot.on('text', (ctx, next) => { ctx.session.counter = ctx.session.counter || 0 ctx.session.counter++ - ctx.replyWithMarkdown(`Counter updated, new value: \`${ctx.session.counter}\``) + ctx.replyWithMarkdownV2(`Counter updated, new value: \`${ctx.session.counter}\``) return next() }) bot.command('/stats', (ctx) => { - ctx.replyWithMarkdown(`Database has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`) + ctx.replyWithMarkdownV2(`Database has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`) }) bot.command('/remove', (ctx) => { - ctx.replyWithMarkdown(`Removing session from database: \`${JSON.stringify(ctx.session)}\``) + ctx.replyWithMarkdownV2(`Removing session from database: \`${JSON.stringify(ctx.session)}\``) // Setting session to null, undefined or empty object/array will trigger removing it from database ctx.session = null }) bot.launch()
-

💡 Full example

-
const {Telegraf} = require('telegraf')
+

📄 Full example

+
const { Telegraf } = require('telegraf')
 const LocalSession = require('telegraf-session-local')
 
 const bot = new Telegraf(process.env.BOT_TOKEN) // Your Bot token here
 
-// Name of session property object in Telegraf Context (default: 'session')
-const property = 'data'
-
 const localSession = new LocalSession({
   // Database name/path, where sessions will be located (default: 'sessions.json')
   database: 'example_db.json',
@@ -155,30 +160,28 @@ 

💡 Full example

// console.log(DB.get('sessions').getById('1:1').value()) }) -// Telegraf will use `telegraf-session-local` configured above middleware with overrided `property` name -bot.use(localSession.middleware(property)) +// Telegraf will use `telegraf-session-local` configured above middleware +bot.use(localSession.middleware()) bot.on('text', (ctx, next) => { - ctx[property].counter = ctx[property].counter || 0 - ctx[property].counter++ - ctx.replyWithMarkdown(`Counter updated, new value: \`${ctx.session.counter}\``) + ctx.session.counter = ctx.session.counter || 0 + ctx.session.counter++ + ctx.replyWithMarkdownV2(`Counter updated, new value: \`${ctx.session.counter}\``) // Writing message to Array `messages` into database which already has sessions Array - ctx[property + 'DB'].get('messages').push([ctx.message]).write() - // `property`+'DB' is a name of property which contains lowdb instance, default = `sessionDB`, in current example = `dataDB` - // ctx.dataDB.get('messages').push([ctx.message]).write() + ctx.sessionDB.get('messages').push([ctx.message]).write() + // `property`+'DB' is a name of ctx property which contains lowdb instance, default = `sessionDB` return next() }) bot.command('/stats', (ctx) => { - let msg = `Using session object from [Telegraf Context](http://telegraf.js.org/context.html) (\`ctx\`), named \`${property}\`\n` - msg += `Database has \`${ctx[property].counter}\` messages from @${ctx.from.username || ctx.from.id}` - ctx.replyWithMarkdown(msg) + ctx.replyWithMarkdownV2(`Session has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`) }) + bot.command('/remove', (ctx) => { - ctx.replyWithMarkdown(`Removing session from database: \`${JSON.stringify(ctx[property])}\``) + ctx.replyWithMarkdownV2(`Removing session from lowdb database: \`${JSON.stringify(ctx.session)}\``) // Setting session to null, undefined or empty object/array will trigger removing it from database - ctx[property] = null + ctx.session = null }) bot.launch() @@ -201,7 +204,7 @@


diff --git a/docs/module-telegraf-session-local.html b/docs/module-telegraf-session-local.html index dcd7a3c..c3d2869 100644 --- a/docs/module-telegraf-session-local.html +++ b/docs/module-telegraf-session-local.html @@ -20,6 +20,7 @@ + @@ -35,7 +36,9 @@ -

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

Global

+ +

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

+
@@ -52,10 +55,6 @@

telegraf-session-local

- - - -
@@ -63,16 +62,12 @@

telegraf-session-local

-

Telegraf Session middleware for storing sessions locally (Memory/FileSync/FileAsync/...)

- - - - - - -
+ +
Description:
+
  • Telegraf Session middleware for storing sessions locally (Memory/FileSync/FileAsync/...)

+
Source:
@@ -132,33 +127,9 @@

telegraf-session-local

- - - - - - - - - - - - - - - - - - - - - - - - - - - + +

Telegraf Session middleware for storing sessions locally (Memory/FileSync/FileAsync/...)

+ @@ -206,7 +177,7 @@

Requires


diff --git a/docs/scripts/collapse.js b/docs/scripts/collapse.js index 327039f..4e63926 100644 --- a/docs/scripts/collapse.js +++ b/docs/scripts/collapse.js @@ -1,15 +1,34 @@ function hideAllButCurrent(){ //by default all submenut items are hidden //but we need to rehide them for search + document.querySelectorAll("nav > ul").forEach(function(parent) { + if (parent.className.indexOf("collapse_top") !== -1) { + parent.style.display = "none"; + } + }); document.querySelectorAll("nav > ul > li > ul li").forEach(function(parent) { parent.style.display = "none"; }); + document.querySelectorAll("nav > h3").forEach(function(section) { + if (section.className.indexOf("collapsed_header") !== -1) { + section.addEventListener("click", function(){ + if (section.nextSibling.style.display === "none") { + section.nextSibling.style.display = "block"; + } else { + section.nextSibling.style.display = "none"; + } + }); + } + }); //only current page (if it exists) should be opened var file = window.location.pathname.split("/").pop().replace(/\.html/, ''); document.querySelectorAll("nav > ul > li > a").forEach(function(parent) { var href = parent.attributes.href.value.replace(/\.html/, ''); if (file === href) { + if (parent.parentNode.parentNode.className.indexOf("collapse_top") !== -1) { + parent.parentNode.parentNode.style.display = "block"; + } parent.parentNode.querySelectorAll("ul li").forEach(function(elem) { elem.style.display = "block"; }); diff --git a/docs/scripts/commonNav.js b/docs/scripts/commonNav.js new file mode 100644 index 0000000..03e8202 --- /dev/null +++ b/docs/scripts/commonNav.js @@ -0,0 +1,28 @@ +if (typeof fetch === 'function') { + const init = () => { + if (typeof scrollToNavItem !== 'function') return false + scrollToNavItem() + // hideAllButCurrent not always loaded + if (typeof hideAllButCurrent === 'function') hideAllButCurrent() + return true + } + fetch('./nav.inc.html') + .then(response => response.ok ? response.text() : `${response.url} => ${response.status} ${response.statusText}`) + .then(body => { + document.querySelector('nav').innerHTML += body + // nav.js should be quicker to load than nav.inc.html, a fallback just in case + return init() + }) + .then(done => { + if (done) return + let i = 0 + ;(function waitUntilNavJs () { + if (init()) return + if (i++ < 100) return setTimeout(waitUntilNavJs, 300) + console.error(Error('nav.js not loaded after 30s waiting for it')) + })() + }) + .catch(error => console.error(error)) +} else { + console.error(Error('Browser too old to display commonNav (remove commonNav docdash option)')) +} diff --git a/docs/scripts/search.js b/docs/scripts/search.js index 546c82f..959cdee 100644 --- a/docs/scripts/search.js +++ b/docs/scripts/search.js @@ -33,6 +33,9 @@ document.getElementById("nav-search").addEventListener("keyup", function(event) document.querySelectorAll("nav > ul > li").forEach(function(elem) { elem.style.display = "block"; }); + document.querySelectorAll("nav > ul").forEach(function(elem) { + elem.style.display = "block"; + }); //hide all results document.querySelectorAll("nav > ul > li > ul li").forEach(function(elem) { elem.style.display = "none"; @@ -79,5 +82,18 @@ document.getElementById("nav-search").addEventListener("keyup", function(event) parent.style.display = "none"; } }); + document.querySelectorAll("nav > ul.collapse_top").forEach(function(parent) { + var countVisible = 0; + parent.querySelectorAll("li").forEach(function(elem) { + if (elem.style.display !== "none") { + countVisible++; + } + }); + + if (countVisible == 0) { + //has no child at all and does not contain text + parent.style.display = "none"; + } + }); } }); \ No newline at end of file diff --git a/docs/session.js.html b/docs/session.js.html index 63a6a9d..d2db8c1 100644 --- a/docs/session.js.html +++ b/docs/session.js.html @@ -20,6 +20,7 @@ + @@ -35,7 +36,9 @@ -

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

Global

+ +

Home

GitHub Repository ⧉

NPM Package ⧉

Modules

Classes

+
@@ -354,7 +357,7 @@

session.js


diff --git a/docs/styles/jsdoc.css b/docs/styles/jsdoc.css index eb45265..0fe6d3c 100644 --- a/docs/styles/jsdoc.css +++ b/docs/styles/jsdoc.css @@ -162,12 +162,19 @@ h6 { } -tt, code, kbd, samp { +tt, code, kbd, samp, pre { font-family: Consolas, Monaco, 'Andale Mono', monospace; background: #f4f4f4; +} + +tt, code, kbd, samp{ padding: 1px 5px; } +pre { + padding-bottom: 1em; +} + .class-description { font-size: 130%; line-height: 140%; @@ -242,6 +249,10 @@ nav h3 { color: #000; } +nav h3.collapsed_header { + cursor: pointer; +} + nav ul { font-family: 'Lucida Grande', 'Lucida Sans Unicode', arial, sans-serif; font-size: 100%; @@ -762,4 +773,4 @@ html[data-search-mode] .level-hide { font-weight: 300; font-style: normal; -} \ No newline at end of file +} diff --git a/docs/styles/prettify.css b/docs/styles/prettify.css index d9521ec..6f4d2ee 100644 --- a/docs/styles/prettify.css +++ b/docs/styles/prettify.css @@ -76,4 +76,5 @@ ol.linenums { margin-top: 0; margin-bottom: 0; + padding-bottom: 2px; } diff --git a/examples/extra.js b/examples/extra.js index 90087ca..83728dd 100644 --- a/examples/extra.js +++ b/examples/extra.js @@ -3,9 +3,6 @@ const LocalSession = require('../lib/session') // require('telegraf-session-loca const bot = new Telegraf(process.env.BOT_TOKEN) // Your Bot token here -// Name of session property object in Telegraf Context (default: 'session') -const property = 'data' - const localSession = new LocalSession({ // Database name/path, where sessions will be located (default: 'sessions.json') database: 'example_db.json', @@ -29,30 +26,28 @@ localSession.DB.then(DB => { // console.log(DB.get('sessions').getById('1:1').value()) }) -// Telegraf will use `telegraf-session-local` configured above middleware with overrided `property` value: `data`, instead of `session` -bot.use(localSession.middleware(property)) +// Telegraf will use `telegraf-session-local` configured above middleware +bot.use(localSession.middleware()) bot.on('text', (ctx, next) => { - ctx[property].counter = ctx[property].counter || 0 - ctx[property].counter++ - ctx.replyWithMarkdown(`Counter updated, new value: \`${ctx[property].counter}\``) + ctx.session.counter = ctx.session.counter || 0 + ctx.session.counter++ + ctx.replyWithMarkdownV2(`Counter updated, new value: \`${ctx.session.counter}\``) // Writing message to Array `messages` into database which already has sessions Array - ctx[property + 'DB'].get('messages').push([ctx.message]).write() - // `property`+'DB' is a name of property which contains lowdb instance, default = `sessionDB`, in current example = `dataDB` - // ctx.dataDB.get('messages').push([ctx.message]).write() + ctx.sessionDB.get('messages').push([ctx.message]).write() + // `property`+'DB' is a name of ctx property which contains lowdb instance, default = `sessionDB` return next() }) bot.command('/stats', (ctx) => { - let msg = `Using session object from [Telegraf Context](http://telegraf.js.org/context.html) (\`ctx\`), named \`${property}\`\n` - msg += `Database has \`${ctx[property].counter}\` messages from @${ctx.from.username || ctx.from.id}` - ctx.replyWithMarkdown(msg) + ctx.replyWithMarkdownV2(`Session has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`) }) + bot.command('/remove', (ctx) => { - ctx.replyWithMarkdown(`Removing session from database: \`${JSON.stringify(ctx[property])}\``) + ctx.replyWithMarkdownV2(`Removing session from lowdb database: \`${JSON.stringify(ctx.session)}\``) // Setting session to null, undefined or empty object/array will trigger removing it from database - ctx[property] = null + ctx.session = null }) bot.launch() diff --git a/examples/simple.js b/examples/simple.js index 120fa97..dd23a58 100644 --- a/examples/simple.js +++ b/examples/simple.js @@ -8,16 +8,16 @@ bot.use((new LocalSession({ database: 'example_db.json' })).middleware()) bot.on('text', (ctx, next) => { ctx.session.counter = ctx.session.counter || 0 ctx.session.counter++ - ctx.replyWithMarkdown(`Counter updated, new value: \`${ctx.session.counter}\``) + ctx.replyWithMarkdownV2(`Counter updated, new value: \`${ctx.session.counter}\``) return next() }) bot.command('/stats', (ctx) => { - ctx.replyWithMarkdown(`Database has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`) + ctx.replyWithMarkdownV2(`Database has \`${ctx.session.counter}\` messages from @${ctx.from.username || ctx.from.id}`) }) bot.command('/remove', (ctx) => { - ctx.replyWithMarkdown(`Removing session from database: \`${JSON.stringify(ctx.session)}\``) + ctx.replyWithMarkdownV2(`Removing session from database: \`${JSON.stringify(ctx.session)}\``) // Setting session to null, undefined or empty object/array will trigger removing it from database ctx.session = null })