Beispiel #1
0
def start(bot: Bot, update: Update, session):
    add_user(update.message.from_user, session)
    if update.message.chat.type == 'private':
        send_async(bot,
                   chat_id=update.message.chat.id,
                   text=MSG_START_WELCOME,
                   parse_mode=ParseMode.HTML)
Beispiel #2
0
def welcome(bot: Bot, update: Update, session):
    newbie(bot, update)
    global last_welcome
    print('welcome')
    if update.message.chat.type in ['group', 'supergroup']:
        group = update_group(update.message.chat, session)
        for new_chat_member in update.message.new_chat_members:
            user = add_user(new_chat_member, session)
            print(user)
            administrator = session.query(Admin).filter_by(
                user_id=user.id).all()
            allow_anywhere = False
            for adm in administrator:
                if adm.admin_type == AdminType.FULL.value:
                    allow_anywhere = True
                    break
            print(update.message.chat.id)
            print(VENTURE_CHAT_ID == update.message.chat.id)
            if str(update.message.chat.id) == VENTURE_CHAT_ID:
                print('equal')
                if group.welcome_enabled:
                    print('enable_welcome')
                    welcome_msg = session.query(WelcomeMsg).filter_by(
                        chat_id=group.id).first()
                    send_async(bot,
                               chat_id=update.message.chat.id,
                               text=fill_template(welcome_msg.message, user))
            elif user is None and not allow_anywhere and user.id != bot.id:
                send_async(bot, chat_id=update.message.chat.id)
                bot.restrictChatMember(update.message.chat.id,
                                       new_chat_member.id)

            else:
                if group.welcome_enabled:
                    welcome_msg = session.query(WelcomeMsg).filter_by(
                        chat_id=group.id).first()
                    if welcome_msg is None:
                        welcome_msg = WelcomeMsg(chat_id=group.id,
                                                 message=MSG_WELCOME_DEFAULT)
                        session.add(welcome_msg)

                    welcomed = session.query(Wellcomed).filter_by(
                        user_id=new_chat_member.id,
                        chat_id=update.message.chat.id).first()
                    if welcomed is None:
                        if time() - last_welcome > 30:
                            send_async(bot,
                                       chat_id=update.message.chat.id,
                                       text=fill_template(
                                           welcome_msg.message, user))
                            last_welcome = time()
                        welcomed = Wellcomed(user_id=new_chat_member.id,
                                             chat_id=update.message.chat.id)
                        session.add(welcomed)
                    session.commit()
Beispiel #3
0
def web_auth(bot: Bot, update: Update, session):
    user = add_user(update.message.from_user, session)
    auth = session.query(Auth).filter_by(user_id=user.id).first()
    if auth is None:
        auth = Auth()
        auth.id = uuid.uuid4().hex
        auth.user_id = user.id
        session.add(auth)
        session.commit()
    link = WEB_LINK.format(auth.id)
    send_async(bot,
               chat_id=update.message.chat.id,
               text=MSG_PERSONAL_SITE_LINK.format(link),
               parse_mode=ParseMode.HTML,
               disable_web_page_preview=True)
Beispiel #4
0
def welcome(bot: Bot, update: Update):
    newbie(bot, update)
    global last_welcome
    if update.message.chat.type in ['group', 'supergroup']:
        group = update_group(update.message.chat)
        for new_chat_member in update.message.new_chat_members:
            session = Session()
            user = add_user(new_chat_member)
            administrator = session.query(Admin).filter_by(
                user_id=user.id).all()
            allow_anywhere = False
            for adm in administrator:
                if adm.admin_type == AdminType.FULL.value:
                    allow_anywhere = True
                    break
            if len(group.squad) == 1 and group.squad[0].thorns_enabled and user.id != 386494081 and \
                    (user.member or user.member not in group.squad[0].members) and not allow_anywhere:
                send_async(bot,
                           chat_id=update.message.chat.id,
                           text=MSG_THORNS.format(str(user)))
                bot.kickChatMember(update.message.chat.id, new_chat_member.id)
                bot.unbanChatMember(update.message.chat.id, new_chat_member.id)
            else:
                if group.welcome_enabled:
                    welcome_msg = session.query(WelcomeMsg).filter_by(
                        chat_id=group.id).first()
                    if welcome_msg is None:
                        welcome_msg = WelcomeMsg(chat_id=group.id,
                                                 message=MSG_WELCOME_DEFAULT)
                        session.add(welcome_msg)

                    welcomed = session.query(Wellcomed).filter_by(
                        user_id=new_chat_member.id,
                        chat_id=update.message.chat.id).first()
                    if welcomed is None:
                        if time() - last_welcome > 30:
                            send_async(bot,
                                       chat_id=update.message.chat.id,
                                       text=fill_template(
                                           welcome_msg.message, user))
                            last_welcome = time()
                        welcomed = Wellcomed(user_id=new_chat_member.id,
                                             chat_id=update.message.chat.id)
                        session.add(welcomed)
                    session.commit()
Beispiel #5
0
def manage_all(bot: Bot, update: Update, session, chat_data, job_queue):
    add_user(update.message.from_user, session)
    if update.message.chat.type in ['group', 'supergroup', 'channel']:
        squad = session.query(Squad).filter_by(
            chat_id=update.message.chat.id).first()
        admin = session.query(Admin).filter(
            Admin.user_id == update.message.from_user.id
            and Admin.admin_group in [update.message.chat.id, 0]).first()

        if squad is not None and admin is None and battle_time():
            bot.delete_message(update.message.chat.id,
                               update.message.message_id)

        if not update.message.text:
            return

        text = update.message.text.lower()

        if text.startswith(CC_SET_WELCOME):
            set_welcome(bot, update)
        elif text == CC_HELP:
            help_msg(bot, update)
        elif text == CC_SQUAD:
            call_squad(bot, update)
        elif text == CC_SHOW_WELCOME:
            show_welcome(bot, update)
        elif text == CC_TURN_ON_WELCOME:
            enable_welcome(bot, update)
        elif text == CC_TURN_OFF_WELCOME:
            disable_welcome(bot, update)
        elif text.startswith(CC_SET_TRIGGER):
            set_trigger(bot, update)
        elif text.startswith(CC_UNSET_TRIGGER):
            del_trigger(bot, update)
        elif text == CC_TRIGGER_LIST:
            list_triggers(bot, update)
        elif text == CC_ADMIN_LIST:
            list_admins(bot, update)
        elif text == CC_PING:
            ping(bot, update)
        elif text == CC_DAY_STATISTICS:
            day_activity(bot, update)
        elif text == CC_WEEK_STATISTICS:
            week_activity(bot, update)
        elif text == CC_BATTLE_STATISTICS:
            battle_activity(bot, update)
        elif text == CC_ALLOW_TRIGGER_ALL:
            enable_trigger_all(bot, update)
        elif text == CC_DISALLOW_TRIGGER_ALL:
            disable_trigger_all(bot, update)
        elif text in CC_ADMINS:
            admins_for_users(bot, update)
        elif text == CC_ALLOW_PIN_ALL:
            pin_all(bot, update)
        elif text == CC_DISALLOW_PIN_ALL:
            not_pin_all(bot, update)
        elif text in CC_BOSS_1:
            boss_leader(bot, update)
        elif text in CC_BOSS_2:
            boss_zhalo(bot, update)
        elif text in CC_BOSS_3:
            boss_monoeye(bot, update)
        elif text in CC_BOSS_4:
            boss_hydra(bot, update)
        elif text == CC_OPEN_HIRING:
            open_hiring(bot, update)
        elif text == CC_CLOSE_HIRING:
            close_hiring(bot, update)
        elif update.message.reply_to_message is not None:
            if text == CC_PIN:
                pin(bot, update)
            elif text == CC_SILENT_PIN:
                silent_pin(bot, update)
            elif text == CC_DELETE:
                delete_msg(bot, update)
            elif text == CC_KICK:
                delete_user(bot, update)
            else:
                trigger_show(bot, update)
        elif re.search(REPORT, update.message.text):
            if update.message.forward_from.id == CWBOT_ID:
                report_received(bot, update)
        else:
            trigger_show(bot, update)

    elif update.message.chat.type == 'private':
        admin = session.query(Admin).filter_by(
            user_id=update.message.from_user.id).all()
        is_admin = False
        for _ in admin:
            is_admin = True
            break

        if 'order_wait' in chat_data and chat_data['order_wait']:
            order(bot, update, chat_data)

        elif update.message.text:
            text = update.message.text.lower()

            if text == ADMIN_COMMAND_STATUS.lower():
                send_status(bot, update)
            elif text == USER_COMMAND_BACK.lower():
                user_panel(bot, update)
            elif text == USER_COMMAND_SQUAD_REQUEST.lower():
                squad_request(bot, update)
            elif text == ADMIN_COMMAND_RECRUIT.lower():
                list_squad_requests(bot, update)
            elif text == ADMIN_COMMAND_ORDER.lower():
                orders(bot, update, chat_data)
            elif text == ADMIN_COMMAND_SQUAD_LIST.lower():
                squad_list(bot, update)
            elif text == ADMIN_COMMAND_GROUPS.lower():
                group_list(bot, update)
            elif text == ADMIN_COMMAND_REPORTS.lower():
                battle_reports_show(bot, update)
            elif text == ADMIN_COMMAND_FIRE_UP.lower():
                remove_from_squad(bot, update)
            elif text == USER_COMMAND_ME.lower():
                char_show(bot, update)
            elif text == USER_COMMAND_TOP.lower():
                top_about(bot, update)
            elif text == TOP_COMMAND_ATTACK.lower():
                attack_top(bot, update)
            elif text == TOP_COMMAND_DEFENCE.lower():
                def_top(bot, update)
            elif text == TOP_COMMAND_EXP.lower():
                exp_top(bot, update)
            elif text == TOP_COMMAND_BUILD.lower():
                week_build_top(bot, update)
            elif text == TOP_COMMAND_BATTLES.lower():
                week_battle_top(bot, update)
            elif text == USER_COMMAND_BUILD.lower():
                send_async(bot,
                           chat_id=update.message.chat.id,
                           text=MSG_IN_DEV,
                           parse_mode=ParseMode.HTML)
            elif text == USER_COMMAND_STATISTICS.lower():
                statistic_about(bot, update)
            elif text == STATISTICS_COMMAND_EXP.lower():
                exp_statistic(bot, update)
            elif text == USER_COMMAND_SQUAD.lower():
                squad_about(bot, update)
            elif text == USER_COMMAND_SQUAD_LEAVE.lower():
                leave_squad_request(bot, update)
            elif text == USER_COMMAND_CONTACTS.lower():
                web_auth(bot, update)
            elif text == ADMIN_COMMAND_ADMINPANEL.lower():
                admin_panel(bot, update)
            elif 'wait_group_name' in chat_data and chat_data[
                    'wait_group_name']:
                add_group(bot, update, chat_data)

            elif update.message.forward_from:
                from_id = update.message.forward_from.id

                if from_id == CWBOT_ID:
                    if text.startswith(STOCK):
                        stock_compare(bot, update, chat_data)
                    elif re.search(PROFILE, update.message.text) or re.search(
                            HERO, update.message.text):
                        char_update(bot, update)
                    elif re.search(REPORT, update.message.text):
                        report_received(bot, update)
                    elif re.search(BUILD_REPORT, update.message.text):
                        build_report_received(bot, update)
                    elif re.search(REPAIR_REPORT, update.message.text):
                        repair_report_received(bot, update)
                elif from_id == TRADEBOT_ID:
                    if TRADE_BOT in text:
                        trade_compare(bot, update, chat_data)
            elif not is_admin:
                user_panel(bot, update)
            else:
                order(bot, update, chat_data)
        elif not is_admin:
            user_panel(bot, update)
        else:
            order(bot, update, chat_data)
Beispiel #6
0
def callback_query(bot: Bot, update: Update, session, chat_data: dict,
                   job_queue: JobQueue):
    update_group(update.callback_query.message.chat, session)
    user = add_user(update.effective_user, session)
    data = json.loads(update.callback_query.data)
    if data['t'] == QueryType.GroupList.value:
        msg = MSG_GROUP_STATUS_CHOOSE_CHAT
        squads = session.query(Squad).all()
        inline_keys = []
        for squad in squads:
            inline_keys.append(
                InlineKeyboardButton(squad.squad_name,
                                     callback_data=json.dumps({
                                         't':
                                         QueryType.GroupInfo.value,
                                         'id':
                                         squad.chat_id
                                     })))
        inline_markup = InlineKeyboardMarkup([[key] for key in inline_keys])
        bot.editMessageText(msg,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=inline_markup)
    elif data['t'] == QueryType.GroupInfo.value:
        msg, inline_markup = generate_group_info(data['id'], session)
        bot.editMessageText(msg,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=inline_markup)
    elif data['t'] == QueryType.DelAdm.value:
        admin_user = session.query(User).filter_by(id=data['uid']).first()
        if admin_user:
            del_adm(bot, data['gid'], admin_user, session)
        msg, inline_markup = generate_group_info(data['gid'], session)
        bot.editMessageText(msg,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=inline_markup)
    elif data['t'] == QueryType.Order.value:
        order_text = chat_data['order']
        order_type = chat_data['order_type']
        order_pin = chat_data['pin'] if 'pin' in chat_data else True
        order_btn = chat_data['btn'] if 'btn' in chat_data else True
        if not data['g']:
            if order_btn:
                order = Order()
                order.text = order_text
                order.chat_id = data['id']
                order.date = datetime.now()
                msg = send_async(bot,
                                 chat_id=order.chat_id,
                                 text=MSG_ORDER_CLEARED_BY_HEADER +
                                 MSG_EMPTY).result()
                if msg:
                    order.confirmed_msg = msg.message_id
                else:
                    order.confirmed_msg = 0
                session.add(order)
                session.commit()
                markup = generate_ok_markup(order.id, 0)
                msg = send_order(bot, order.text, order_type, order.chat_id,
                                 markup).result().result()
            else:
                msg = send_order(bot, order_text, order_type, data['id'],
                                 None).result().result()
            if order_pin and msg:
                try:
                    bot.request.post(
                        bot.base_url + '/pinChatMessage', {
                            'chat_id': data['id'],
                            'message_id': msg.message_id,
                            'disable_notification': False
                        })
                except TelegramError as err:
                    bot.logger.error(err.message)
        else:
            group = session.query(OrderGroup).filter_by(id=data['id']).first()
            for item in group.items:
                if order_btn:
                    order = Order()
                    order.text = order_text
                    order.chat_id = item.chat_id
                    order.date = datetime.now()
                    msg = send_async(bot,
                                     chat_id=order.chat_id,
                                     text=MSG_ORDER_CLEARED_BY_HEADER +
                                     MSG_EMPTY).result()
                    if msg:
                        order.confirmed_msg = msg.message_id
                    else:
                        order.confirmed_msg = 0
                    session.add(order)
                    session.commit()
                    markup = generate_ok_markup(order.id, 0)
                    msg = send_order(bot, order.text, order_type,
                                     order.chat_id, markup).result().result()
                else:
                    msg = send_order(bot, order_text, order_type, item.chat_id,
                                     None).result().result()
                if order_pin and msg:
                    try:
                        bot.request.post(
                            bot.base_url + '/pinChatMessage', {
                                'chat_id': item.chat_id,
                                'message_id': msg.message_id,
                                'disable_notification': False
                            })
                    except TelegramError as err:
                        bot.logger.error(err.message)
        update.callback_query.answer(text=MSG_ORDER_SENT)
    elif data['t'] == QueryType.OrderOk.value:
        order = session.query(Order).filter_by(id=data['id']).first()
        if order is not None:
            squad = session.query(Squad).filter_by(
                chat_id=order.chat_id).first()
            if squad is not None:
                squad_member = session.query(SquadMember).filter_by(
                    squad_id=squad.chat_id,
                    user_id=update.callback_query.from_user.id,
                    approved=True).first()
                if squad_member is not None:
                    order_ok = session.query(OrderCleared).filter_by(
                        order_id=data['id'],
                        user_id=squad_member.user_id).first()
                    if order_ok is None and datetime.now(
                    ) - order.date < timedelta(minutes=10):
                        order_ok = OrderCleared()
                        order_ok.order_id = data['id']
                        order_ok.user_id = update.callback_query.from_user.id
                        session.add(order_ok)
                        session.commit()
                        if order.confirmed_msg != 0:
                            if order.id not in order_updated or \
                                    datetime.now() - order_updated[order.id] > timedelta(seconds=4):
                                order_updated[order.id] = datetime.now()
                                job_queue.run_once(update_confirmed, 5, order)
                        update.callback_query.answer(text=MSG_ORDER_CLEARED)
                    else:
                        update.callback_query.answer(
                            text=MSG_ORDER_CLEARED_ERROR)
                else:
                    update.callback_query.answer(text=MSG_ORDER_CLEARED_ERROR)
            else:
                order_ok = session.query(OrderCleared).filter_by(
                    order_id=data['id'],
                    user_id=update.callback_query.from_user.id).first()
                if order_ok is None and datetime.now(
                ) - order.date < timedelta(minutes=10):
                    order_ok = OrderCleared()
                    order_ok.order_id = data['id']
                    order_ok.user_id = update.callback_query.from_user.id
                    session.add(order_ok)
                    session.commit()
                    if order.confirmed_msg != 0:
                        if order.id not in order_updated or \
                                datetime.now() - order_updated[order.id] > timedelta(seconds=4):
                            order_updated[order.id] = datetime.now()
                            job_queue.run_once(update_confirmed, 5, order)
                    update.callback_query.answer(text=MSG_ORDER_CLEARED)
                else:
                    update.callback_query.answer(text=MSG_ORDER_CLEARED_ERROR)
    elif data['t'] == QueryType.Orders.value:
        chat_data['order_wait'] = False
        if 'txt' in data and len(data['txt']):
            if data['txt'] == Icons.LES.value:
                chat_data['order'] = Castle.LES.value
            elif data['txt'] == Icons.GORY.value:
                chat_data['order'] = Castle.GORY.value
            elif data['txt'] == Icons.SEA.value:
                chat_data['order'] = Castle.SEA.value
            else:
                chat_data['order'] = data['txt']
        markup = generate_order_chats_markup(
            session, chat_data['pin'] if 'pin' in chat_data else True,
            chat_data['btn'] if 'btn' in chat_data else True)
        bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.OrderGroup.value:
        chat_data['order_wait'] = False
        if 'txt' in data and len(data['txt']):
            chat_data['order_type'] = MessageType.TEXT
            if data['txt'] == Icons.LES.value:
                chat_data['order'] = Castle.LES.value
            elif data['txt'] == Icons.GORY.value:
                chat_data['order'] = Castle.GORY.value
            elif data['txt'] == Icons.SEA.value:
                chat_data['order'] = Castle.SEA.value
            else:
                chat_data['order'] = data['txt']
        admin_user = session.query(Admin).filter(
            Admin.user_id == update.callback_query.from_user.id).all()
        markup = generate_order_groups_markup(
            session, admin_user,
            chat_data['pin'] if 'pin' in chat_data else True,
            chat_data['btn'] if 'btn' in chat_data else True)
        bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.OrderGroupManage.value:
        group = session.query(OrderGroup).filter_by(id=data['id']).first()
        markup = generate_group_manage(data['id'], session)
        bot.editMessageText(MSG_ORDER_GROUP_CONFIG_HEADER.format(group.name),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.OrderGroupTriggerChat.value:
        group = session.query(OrderGroup).filter_by(id=data['id']).first()
        deleted = False
        for item in group.items:
            if item.chat_id == data['c']:
                session.delete(item)
                session.commit()
                deleted = True
        if not deleted:
            item = OrderGroupItem()
            item.group_id = group.id
            item.chat_id = data['c']
            session.add(item)
            session.commit()
        markup = generate_group_manage(data['id'], session)
        bot.editMessageText(MSG_ORDER_GROUP_CONFIG_HEADER.format(group.name),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.OrderGroupAdd.value:
        chat_data['wait_group_name'] = True
        send_async(bot,
                   chat_id=update.callback_query.message.chat.id,
                   text=MSG_ORDER_GROUP_NEW)
    elif data['t'] == QueryType.OrderGroupDelete.value:
        group = session.query(OrderGroup).filter_by(id=data['id']).first()
        session.delete(group)
        session.commit()
        bot.editMessageText(MSG_ORDER_GROUP_LIST,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_groups_manage(session))
    elif data['t'] == QueryType.OrderGroupList.value:
        bot.editMessageText(MSG_ORDER_GROUP_LIST,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_groups_manage(session))
    elif data['t'] == QueryType.ShowEquip.value:
        user = session.query(User).filter_by(id=data['id']).first()
        update.callback_query.answer(text=MSG_CLEARED)
        back = data['b'] if 'b' in data else False
        bot.editMessageText('{}\n{} {}'.format(user.equip.equip,
                                               MSG_LAST_UPDATE,
                                               user.equip.date),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_profile_buttons(user, back))
    elif data['t'] == QueryType.ShowStock.value:
        user = session.query(User).filter_by(id=data['id']).first()
        update.callback_query.answer(text=MSG_CLEARED)
        back = data['b'] if 'b' in data else False
        bot.editMessageText('{}\n{} {}'.format(
            user.stock.stock, MSG_LAST_UPDATE,
            user.stock.date.strftime("%Y-%m-%d %H:%M:%S")),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_profile_buttons(user, back))
    elif data['t'] == QueryType.ShowHero.value:
        user = session.query(User).filter_by(id=data['id']).first()
        update.callback_query.answer(text=MSG_CLEARED)
        back = data['b'] if 'b' in data else False
        bot.editMessageText(fill_char_template(MSG_PROFILE_SHOW_FORMAT, user,
                                               user.character),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_profile_buttons(user, back))
    elif data['t'] == QueryType.MemberList.value:
        squad = session.query(Squad).filter_by(chat_id=data['id']).first()
        markup = generate_squad_members(squad.members, session)
        bot.editMessageText(squad.squad_name,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.LeaveSquad.value:
        member = session.query(SquadMember).filter_by(
            user_id=data['id']).first()
        leave_squad(bot, user, member, update.effective_message, session)
    elif data['t'] == QueryType.RequestSquad.value:
        member = session.query(SquadMember).filter_by(
            user_id=update.callback_query.from_user.id).first()
        if member is None:
            member = SquadMember()
            member.user_id = update.callback_query.from_user.id
            member.squad_id = data['id']
            session.add(member)
            session.commit()
            admins = session.query(Admin).filter_by(
                admin_group=data['id']).all()
            usernames = [
                '@' + session.query(User).filter_by(
                    id=admin.user_id).first().username for admin in admins
            ]
            bot.editMessageText(MSG_SQUAD_REQUESTED.format(
                member.squad.squad_name, ', '.join(usernames)),
                                update.callback_query.message.chat.id,
                                update.callback_query.message.message_id,
                                parse_mode=ParseMode.HTML)
            admins = session.query(Admin).filter_by(
                admin_group=member.squad.chat_id).all()
            for adm in admins:
                send_async(bot,
                           chat_id=adm.user_id,
                           text=MSG_SQUAD_REQUEST_NEW)
        else:
            markup = generate_leave_squad(user.id)
            bot.editMessageText(MSG_SQUAD_REQUEST_EXISTS,
                                update.callback_query.message.chat.id,
                                update.callback_query.message.message_id,
                                reply_markup=markup)
    elif data['t'] == QueryType.RequestSquadAccept.value:
        member = session.query(SquadMember).filter_by(user_id=data['id'],
                                                      approved=False).first()
        if member:
            member.approved = True
            session.add(member)
            session.commit()
            bot.editMessageText(
                MSG_SQUAD_REQUEST_ACCEPTED.format('@' + member.user.username),
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id)
            admin = session.query(Admin).filter_by(
                user_id=member.user_id).all()
            is_admin = False
            for _ in admin:
                is_admin = True
                break
            send_async(bot,
                       chat_id=member.user_id,
                       text=MSG_SQUAD_REQUEST_ACCEPTED_ANSWER,
                       reply_markup=generate_user_markup(is_admin))
            send_async(
                bot,
                chat_id=member.squad_id,
                text=MSG_SQUAD_REQUEST_ACCEPTED.format('@' +
                                                       member.user.username))
    elif data['t'] == QueryType.RequestSquadDecline.value:
        member = session.query(SquadMember).filter_by(user_id=data['id'],
                                                      approved=False).first()
        if member:
            bot.editMessageText(
                MSG_SQUAD_REQUEST_DECLINED.format('@' + member.user.username),
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id)
            session.delete(member)
            session.commit()
            send_async(bot,
                       chat_id=member.user_id,
                       text=MSG_SQUAD_REQUEST_DECLINED_ANSWER)
    elif data['t'] == QueryType.InviteSquadAccept.value:
        if update.callback_query.from_user.id != data['id']:
            update.callback_query.answer(text=MSG_GO_AWAY)
            return
        member = session.query(SquadMember).filter_by(
            user_id=data['id']).first()
        if member is None:
            member = SquadMember()
            member.user_id = user.id
            member.squad_id = update.callback_query.message.chat.id
            member.approved = True
            session.add(member)
            session.commit()
            bot.editMessageText(
                MSG_SQUAD_ADD_ACCEPTED.format('@' + user.username),
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id)
    elif data['t'] == QueryType.InviteSquadDecline.value:
        if update.callback_query.from_user.id != data['id']:
            update.callback_query.answer(text=MSG_GO_AWAY)
            return
        user = session.query(User).filter_by(id=data['id']).first()
        bot.editMessageText(
            MSG_SQUAD_REQUEST_DECLINED.format('@' + user.username),
            update.callback_query.message.chat.id,
            update.callback_query.message.message_id)
    elif data['t'] == QueryType.TriggerOrderPin.value:
        if 'pin' in chat_data:
            chat_data['pin'] = not chat_data['pin']
        else:
            chat_data['pin'] = False
        if data['g']:
            admin_user = session.query(Admin).filter(
                Admin.user_id == update.callback_query.from_user.id).all()
            markup = generate_order_groups_markup(
                session, admin_user,
                chat_data['pin'] if 'pin' in chat_data else True,
                chat_data['btn'] if 'btn' in chat_data else True)
            bot.editMessageText(MSG_ORDER_SEND_HEADER.format(
                chat_data['order']),
                                update.callback_query.message.chat.id,
                                update.callback_query.message.message_id,
                                reply_markup=markup)
        else:
            markup = generate_order_chats_markup(
                session, chat_data['pin'] if 'pin' in chat_data else True,
                chat_data['btn'] if 'btn' in chat_data else True)
            bot.editMessageText(MSG_ORDER_SEND_HEADER.format(
                chat_data['order']),
                                update.callback_query.message.chat.id,
                                update.callback_query.message.message_id,
                                reply_markup=markup)
    elif data['t'] == QueryType.TriggerOrderButton.value:
        if 'btn' in chat_data:
            chat_data['btn'] = not chat_data['btn']
        else:
            chat_data['btn'] = False
        if data['g']:
            admin_user = session.query(Admin).filter(
                Admin.user_id == update.callback_query.from_user.id).all()
            markup = generate_order_groups_markup(
                session, admin_user,
                chat_data['pin'] if 'pin' in chat_data else True,
                chat_data['btn'] if 'btn' in chat_data else True)
            bot.editMessageText(MSG_ORDER_SEND_HEADER.format(
                chat_data['order']),
                                update.callback_query.message.chat.id,
                                update.callback_query.message.message_id,
                                reply_markup=markup)
        else:
            markup = generate_order_chats_markup(
                session, chat_data['pin'] if 'pin' in chat_data else True,
                chat_data['btn'] if 'btn' in chat_data else True)
            bot.editMessageText(MSG_ORDER_SEND_HEADER.format(
                chat_data['order']),
                                update.callback_query.message.chat.id,
                                update.callback_query.message.message_id,
                                reply_markup=markup)
    elif data['t'] == QueryType.SquadList.value:
        admin = session.query(Admin).filter_by(
            user_id=update.callback_query.from_user.id).all()
        global_adm = False
        for adm in admin:
            if adm.admin_type <= AdminType.FULL.value:
                global_adm = True
                break
        if global_adm:
            squads = session.query(Squad).all()
        else:
            group_ids = []
            for adm in admin:
                group_ids.append(adm.admin_group)
            squads = session.query(Squad).filter(
                Squad.chat_id in group_ids).all()
        markup = generate_squad_list(squads, session)
        bot.editMessageText(MSG_SQUAD_LIST,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.GroupDelete.value:
        squad = session.query(Squad).filter_by(chat_id=data['gid']).first()
        if squad is not None:
            for member in squad.members:
                session.delete(member)
            session.delete(squad)
            session.commit()
            send_async(bot, chat_id=data['gid'], text=MSG_SQUAD_DELETE)
        msg = MSG_GROUP_STATUS_CHOOSE_CHAT
        squads = session.query(Squad).all()
        inline_keys = []
        for squad in squads:
            inline_keys.append(
                InlineKeyboardButton(squad.squad_name,
                                     callback_data=json.dumps({
                                         't':
                                         QueryType.GroupInfo.value,
                                         'id':
                                         squad.chat_id
                                     })))
        inline_markup = InlineKeyboardMarkup([[key] for key in inline_keys])
        bot.editMessageText(msg,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=inline_markup)
    elif data['t'] == QueryType.OtherReport.value:
        squad = session.query(Squad).filter(Squad.chat_id == data['c']).first()
        time_from = datetime.fromtimestamp(data['ts'])
        time_to = time_from + timedelta(hours=4)
        reports = session.query(User, Report) \
            .join(SquadMember) \
            .outerjoin(Report, and_(User.id == Report.user_id, Report.date > time_from, Report.date < time_to)) \
            .filter(SquadMember.squad_id == data['c']).order_by(Report.date.desc()).all()
        text = ''
        full_def = 0
        full_atk = 0
        full_exp = 0
        full_gold = 0
        full_stock = 0
        for user, report in reports:
            if report:
                text += MSG_REPORT_SUMMARY_ROW.format(
                    report.name, user.username, report.attack, report.defence,
                    report.earned_exp, report.earned_gold, report.earned_stock)
                full_atk += report.attack
                full_def += report.defence
                full_exp += report.earned_exp
                full_gold += report.earned_gold
                full_stock += report.earned_stock
            else:
                text += MSG_REPORT_SUMMARY_ROW_EMPTY.format(
                    user.character.name, user.username)
        text = MSG_REPORT_SUMMARY_HEADER.format(
            squad.squad_name, time_from.strftime('%d-%m-%Y %H:%M'), full_atk,
            full_def, full_exp, full_gold, full_stock) + text
        markup = generate_other_reports(time_from, squad.chat_id)
        bot.editMessageText(text,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            parse_mode=ParseMode.HTML,
                            reply_markup=markup)
    elif data['t'] == QueryType.GlobalBuildTop.value:
        update.callback_query.answer(text=MSG_TOP_GENERATING)
        global_build_top(bot, update)
    elif data['t'] == QueryType.WeekBuildTop.value:
        update.callback_query.answer(text=MSG_TOP_GENERATING)
        week_build_top(bot, update)
    elif data['t'] == QueryType.SquadGlobalBuildTop.value:
        update.callback_query.answer(text=MSG_TOP_GENERATING)
        global_squad_build_top(bot, update)
    elif data['t'] == QueryType.SquadWeekBuildTop.value:
        update.callback_query.answer(text=MSG_TOP_GENERATING)
        week_squad_build_top(bot, update)
    elif data['t'] == QueryType.BattleGlobalTop.value:
        update.callback_query.answer(text=MSG_TOP_GENERATING)
        global_battle_top(bot, update)
    elif data['t'] == QueryType.BattleWeekTop.value:
        update.callback_query.answer(text=MSG_TOP_GENERATING)
        week_battle_top(bot, update)
    elif data['t'] == QueryType.Yes.value:
        leave_squad(bot, user, user.member, update.effective_message, session)
    elif data['t'] == QueryType.No.value:
        bot.editMessageText(MSG_SQUAD_LEAVE_DECLINE,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id)
Beispiel #7
0
def manage_all(bot: Bot, update: Update, session, chat_data, job_queue):
    add_user(update.message.from_user, session)
    if update.message.chat.type in ['group', 'supergroup', 'channel']:
        squad = session.query(Squad).filter_by(
            chat_id=update.message.chat.id).first()
        admin = session.query(Admin).filter(
            Admin.user_id == update.message.from_user.id and
            Admin.admin_group in [update.message.chat.id, 0]).first()

        if squad is not None and admin is None and battle_time():
            bot.delete_message(update.message.chat.id,
                               update.message.message_id)

        if not update.message.text:
            return

        text = update.message.text.lower()

        if text.startswith('приветствие:'):
            set_welcome(bot, update)
        elif text == 'помощь':
            help_msg(bot, update)
        elif text == 'покажи приветствие':
            show_welcome(bot, update)
        elif text == 'включи приветствие':
            enable_welcome(bot, update)
        elif text == 'выключи приветствие':
            disable_welcome(bot, update)
        elif text.startswith('затриггерь:'):
            set_trigger(bot, update)
        elif text.startswith('разтриггерь:'):
            del_trigger(bot, update)
        elif text == 'список триггеров':
            list_triggers(bot, update)
        elif text == 'список админов':
            list_admins(bot, update)
        elif text == 'пинг':
            ping(bot, update)
        elif text == 'статистика за день':
            day_activity(bot, update)
        elif text == 'статистика за неделю':
            week_activity(bot, update)
        elif text == 'статистика за бой':
            battle_activity(bot, update)
        elif text == 'разрешить триггерить всем':
            enable_trigger_all(bot, update)
        elif text == 'запретить триггерить всем':
            disable_trigger_all(bot, update)
        elif text in ['админы', 'офицер']:
            admins_for_users(bot, update)
        elif text == 'пинят все':
            pin_all(bot, update)
        elif text == 'хорош пинить':
            not_pin_all(bot, update)
        elif text in ['бандит', 'краб']:
            boss_leader(bot, update)
        elif text in ['жало', 'королева роя']:
            boss_zhalo(bot, update)
        elif text in ['циклоп', 'борода']:
            boss_monoeye(bot, update)
        elif text in ['гидра', 'лич']:
            boss_hydra(bot, update)
        elif text == 'открыть набор':
            open_hiring(bot, update)
        elif text == 'закрыть набор':
            close_hiring(bot, update)
        elif update.message.reply_to_message is not None:
            if text == 'пин':
                pin(bot, update)
            elif text == 'сайлентпин':
                silent_pin(bot, update)
            elif text == 'удоли':
                delete_msg(bot, update)
            elif text == 'свали':
                delete_user(bot, update)
            else:
                trigger_show(bot, update)
        elif 'твои результаты в бою:' in text:
            if update.message.forward_from.id == CWBOT_ID:
                report_received(bot, update)
        else:
            trigger_show(bot, update)

    elif update.message.chat.type == 'private':
        admin = session.query(Admin).filter_by(user_id=update.message.from_user.id).all()
        is_admin = False
        for _ in admin:
            is_admin = True
            break

        if 'order_wait' in chat_data and chat_data['order_wait']:
            order(bot, update, chat_data)

        elif update.message.text:
            text = update.message.text.lower()

            if text == ADMIN_COMMAND_STATUS.lower():
                send_status(bot, update)
            elif text == USER_COMMAND_BACK.lower():
                user_panel(bot, update)
            elif text == USER_COMMAND_SQUAD_REQUEST.lower():
                squad_request(bot, update)
            elif text == ADMIN_COMMAND_RECRUIT.lower():
                list_squad_requests(bot, update)
            elif text == ADMIN_COMMAND_ORDER.lower():
                orders(bot, update, chat_data)
            elif text == ADMIN_COMMAND_SQUAD_LIST.lower():
                squad_list(bot, update)
            elif text == ADMIN_COMMAND_GROUPS.lower():
                group_list(bot, update)
            elif text == ADMIN_COMMAND_FIRE_UP.lower():
                remove_from_squad(bot, update)
            elif text == USER_COMMAND_ME.lower():
                char_show(bot, update)
            elif text == USER_COMMAND_TOP.lower():
                top_about(bot, update)
            elif text == TOP_COMMAND_ATTACK.lower():
                attack_top(bot, update)
            elif text == TOP_COMMAND_DEFENCE.lower():
                def_top(bot, update)
            elif text == TOP_COMMAND_EXP.lower():
                exp_top(bot, update)
            elif text == USER_COMMAND_BUILD.lower():
                send_async(bot,
                           chat_id=update.message.chat.id,
                           text=MSG_IN_DEV,
                           parse_mode=ParseMode.HTML)
            elif text == USER_COMMAND_STATISTICS.lower():
                statistic_about(bot, update)
            elif text == STATISTICS_COMMAND_EXP.lower():
                exp_statistic(bot, update)
            elif text == USER_COMMAND_SQUAD.lower():
                squad_about(bot, update)
            elif text == USER_COMMAND_SQUAD_LEAVE.lower():
                leave_squad(bot, update)
            elif text == USER_COMMAND_CONTACTS.lower():
                send_async(bot,
                           chat_id=update.message.chat.id,
                           text=MSG_IN_DEV,
                           parse_mode=ParseMode.HTML)
            elif 'wait_group_name' in chat_data and chat_data['wait_group_name']:
                add_group(bot, update, chat_data)

            elif update.message.forward_from:
                from_id = update.message.forward_from.id

                if from_id == CWBOT_ID:
                    if text.startswith('📦содержимое склада'):
                        stock_compare(bot, update, chat_data)
                    elif re.search(PROFILE, update.message.text) or re.search(HERO, update.message.text):
                        char_update(bot, update)
                    elif re.search(REPORT, update.message.text):
                        report_received(bot, update)
                    elif re.search(BUILD_REPORT, update.message.text):
                        build_report_received(bot, update)
                    elif re.search(REPAIR_REPORT, update.message.text):
                        repair_report_received(bot, update)
                elif from_id == TRADEBOT_ID:
                    if '📦твой склад с материалами:' in text:
                        trade_compare(bot, update, chat_data)
            elif not is_admin:
                user_panel(bot, update)
            else:
                order(bot, update, chat_data)
        elif not is_admin:
            user_panel(bot, update)
        else:
            order(bot, update, chat_data)
def callback_query(bot: Bot, update: Update, chat_data: dict):
    session = Session()
    update_group(update.callback_query.message.chat)
    user = add_user(update.callback_query.from_user)
    data = json.loads(update.callback_query.data)
    logger.warning(data)
    if data['t'] == QueryType.GroupList.value:
        msg = MSG_GROUP_STATUS_CHOOSE_CHAT
        squads = session.query(Squad).all()
        inline_keys = []
        for squad in squads:
            inline_keys.append(
                InlineKeyboardButton(squad.squad_name,
                                     callback_data=json.dumps({
                                         't':
                                         QueryType.GroupInfo.value,
                                         'id':
                                         squad.chat_id
                                     })))
        inline_markup = InlineKeyboardMarkup([[key] for key in inline_keys])
        bot.editMessageText(msg,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=inline_markup)
    elif data['t'] == QueryType.GroupInfo.value:
        msg, inline_markup = generate_group_info(data['id'])
        bot.editMessageText(msg,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=inline_markup)
    elif data['t'] == QueryType.DelAdm.value:
        del_adm(bot, data['gid'], user)
        msg, inline_markup = generate_group_info(data['gid'])
        bot.editMessageText(msg,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=inline_markup)
    elif data['t'] == QueryType.Order.value:
        if not data['g']:
            order = Order()
            order.text = chat_data['order']
            order.chat_id = data['id']
            order.date = datetime.now()
            order.confirmed_msg = send_async(bot,
                                             chat_id=order.chat_id,
                                             text=MSG_ORDER_CLEARED_BY_HEADER +
                                             MSG_EMPTY).result().message_id
            session.add(order)
            session.commit()
            markup = generate_ok_markup(order.id, 0)
            msg = send_order(bot, order.text, chat_data['order_type'],
                             order.chat_id, markup).result().result()
            if 'pin' in chat_data and chat_data[
                    'pin'] or 'pin' not in chat_data:
                try:
                    bot.request.post(
                        bot.base_url + '/pinChatMessage', {
                            'chat_id': order.chat_id,
                            'message_id': msg.message_id,
                            'disable_notification': False
                        })
                except:
                    pass
        else:
            group = session.query(OrderGroup).filter_by(id=data['id']).first()
            for item in group.items:
                order = Order()
                order.text = chat_data['order']
                order.chat_id = item.chat_id
                order.date = datetime.now()
                order.confirmed_msg = send_async(
                    bot,
                    chat_id=order.chat_id,
                    text=MSG_ORDER_CLEARED_BY_HEADER +
                    MSG_EMPTY).result().message_id
                session.add(order)
                session.commit()
                markup = generate_ok_markup(order.id, 0)
                msg = send_order(bot, order.text, chat_data['order_type'],
                                 order.chat_id, markup).result().result()
                if 'pin' in chat_data and chat_data[
                        'pin'] or 'pin' not in chat_data:
                    try:
                        bot.request.post(
                            bot.base_url + '/pinChatMessage', {
                                'chat_id': order.chat_id,
                                'message_id': msg.message_id,
                                'disable_notification': False
                            })
                    except:
                        pass
        update.callback_query.answer(text=MSG_ORDER_SENT)
    elif data['t'] == QueryType.OrderOk.value:
        order = session.query(Order).filter_by(id=data['id']).first()
        if order is not None:
            squad = session.query(Squad).filter_by(
                chat_id=order.chat_id).first()
            if squad is not None:
                squad_member = session.query(SquadMember).filter_by(
                    squad_id=squad.chat_id,
                    user_id=update.callback_query.from_user.id).first()
                if squad_member is not None:
                    order_ok = session.query(OrderCleared).filter_by(
                        order_id=data['id'],
                        user_id=squad_member.user_id).first()
                    if order_ok is None and datetime.now(
                    ) - order.date < timedelta(minutes=10):
                        order_ok = OrderCleared()
                        order_ok.order_id = data['id']
                        order_ok.user_id = update.callback_query.from_user.id
                        session.add(order_ok)
                        session.commit()
                        if order.confirmed_msg != 0:
                            confirmed = order.cleared
                            msg = MSG_ORDER_CLEARED_BY_HEADER
                            for confirm in confirmed:
                                msg += str(confirm.user) + '\n'
                            bot.editMessageText(msg, order.chat_id,
                                                order.confirmed_msg)
                        update.callback_query.answer(text=MSG_ORDER_CLEARED)
                    else:
                        update.callback_query.answer(
                            text=MSG_ORDER_CLEARED_ERROR)
                else:
                    update.callback_query.answer(text=MSG_ORDER_CLEARED_ERROR)
            else:
                order_ok = session.query(OrderCleared).filter_by(
                    order_id=data['id'],
                    user_id=update.callback_query.from_user.id).first()
                if order_ok is None and datetime.now(
                ) - order.date < timedelta(minutes=10):
                    order_ok = OrderCleared()
                    order_ok.order_id = data['id']
                    order_ok.user_id = update.callback_query.from_user.id
                    session.add(order_ok)
                    session.commit()
                    update.callback_query.answer(text=MSG_ORDER_CLEARED)
                else:
                    update.callback_query.answer(text=MSG_ORDER_CLEARED_ERROR)
    elif data['t'] == QueryType.Orders.value:
        if 'txt' in data and len(data['txt']):
            if data['txt'] == Icons.LES.value:
                chat_data['order'] = Castle.LES.value
            elif data['txt'] == Icons.GORY.value:
                chat_data['order'] = Castle.GORY.value
            elif data['txt'] == Icons.SEA.value:
                chat_data['order'] = Castle.SEA.value
            else:
                chat_data['order'] = data['txt']
        markup = generate_order_chats_markup(
            bot, chat_data['pin'] if 'pin' in chat_data else True)
        bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.OrderGroup.value:
        if 'txt' in data and len(data['txt']):
            chat_data['order_type'] = MessageType.TEXT
            if data['txt'] == Icons.LES.value:
                chat_data['order'] = Castle.LES.value
            elif data['txt'] == Icons.GORY.value:
                chat_data['order'] = Castle.GORY.value
            elif data['txt'] == Icons.SEA.value:
                chat_data['order'] = Castle.SEA.value
            else:
                chat_data['order'] = data['txt']
        admin_user = session.query(Admin).filter(
            Admin.user_id == update.callback_query.from_user.id).all()
        markup = generate_order_groups_markup(
            bot, admin_user, chat_data['pin'] if 'pin' in chat_data else True)
        bot.editMessageText(MSG_ORDER_SEND_HEADER.format(chat_data['order']),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.OrderGroupManage.value:
        group = session.query(OrderGroup).filter_by(id=data['id']).first()
        markup = generate_group_manage(data['id'])
        bot.editMessageText(MSG_ORDER_GROUP_CONFIG_HEADER.format(group.name),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.OrderGroupTriggerChat.value:
        group = session.query(OrderGroup).filter_by(id=data['id']).first()
        deleted = False
        for item in group.items:
            if item.chat_id == data['c']:
                session.delete(item)
                session.commit()
                deleted = True
        if not deleted:
            item = OrderGroupItem()
            item.group_id = group.id
            item.chat_id = data['c']
            session.add(item)
            session.commit()
        markup = generate_group_manage(data['id'])
        bot.editMessageText(MSG_ORDER_GROUP_CONFIG_HEADER.format(group.name),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.OrderGroupAdd.value:
        chat_data['wait_group_name'] = True
        send_async(bot,
                   chat_id=update.callback_query.message.chat.id,
                   text=MSG_ORDER_GROUP_NEW)
    elif data['t'] == QueryType.OrderGroupDelete.value:
        group = session.query(OrderGroup).filter_by(id=data['id']).first()
        session.delete(group)
        session.commit()
        bot.editMessageText(MSG_ORDER_GROUP_LIST,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_groups_manage())
    elif data['t'] == QueryType.OrderGroupList.value:
        bot.editMessageText(MSG_ORDER_GROUP_LIST,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_groups_manage())
    elif data['t'] == QueryType.ShowEquip.value:
        user = session.query(User).filter_by(id=data['id']).first()
        update.callback_query.answer(text=MSG_CLEARED)
        bot.editMessageText('{}\n🕑 Последнее обновление {}'.format(
            user.equip.equip, user.equip.date),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_profile_buttons(user))
    elif data['t'] == QueryType.ShowStock.value:
        user = session.query(User).filter_by(id=data['id']).first()
        update.callback_query.answer(text=MSG_CLEARED)
        bot.editMessageText('{}\n🕑 Последнее обновление {}'.format(
            user.stock.stock, user.stock.date.strftime("%Y-%m-%d %H:%M:%S")),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_profile_buttons(user))
    elif data['t'] == QueryType.ShowHero.value:
        user = session.query(User).filter_by(id=data['id']).first()
        update.callback_query.answer(text=MSG_CLEARED)
        bot.editMessageText(fill_char_template(MSG_PROFILE_SHOW_FORMAT, user,
                                               user.character),
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=generate_profile_buttons(user))
    elif data['t'] == QueryType.MemberList.value:
        squad = session.query(Squad).filter_by(chat_id=data['id']).first()
        markup = generate_squad_members(squad.members)
        bot.editMessageText(squad.squad_name,
                            update.callback_query.message.chat.id,
                            update.callback_query.message.message_id,
                            reply_markup=markup)
    elif data['t'] == QueryType.LeaveSquad.value:
        member = session.query(SquadMember).filter_by(
            user_id=data['id']).first()
        if member:
            squad = member.squad
            user = member.user
            session.delete(member)
            session.commit()
            admins = session.query(Admin).filter_by(
                admin_group=squad.chat_id).all()
            for adm in admins:
                if adm.user_id != update.callback_query.from_user.id:
                    send_async(bot,
                               chat_id=adm.user_id,
                               text=MSG_SQUAD_LEAVED.format(
                                   user.character.name, squad.squad_name))
            send_async(bot,
                       chat_id=member.squad_id,
                       text=MSG_SQUAD_LEAVED.format(user.character.name,
                                                    squad.squad_name))
            send_async(bot,
                       chat_id=member.user_id,
                       text=MSG_SQUAD_LEAVED.format(user.character.name,
                                                    squad.squad_name))
            if data['id'] == update.callback_query.from_user.id:
                bot.editMessageText(
                    MSG_SQUAD_LEAVED.format(user.character.name,
                                            squad.squad_name),
                    update.callback_query.message.chat.id,
                    update.callback_query.message.message_id)
            else:
                members = session.query(SquadMember).filter_by(
                    squad_id=member.squad_id).all()
                bot.editMessageText(update.callback_query.message.text,
                                    update.callback_query.message.chat.id,
                                    update.callback_query.message.message_id,
                                    reply_markup=generate_fire_up(members))
        else:
            update.callback_query.answer(
                text=
                'Этот пользователь уже выпилен из отряда, кнопка больше не работает =('
            )
    elif data['t'] == QueryType.RequestSquad.value:
        member = session.query(SquadMember).filter_by(
            user_id=update.callback_query.from_user.id).first()
        if member is None:
            member = SquadMember()
            member.user_id = update.callback_query.from_user.id
            member.squad_id = data['id']
            session.add(member)
            session.commit()
            admins = session.query(Admin).filter_by(
                admin_group=data['id']).all()
            usernames = [
                '@' + session.query(User).filter_by(
                    id=admin.user_id).first().username for admin in admins
            ]
            bot.editMessageText(
                MSG_SQUAD_REQUESTED.format(member.squad.squad_name,
                                           ', '.join(usernames)),
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id)
            admins = session.query(Admin).filter_by(
                admin_group=member.squad.chat_id).all()
            for adm in admins:
                send_async(bot,
                           chat_id=adm.user_id,
                           text=MSG_SQUAD_REQUEST_NEW)
        else:
            markup = generate_leave_squad(user.id)
            bot.editMessageText(MSG_SQUAD_REQUEST_EXISTS,
                                update.callback_query.message.chat.id,
                                update.callback_query.message.message_id,
                                reply_markup=markup)
    elif data['t'] == QueryType.RequestSquadAccept.value:
        member = session.query(SquadMember).filter_by(
            user_id=data['id']).first()
        if member:
            member.approved = True
            session.add(member)
            session.commit()
            bot.editMessageText(
                MSG_SQUAD_REQUEST_ACCEPTED.format('@' + member.user.username),
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id)
            send_async(bot,
                       chat_id=member.user_id,
                       text=MSG_SQUAD_REQUEST_ACCEPTED_ANSWER)
            send_async(
                bot,
                chat_id=member.squad_id,
                text=MSG_SQUAD_REQUEST_ACCEPTED.format('@' +
                                                       member.user.username))
    elif data['t'] == QueryType.RequestSquadDecline.value:
        member = session.query(SquadMember).filter_by(
            user_id=data['id']).first()
        if member:
            bot.editMessageText(
                MSG_SQUAD_REQUEST_DECLINED.format('@' + member.user.username),
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id)
            session.delete(member)
            session.commit()
            send_async(bot,
                       chat_id=member.user_id,
                       text=MSG_SQUAD_REQUEST_DECLINED_ANSWER)
    elif data['t'] == QueryType.InviteSquadAccept.value:
        if update.callback_query.from_user.id != data['id']:
            update.callback_query.answer(text='Пшёл вон!')
            return
        member = session.query(SquadMember).filter_by(
            user_id=data['id']).first()
        if member is None:
            member = SquadMember()
            member.user_id = user.id
            member.squad_id = update.callback_query.message.chat.id
            session.add(member)
            session.commit()
            member.approved = True
            session.add(member)
            session.commit()
            bot.editMessageText(
                MSG_SQUAD_ADD_ACCEPTED.format('@' + user.username),
                update.callback_query.message.chat.id,
                update.callback_query.message.message_id)
    elif data['t'] == QueryType.InviteSquadDecline.value:
        if update.callback_query.from_user.id != data['id']:
            update.callback_query.answer(text='Пшёл вон!')
            return
        user = session.query(User).filter_by(id=data['id']).first()
        bot.editMessageText(
            MSG_SQUAD_REQUEST_DECLINED.format('@' + user.username),
            update.callback_query.message.chat.id,
            update.callback_query.message.message_id)
    elif data['t'] == QueryType.TriggerOrderPin.value:
        if 'pin' in chat_data:
            chat_data['pin'] = not chat_data['pin']
        else:
            chat_data['pin'] = False
        if data['g']:
            admin_user = session.query(Admin).filter(
                Admin.user_id == update.callback_query.from_user.id).all()
            markup = generate_order_groups_markup(
                bot, admin_user,
                chat_data['pin'] if 'pin' in chat_data else True)
            bot.editMessageText(MSG_ORDER_SEND_HEADER.format(
                chat_data['order']),
                                update.callback_query.message.chat.id,
                                update.callback_query.message.message_id,
                                reply_markup=markup)
        else:
            markup = generate_order_chats_markup(
                bot, chat_data['pin'] if 'pin' in chat_data else True)
            bot.editMessageText(MSG_ORDER_SEND_HEADER.format(
                chat_data['order']),
                                update.callback_query.message.chat.id,
                                update.callback_query.message.message_id,
                                reply_markup=markup)
Beispiel #9
0
def start(bot: Bot, update: Update):
    add_user(update.message.from_user)
    if update.message.chat.type == 'private':
        send_async(bot, chat_id=update.message.chat.id, text=MSG_START_WELCOME)
Beispiel #10
0
def manage_all(bot: Bot, update: Update, chat_data, job_queue):
    try:
        add_user(update.message.from_user)
        if update.message.chat.type in ['group', 'supergroup', 'channel']:
            session = Session()
            squad = session.query(Squad).filter_by(
                chat_id=update.message.chat.id).first()
            admin = session.query(Admin).filter(
                Admin.user_id == update.message.from_user.id
                and Admin.admin_group in [update.message.chat.id, 0]).first()
            if squad is not None and admin is None and battle_time():
                bot.delete_message(update.message.chat.id,
                                   update.message.message_id)
            if update.message.text and update.message.text.upper().startswith(
                    'Приветствие:'.upper()):
                set_welcome(bot, update)
            elif update.message.text and 'Твои результаты в бою:' in update.message.text and \
                    update.message.forward_from and update.message.forward_from.id == 265204902:
                job_queue.run_once(
                    del_msg, 2,
                    (update.message.chat.id, update.message.message_id))
            elif update.message.text and update.message.text.upper(
            ) == 'Помощь'.upper():
                help_msg(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Покажи приветствие'.upper():
                show_welcome(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Включи приветствие'.upper():
                enable_welcome(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Выключи приветствие'.upper():
                disable_welcome(bot, update)
            elif update.message.text and update.message.text.upper(
            ).startswith('Затриггерь:'.upper()):
                set_trigger(bot, update)
            elif update.message.text and update.message.text.upper(
            ).startswith('Разтриггерь:'.upper()):
                del_trigger(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Список триггеров'.upper():
                list_triggers(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Список админов'.upper():
                list_admins(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Пинг'.upper():
                ping(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Статистика за день'.upper():
                day_activity(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Статистика за неделю'.upper():
                week_activity(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Статистика за бой'.upper():
                battle_activity(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Разрешить триггерить всем'.upper():
                enable_trigger_all(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Запретить триггерить всем'.upper():
                disable_trigger_all(bot, update)
            elif update.message.text and update.message.text.upper() in [
                    'Админы'.upper(), 'офицер'.upper()
            ]:
                admins_for_users(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Пинят все'.upper():
                pin_all(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Хорош пинить'.upper():
                not_pin_all(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'Пин'.upper() and update.message.reply_to_message is not None:
                pin(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'сайлентпин'.upper(
            ) and update.message.reply_to_message is not None:
                silent_pin(bot, update)
            elif update.message.text and update.message.text.upper() in [
                    'бандит'.upper(), 'краб'.upper()
            ]:
                boss_leader(bot, update)
            elif update.message.text and update.message.text.upper() in [
                    'жало'.upper(), 'королева роя'.upper()
            ]:
                boss_zhalo(bot, update)
            elif update.message.text and update.message.text.upper() in [
                    'циклоп'.upper(), 'борода'.upper()
            ]:
                boss_monoeye(bot, update)
            elif update.message.text and update.message.text.upper() in [
                    'гидра'.upper(), 'лич'.upper()
            ]:
                boss_hydra(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'открыть набор'.upper():
                open_hiring(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'закрыть набор'.upper():
                close_hiring(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'удоли'.upper(
            ) and update.message.reply_to_message is not None:
                delete_msg(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'свали'.upper(
            ) and update.message.reply_to_message is not None:
                delete_user(bot, update)
            elif update.message.text:
                trigger_show(bot, update)
        elif update.message.chat.type == 'private':
            if update.message.text and update.message.text.upper(
            ) == 'Статус'.upper():
                send_status(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'хочу в отряд'.upper():
                squad_request(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'заявки в отряд'.upper():
                list_squad_requests(bot, update)
            elif update.message.text and update.message.text.upper() in [
                    'Приказы'.upper(), 'пин'.upper()
            ]:
                orders(bot, update, chat_data)
            elif update.message.text and update.message.text.upper() in [
                    'список отряда'.upper(), 'список'.upper()
            ]:
                Thread(target=squad_list, args=(bot, update)).start()
            elif update.message.text and update.message.text.upper(
            ) == 'Группы'.upper():
                group_list(bot, update)
            elif update.message.text and update.message.text.upper(
            ) == 'чистка отряда'.upper():
                remove_from_squad(bot, update)
            elif update.message.forward_from and update.message.forward_from.id == 265204902 and \
                    update.message.text.startswith('📦Содержимое склада'):
                stock_compare(bot, update, chat_data)
            elif update.message.forward_from and update.message.forward_from.id == 278525885 and \
                            '📦Твой склад с материалами:' in update.message.text:
                trade_compare(bot, update, chat_data)
            elif 'wait_group_name' in chat_data and chat_data[
                    'wait_group_name']:
                add_group(bot, update, chat_data)
            elif update.message.text and update.message.forward_from and update.message.forward_from.id == 265204902 and \
                    (re.search(profile, update.message.text) or re.search(hero, update.message.text)):
                char_update(bot, update)
            else:
                order(bot, update, chat_data)
    except Exception as e:
        Session.rollback()
Beispiel #11
0
def manage_all(bot: Bot, update: Update, session):
    add_user(update.message.from_user, session)

    if update.message.chat.type in ['group', 'supergroup', 'channel']:

        if not update.message.text:
            return

        text = update.message.text.lower()

        if text.startswith(CC_SET_WELCOME):
            set_welcome(bot, update)
        elif text == CC_HELP:
            help_msg(bot, update)

        elif text == CC_SHOW_WELCOME:
            show_welcome(bot, update)
        elif text == CC_TURN_ON_WELCOME:
            enable_welcome(bot, update)
        elif text == CC_TURN_OFF_WELCOME:
            disable_welcome(bot, update)
        elif text.startswith(CC_SET_TRIGGER):
            set_trigger(bot, update)
        elif text.startswith(CC_UNSET_TRIGGER):
            del_trigger(bot, update)
        elif text == CC_TRIGGER_LIST:
            list_triggers(bot, update)
        elif text == CC_ADMIN_LIST:
            list_admins(bot, update)
        elif text == CC_PING:
            ping(bot, update)

        elif text == CC_ALLOW_TRIGGER_ALL:
            enable_trigger_all(bot, update)
        elif text == CC_DISALLOW_TRIGGER_ALL:
            disable_trigger_all(bot, update)
        elif text in CC_ADMINS:
            admins_for_users(bot, update)
        elif text == CC_ALLOW_PIN_ALL:
            pin_all(bot, update)
        elif text == CC_DISALLOW_PIN_ALL:
            not_pin_all(bot, update)

        elif update.message.reply_to_message is not None:
            if text == CC_PIN:
                pin(bot, update)
            elif text == CC_SILENT_PIN:
                silent_pin(bot, update)
            elif text == CC_DELETE:
                delete_msg(bot, update)
            elif text == CC_KICK:
                delete_user(bot, update)
            else:
                trigger_show(bot, update)

        else:
            trigger_show(bot, update)


# might need to remove elif statements below

    elif update.message.chat.type == 'private':
        admin = session.query(Admin).filter_by(
            user_id=update.message.from_user.id).all()
        is_admin = False
        for _ in admin:
            is_admin = True
            break

        if update.message.text:
            text = update.message.text.lower()

            if text == SHOW_ADMIN.lower():
                admin_panel(bot, update)

        if not is_admin:
            user_panel(bot, update)