diff --git a/handlers/middlewares/syncStatus.js b/handlers/middlewares/syncStatus.js new file mode 100644 index 0000000..d594a0b --- /dev/null +++ b/handlers/middlewares/syncStatus.js @@ -0,0 +1,42 @@ +'use strict'; + +const { getUser } = require('../../stores/user'); + +const syncStatusHandler = (ctx, next) => { + const { message } = ctx; + const { new_chat_members } = message; + + new_chat_members.forEach(async newMember => { + if (newMember.is_bot) { + return null; + } + + const dbUser = await getUser({ id: newMember.id }); + // this handler runs after messages/addUser + // so, it should always be able to obtain the user from db + console.assert(dbUser); + + switch (dbUser.status) { + case 'admin': + return ctx.telegram.promoteChatMember(ctx.chat.id, dbUser.id, { + can_change_info: false, + can_delete_messages: true, + can_invite_users: true, + can_pin_messages: true, + can_promote_members: true, + can_restrict_members: true, + }); + case 'banned': + return ctx.telegram.kickChatMember(ctx.chat.id, dbUser.id); + case 'member': + // do nothing + return null; + default: + throw new Error(`Unexpected member status: ${dbUser.status}`); + } + }); + + return next(); +}; + +module.exports = syncStatusHandler; diff --git a/index.js b/index.js index 96b4bcf..2744c25 100644 --- a/index.js +++ b/index.js @@ -36,6 +36,7 @@ const command = './handlers/commands'; const leaveUnmanagedHandler = require(`${middleware}/leaveUnmanaged`); const removeCommandsHandler = require(`${middleware}/removeCommands`); const kickBannedHandler = require(`${middleware}/kickBanned`); +const syncStatusHandler = require(`${middleware}/syncStatus`); const antibotHandler = require(`${middleware}/antibot`); const addedToGroupHandler = require(`${middleware}/addedToGroup`); @@ -82,6 +83,7 @@ bot.on('message', addCustomCmdHandler, runCustomCmdHandler ); +bot.on('new_chat_members', syncStatusHandler); bot.on('new_chat_members', antibotHandler); bot.on([ 'new_chat_members', 'left_chat_member' ], deleteAfter(delTimeout)); bot.command('admin', adminHandler);