Skip to content
Snippets Groups Projects
Verified Commit a4358d64 authored by vanutp's avatar vanutp
Browse files

- Теперь цитатится только если /q в начале

- можно юзать как команду с @ник_бота
- немного моего кодстайла и пофиксов укуркода ли
parent bf5d695a
Branches
No related tags found
No related merge requests found
module.exports = {
root: true,
'env': {
'es6': true,
'node': true,
},
'extends': 'eslint:recommended',
'globals': {
'Atomics': 'readonly',
'SharedArrayBuffer': 'readonly',
},
'parserOptions': {
ecmaVersion: 2020,
},
'rules': {
'comma-dangle': ['error', 'always-multiline'],
'quotes': ['error', 'single'],
},
}
{
"env": {
"es6": true,
"node": true
},
"extends": "standard",
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parserOptions": {
"ecmaVersion": 2018,
"sourceType": "module"
},
"rules": {}
}
bot.js 100644 → 100755
......@@ -5,12 +5,12 @@ const session = require('telegraf/session')
const rateLimit = require('telegraf-ratelimit')
const I18n = require('telegraf-i18n')
const {
db
db,
} = require('./database')
const {
stats,
onlyGroup,
onlyAdmin
onlyAdmin,
} = require('./middlewares')
const {
handleHelp,
......@@ -28,18 +28,18 @@ const {
handleSettingsRate,
handleLanguage,
handleFstik,
handleSettingsEmoji
handleSettingsEmoji,
} = require('./handlers')
const {
updateUser,
updateGroup
updateGroup,
} = require('./helpers')
const randomInteger = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min
const bot = new Telegraf(process.env.BOT_TOKEN, {
telegram: {webhookReply: false},
handlerTimeout: 1
handlerTimeout: 1,
})
bot.catch((error) => {
......@@ -68,27 +68,29 @@ bot.use(Composer.groupChat(Composer.command(rateLimit({
window: 1000,
limit: 1,
keyGenerator: (ctx) => ctx.chat.id,
onLimitExceeded: ({ deleteMessage }) => deleteMessage().catch(() => {})
onLimitExceeded: ({deleteMessage}) => deleteMessage().catch(() => {
}),
}))))
bot.use(Composer.mount('callback_query', rateLimit({
window: 1000,
limit: 1,
keyGenerator: (ctx) => ctx.from.id,
onLimitExceeded: ({ answerCbQuery }) => answerCbQuery('too fast', true)
onLimitExceeded: ({answerCbQuery}) => answerCbQuery('too fast', true),
})))
bot.use(rateLimit({
window: 1000,
limit: 1
limit: 1,
}))
bot.on(['channel_post', 'edited_channel_post'], () => {})
bot.on(['channel_post', 'edited_channel_post'], () => {
})
const i18n = new I18n({
directory: path.resolve(__dirname, 'locales'),
defaultLanguage: 'ru',
defaultLanguageOnMissing: true
defaultLanguageOnMissing: true,
})
bot.use(i18n.middleware())
......@@ -102,25 +104,33 @@ bot.use(Composer.groupChat(session({
}
return null
},
ttl: 60 * 5
ttl: 60 * 5,
})))
const updateGroupAndUser = async (ctx, next) => {
await updateUser(ctx)
await updateGroup(ctx)
await next(ctx)
await ctx.session.userInfo.save().catch(() => {})
await ctx.group.info.save().catch(() => {})
await ctx.session.userInfo.save().catch(() => {
})
await ctx.group.info.save().catch(() => {
})
}
bot.getMe().then(({username}) => {
const QUOTE_CMD_REGEX = new RegExp(String.raw`^(\.й|\/й|\/q)(@${username})?( .*|$)`)
bot.use(Composer.groupChat(Composer.hears(QUOTE_CMD_REGEX, updateGroupAndUser)))
bot.hears(QUOTE_CMD_REGEX, handleQuote)
})
bot.use(Composer.groupChat(Composer.command(updateGroupAndUser)))
bot.use(Composer.groupChat(Composer.hears(/(\.й|\/й|\/q)( .*|$)/, updateGroupAndUser)))
bot.action(() => true, Composer.groupChat(updateGroupAndUser))
bot.use(Composer.privateChat(async (ctx, next) => {
await updateUser(ctx)
await next(ctx)
await ctx.session.userInfo.save().catch(() => {})
await ctx.session.userInfo.save().catch(() => {
})
}))
bot.command('qtop', onlyGroup, handleTopQuote)
......@@ -130,20 +140,20 @@ bot.command('qrand', onlyGroup, rateLimit({
keyGenerator: (ctx) => {
return ctx.chat.id
},
onLimitExceeded: ({ deleteMessage }) => deleteMessage().catch(() => {})
onLimitExceeded: ({deleteMessage}) => deleteMessage().catch(() => {
}),
}), handleRandomQuote)
bot.hears(/(\.й|\/й|\/q)( .*|$)/, handleQuote)
bot.hears(/\/q_(.*)/, handleGetQuote)
bot.hears(/^\/qs(?:\s([^\s]+)|)/, handleFstik)
bot.hears(/^\/qs(?:\s([^\s]+)|)/, onlyGroup, onlyAdmin, handleSave)
bot.command('qd', onlyGroup, onlyAdmin, handleDelete)
bot.hears(/^\/qcolor(?:(?:\s(?:(#?))([^\s]+))?)/, onlyAdmin, handleColorQuote)
bot.hears(/^\/qcolor(?:\s(#?)([^\s]+))?/, onlyAdmin, handleColorQuote)
bot.hears(/^\/(hidden)/, onlyAdmin, handleSettingsHidden)
bot.hears(/^\/(gab) (\d+)/, onlyAdmin, handleGabHidden)
bot.hears(/^\/(qrate)/, onlyGroup, onlyAdmin, handleSettingsRate)
bot.hears(/^\/(qemoji) (\w+)/, onlyGroup, onlyAdmin, handleSettingsEmoji)
bot.action(/^(rate):(👍|👎)(:.+)?/, handleRate)
bot.action(/^(rate):([👍👎])(:.+)?/u, handleRate)
bot.on('inline_query', handleSearchQuote)
bot.on('new_chat_members', (ctx, next) => {
......@@ -164,7 +174,7 @@ bot.on('message', onlyGroup, rateLimit({
limit: 1,
keyGenerator: (ctx) => {
return ctx.chat.id
}
},
}), updateGroupAndUser, async (ctx, next) => {
const gab = ctx.group.info.settings.randomQuoteGab
......@@ -172,8 +182,8 @@ bot.on('message', onlyGroup, rateLimit({
const quoteCount = await ctx.db.Quote.count({
$and: [
{group: ctx.group.info._id},
{ 'rate.score': { $gt: 0 } }
]
{'rate.score': {$gt: 0}},
],
})
if (randomInteger(quoteCount, gab) === gab || quoteCount >= gab) await handleRandomQuote(ctx)
else await next()
......@@ -188,8 +198,8 @@ db.connection.once('open', async () => {
webhook: {
domain: process.env.BOT_DOMAIN,
hookPath: `/QuoteBot:${process.env.BOT_TOKEN}`,
port: process.env.WEBHOOK_PORT || 2200
}
port: process.env.WEBHOOK_PORT || 2200,
},
}).then(() => {
console.log('bot start webhook')
})
......
const Markup = require('telegraf/markup')
const {
tdlib
tdlib,
} = require('../helpers')
const got = require('got')
const {SUPPORTED_LIBRARIES} = require('../const')
......@@ -39,10 +39,10 @@ module.exports = async (ctx) => {
rate: false,
color: false,
scale: false,
emoji: null
emoji: null,
}
if (ctx.message && ctx.message.text && ctx.message.text.match(/(\.й|\/й|\/q)/)) {
if (ctx.message && ctx.message.text && ctx.message.text.match(/^(\.й|\/й|\/q)/)) {
const args = ctx.message.text.split(' ')
args.splice(0, 1)
......@@ -92,7 +92,7 @@ module.exports = async (ctx) => {
if (!quoteMessage) {
return ctx.replyWithHTML(ctx.i18n.t('quote.empty_forward'), {
reply_to_message_id: ctx.message.message_id
reply_to_message_id: ctx.message.message_id,
})
}
......@@ -136,18 +136,18 @@ module.exports = async (ctx) => {
let sarchForwardName
sarchForwardName = await ctx.db.User.find({
full_name: quoteMessage.forward_sender_name
full_name: quoteMessage.forward_sender_name,
})
if (sarchForwardName.length === 0) {
sarchForwardName = await ctx.db.User.find({
$expr: { $eq: [quoteMessage.forward_sender_name, { $concat: ['$first_name', ' ', '$last_name'] }] }
$expr: {$eq: [quoteMessage.forward_sender_name, {$concat: ['$first_name', ' ', '$last_name']}]},
})
}
if (sarchForwardName.length === 0) {
sarchForwardName = await ctx.db.User.find({
first_name: quoteMessage.forward_sender_name
first_name: quoteMessage.forward_sender_name,
})
}
......@@ -155,7 +155,7 @@ module.exports = async (ctx) => {
messageFrom = {
id: sarchForwardName[0].telegram_id,
name: quoteMessage.forward_sender_name,
username: sarchForwardName[0].username || null
username: sarchForwardName[0].username || null,
}
const getHiddenChat = await ctx.tg.getChat(sarchForwardName[0].telegram_id).catch(console.error)
......@@ -164,14 +164,14 @@ module.exports = async (ctx) => {
messageFrom = {
id: hashCode(quoteMessage.forward_sender_name),
name: quoteMessage.forward_sender_name,
username: 'HiddenSender'
username: 'HiddenSender',
}
}
} else {
messageFrom = {
id: hashCode(quoteMessage.forward_sender_name),
name: quoteMessage.forward_sender_name,
username: 'HiddenSender'
username: 'HiddenSender',
}
}
} else if (quoteMessage.forward_from_chat) {
......@@ -179,7 +179,7 @@ module.exports = async (ctx) => {
id: quoteMessage.forward_from_chat.id,
name: quoteMessage.forward_from_chat.title,
username: quoteMessage.forward_from_chat.username || null,
photo: quoteMessage.forward_from_chat.photo
photo: quoteMessage.forward_from_chat.photo,
}
} else if (quoteMessage.forward_from) {
messageFrom = quoteMessage.forward_from
......@@ -189,7 +189,7 @@ module.exports = async (ctx) => {
id: quoteMessage.chat.id,
name: quoteMessage.chat.title,
username: quoteMessage.chat.username || null,
photo: quoteMessage.chat.photo
photo: quoteMessage.chat.photo,
}
} else {
messageFrom = quoteMessage.from
......@@ -261,7 +261,7 @@ module.exports = async (ctx) => {
if (quoteMessages.length < 1) {
if (quoteImages.length === 0) {
return ctx.replyWithHTML(ctx.i18n.t('quote.empty_forward'), {
reply_to_message_id: ctx.message.message_id
reply_to_message_id: ctx.message.message_id,
})
}
}
......@@ -295,23 +295,23 @@ module.exports = async (ctx) => {
height,
scale: flag.scale || scale,
messages: quoteMessages,
emojiLibrary: emojiLibrary
}
emojiLibrary: emojiLibrary,
},
}).json().catch((error) => {
if (error.response && error.response.body) {
const errorMessage = JSON.parse(error.response.body).error.message
ctx.replyWithHTML(ctx.i18n.t('quote.api_error', {
error: errorMessage
error: errorMessage,
}), {
reply_to_message_id: ctx.message.message_id
reply_to_message_id: ctx.message.message_id,
})
} else {
console.error(error)
ctx.replyWithHTML(ctx.i18n.t('quote.api_error', {
error: 'quote_api_down'
error: 'quote_api_down',
}), {
reply_to_message_id: ctx.message.message_id
reply_to_message_id: ctx.message.message_id,
})
}
return false
......@@ -325,16 +325,16 @@ module.exports = async (ctx) => {
if (ctx.group && (ctx.group.info.settings.rate || flag.rate)) {
replyMarkup = Markup.inlineKeyboard([
Markup.callbackButton('👍', 'rate:👍'),
Markup.callbackButton('👎', 'rate:👎')
Markup.callbackButton('👎', 'rate:👎'),
])
}
const sendResult = await ctx.replyWithDocument({
source: image,
filename: 'quote.webp'
filename: 'quote.webp',
}, {
reply_to_message_id: ctx.message.message_id,
reply_markup: replyMarkup
reply_markup: replyMarkup,
})
if (ctx.group && (ctx.group.info.settings.rate || flag.rate)) {
......@@ -348,14 +348,14 @@ module.exports = async (ctx) => {
votes: [
{
name: '👍',
vote: []
vote: [],
},
{
name: '👎',
vote: []
}
vote: [],
},
],
score: 0
score: 0,
}
await quoteDb.save()
......@@ -363,16 +363,16 @@ module.exports = async (ctx) => {
} else if (generate.result.type === 'image') {
await ctx.replyWithPhoto({
source: image,
filename: 'quote.png'
filename: 'quote.png',
}, {
reply_to_message_id: ctx.message.message_id
reply_to_message_id: ctx.message.message_id,
})
} else {
await ctx.replyWithDocument({
source: image,
filename: 'quote.png'
filename: 'quote.png',
}, {
reply_to_message_id: ctx.message.message_id
reply_to_message_id: ctx.message.message_id,
})
}
}
......
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment