Skip to content

Instantly share code, notes, and snippets.

@SitiSchu
Created November 12, 2017 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SitiSchu/67779a88a22dd45b86bd1ede6aae82bf to your computer and use it in GitHub Desktop.
Save SitiSchu/67779a88a22dd45b86bd1ede6aae82bf to your computer and use it in GitHub Desktop.
'use strict';
const getLongCodeBlocks = msg =>
(msg.entities || [])
.filter(entity => entity.type == 'pre')
.filter(({ offset, length }) => msg.text
.slice(offset, offset + length)
.split(/\n/g)
.length > 10
);
function *reversed(arr) {
for (let i = arr.length - 1; i >= 0; i--) {
yield arr[i];
}
}
const replace = (s, from, length, replacement) =>
s.slice(0, from) + replacement + s.slice(from + length);
const withoutCodeBlocks = ({ text, entities = [] }) => {
for (const { type, offset, length } of reversed(entities)) {
if (type === 'pre') {
text = replace(text, offset, length, '\n');
}
}
return text;
}
const createHandler = ({ replyToPm }) => ({ message, chat, reply }, next) => {
const { text } = message;
const replyOptions = { reply_to_message_id: message.message_id };
if (!['group', 'supergroup'].includes(chat.type)) {
if (!replyToPm) {
return next();
}
return reply(
"Hello! Put me in a group, and I'll " +
"point out when people are posting " +
"long or unformatted snippets of code " +
"and advise them how to do better.");
}
if (!text) {
return next();
}
const hasUnformattedCode = /^\t|^ {2}/m.test(withoutCodeBlocks(message));
const longCodeBlocks = getLongCodeBlocks(message);
if (longCodeBlocks.length) {
reply(
"It looks like you posted long piece of code, " +
"consider editing it out and putting it on hastebin.com " +
"and pasting link to it instead. " +
"Alternatively, send your code in a file.",
replyOptions);
}
else if (hasUnformattedCode) {
reply(
"Please format the code you posted, " +
"by wrapping it in triple backticks. -> `",
replyOptions);
}
return next();
};
// for embedding in another bot
module.exports = createHandler({ replyToPm: false });
// for running standalone via micro-bot
module.exports.botHandler = createHandler({ replyToPm: true });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment