Merge pull request #41 from laurynas-karvelis/master

Allow sending messages longer than 4096 chars
This commit is contained in:
Mahdi Dibaiee 2018-03-02 08:05:37 +00:00 committed by GitHub
commit ea5548beca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 46 additions and 8 deletions

View File

@ -35,10 +35,12 @@ export default class Base extends EventEmitter {
let messageId;
return new Promise((resolve, reject) => {
bot.api[this.method](this.properties).then(response => {
messageId = response.result.message_id;
this.emit('message:sent', response);
}).catch(reject);
this._apiSend(bot)
.then(response => {
messageId = response.result.message_id;
this.emit('message:sent', response);
})
.catch(reject);
if (this._keyboard.one_time_keyboard) {
this._keyboard.replyMarkup = '';
@ -46,6 +48,7 @@ export default class Base extends EventEmitter {
const chat = this.properties.chat_id;
let answers = 0;
bot.on('update', function listener(result) {
answers += result.length;
@ -53,8 +56,8 @@ export default class Base extends EventEmitter {
// if in a group, there will be a reply to this message
if (chat < 0) {
return message.chat.id === chat
&& message.reply_to_message
&& message.reply_to_message.message_id === messageId;
&& message.reply_to_message
&& message.reply_to_message.message_id === messageId;
}
return message && message.chat.id === chat;
@ -62,9 +65,7 @@ export default class Base extends EventEmitter {
if (update) {
resolve(update.message);
this.emit('message:answer', update.message);
bot.removeListener('update', listener);
}
@ -75,6 +76,10 @@ export default class Base extends EventEmitter {
});
}
_apiSend(bot) {
return bot.api[this.method](this.properties);
}
/**
* Returns properties of the object
* @return {object} properties of object

View File

@ -1,5 +1,18 @@
import Base from './Base';
const MSG_MAX_LENGTH = 4096;
function splitToChunks(str, size) {
const numChunks = Math.ceil(str.length / size);
const chunks = new Array(numChunks);
for (let i = 0, o = 0; i < numChunks; ++i, o += size) {
chunks[i] = str.substr(o, size);
}
return chunks;
}
/**
* Message class, used to send message to a chat
*/
@ -93,5 +106,25 @@ export default class Message extends Base {
return this;
}
// override Base.prototype._apiSend() method
_apiSend(bot) {
if (this.properties.text && this.properties.text.length > MSG_MAX_LENGTH) {
let promiseChain = Promise.resolve();
const textChunks = splitToChunks(this.properties.text, MSG_MAX_LENGTH);
textChunks.forEach(chunk => {
const properties = Object.assign({}, this.properties, { text: chunk });
// any unclosed tags, text modifiers will not send out, send as pure text
delete properties.parse_mode;
promiseChain = promiseChain.then(() => bot.api[this.method](properties));
});
return promiseChain;
}
return bot.api[this.method](this.properties);
}
// This class inherits Base's send method
}