Dspace.spbu.ru



Saint Petersburg State UniversityGraduate School of ManagementMaster in Business Analytics and Big Data Chatbot development business prospects: MTS caseMaster’s thesis by the 2nd year students:Anisimov Anton Vyacheslavovich(подпись)Ismailova Maria Rustamovna(подпись)Academic advisor:associate professorYablonsky Sergey AleksandrovichSaint Petersburg2020AbstractMaster Students’ NameAnisimov Anton Vyacheslavovich, Ismailova Maria RustamovnaMaster Thesis TitleChatbot development business prospects: MTS caseEducational ProgramManagementMain field of studyMaster in Business Analytics and Big DataYear2020Academic Advisor’s NameYablonsky Sergey AleksandrovichDescription of the goal, tasks and main resultsGoal: designing a business model and developing an MVP for MTS Live ChatbotObjectives:Undertake an overview of chatbot theoretical basics and a market research of chatbot’s general use cases.Describe current development stage of MTS, their main strategic goals and their ecosystem.Choose an existing MTS service for a chatbot implementation.Design a business model of a chatbot of a chosen service and describe its main features.Create and describe an MVP of a chosen bot.Results:Description of chatbots theory and markets.Description of MTS, its strategy and ecosystem.Choice of MTS Live service for a chatbot implementation.Design of a business model for MTS Live Chatbot.MTS Live Telegram bot MVP development and description.KeywordsChatbot, conversational platform, natural language, ecosystem, business model, value proposition, customer experience, user experience, user interface, customer engagement.АННОТАЦИЯАвторАнисимов Антон Вячеславович, Исмаилова Мария РустамовнаНазвание ВКРПерспективы развития чат-ботов для бизнеса на примере компании МТСОбразовательная программаМенеджментНаправление подготовкиБизнес-аналитика и большие данныеГод2020Научный руководительЯблонский Сергей АлександровичОписание цели, задач и основных результатовЦель: описание бизнес-модели и разработка MVP для чат-бота MTS Live сервисаЗадачи:Провести обзор теоретических аспектов, связанных с чат-ботами, а также обзор рынка и общих случаев использования.Описать текущую стадию развития МТС, их основные стратегические цели, а также имеющуюся экосистему.Выбрать один из сервисов МТС для разработки MVP чат-бота.Описать бизнес-модель чат-бота выбранного сервиса.Создать и описать MVP выбранного чат-бота.Результаты:Описание основ теории чат-ботов, обзор рынка.Описание МТС, их стратегии и экоситемы.Выбор сервиса MTS Live для разработки MVP чат-бота.Описание бизнес-модели чат-бота выбранного сервиса.Разработка и описание MTS Live Telegram bot MVP.Ключевые словаЧат-бот, разговорная платформа, естественный язык, бизнес-модель, создание ценности, потребительский опыт, потребительский интерфейс, вовлечённость потребителя.Table of contents TOC \o "1-3" \h \z \u Table of contents PAGEREF _Toc42201187 \h 5Introduction PAGEREF _Toc42201188 \h 6Chapter 1 Analysis of the chatbot market PAGEREF _Toc42201189 \h 81.1A guide to chatbot basics: what is it and how it works? PAGEREF _Toc42201190 \h 81.2 Chatbot’s business roles and general use cases PAGEREF _Toc42201191 \h 131.2.1 Ways of delivering and evaluating the chatbot value for business PAGEREF _Toc42201192 \h 141.2.2 Chatbot business functions and industry examples PAGEREF _Toc42201193 \h 18Chapter 2 Chatbot implementation proposals for MTS PAGEREF _Toc42201194 \h 222.1 MTS: description and history PAGEREF _Toc42201195 \h 222.2 MTS: main goals and ecosystem description PAGEREF _Toc42201196 \h 262.3 Chatbot implementation directions for MTS PAGEREF _Toc42201197 \h 32Chapter 3 MTS Live Chatbot proposals PAGEREF _Toc42201198 \h 353.1 Business model designing for MTS Live Chatbot PAGEREF _Toc42201199 \h 353.1.1 Strategyzer Cloud service for business model designing PAGEREF _Toc42201200 \h 353.1.2 Design of Business Model Canvas for MTS Live Chatbot PAGEREF _Toc42201201 \h 353.1.3 Design of Value Proposition Canvas for MTS Live Chatbot PAGEREF _Toc42201202 \h 393.1.4 MTS Live Chatbot abilities PAGEREF _Toc42201203 \h 423.2 Creation of MTS Live Chatbot MVP PAGEREF _Toc42201204 \h 443.2.1 Preparation for the development of MVP PAGEREF _Toc42201205 \h 443.2.2 Description of chatbot architecture and development process PAGEREF _Toc42201206 \h 47Conclusion PAGEREF _Toc42201207 \h 62List of references PAGEREF _Toc42201208 \h 64Glossary PAGEREF _Toc42201209 \h 66Appendix MTS Live Telegram Bot MVP Code PAGEREF _Toc42201210 \h 67IntroductionTechnological development is gaining more and more momentum in recent years. Especially in the mobile world where the number of users increasing with this progress, and people are getting used to being permanently online and in the access zone, due to their mobile devices. Now they can’t imagine themselves using online services without fast and user-friendly customer experience, and they’re expecting, that more and more companies will follow that path. In response to the customer's wants and needs, businesses have to implement cutting-edge technologies to justify customer’s expectations, improve their experience and engagement. It is important for the business since better customer experience definitely makes their clients more satisfied with being in touch with the business and, thus, more loyal. One of the ways to deliver expected user experience is by implementing chatbots in the company’s ecosystems and services. Chatbots suggest ways of solving the issues by providing the customers with a comfortable, quick, and always accessible customer experience.This work may be considered as a consulting project for MTS company. The initial task was to conduct a research dedicated to the ways of relieving customer pains by using the chatbots. But after conducting the first research and negotiating with MTS, it was decided and agreed to slightly change the focus of the work. The main reason for this was learning company’s working areas, identification of their main strategic priorities and a strong will to conduct a work, the results of which will be useful for the company and may be implemented in the future. Currently, as a main business goal, MTS has development of their own ecosystem with a huge amount of services that correspond with basic customer’s needs in a variety of industries. That is why it was decided to choose a creation of a business model and MVP of a chatbot for a particular and existing MTS service as the main topic. To make the achievement of this goal real, it was also necessary to state the objectives:Undertake an overview of chatbot theoretical basics and a market research of chatbot’s general use cases.Describe current development stage of MTS, their main strategic goals and their ecosystem.Choose an existing MTS service for a chatbot implementation.Design a business model of a chatbot of a chosen service and describe its main features.Create and describe an MVP of a chosen bot.From the above it follows that the subject of the work is chatbot business implementation and the object of the work is creation of an MVP of a chatbot. Structure and logic of the work meets the set goals and objectives. The work consists of three chapters.The first chapter of this work consists of two paragraphs and is devoted both to theoretical and practical aspects of a chatbot. It analyzes and compares different definitions, describes basic operational principles of the bot, considers and compares two main approaches of chatbot development and proves the relevance of the topic in the first paragraph. In the second paragraph it is described how the bots can bring value to business and how it is possible to evaluate their success. Different business functions and industry examples are also provided in the second paragraph of the first chapter.The second chapter of this work consists of three parts and is devoted to MTS. The first paragraph tells about current MTS scope of work and a brief history of the company. In the second paragraph the main strategic priorities of the company are described. The emphasis is put on the analysis and description of MTS current ecosystem, since it is the main priority of the company. Later, in the third paragraph of the second chapter several possible chatbot implementation directions are described and the one – MTS Live - is chosen for the future work.The third chapter of this work consists of two parts and is devoted to MTS Live Chatbot proposals. In the first paragraph the business model of the bot is described by designing the Business Model Canvas and the Value Proposition Canvas using Strategyzer Cloud Service. The first paragraph ends with a description of main functions of the MTS Live chatbot. The second paragraph of the work describes the MVP of the bot. The MVP was created not for the whole bot described by the business model, but for the part of it, since the aim was to show an example of how such bot can be created. Thus, MVP was created on the base of Telegram API and consists of two main functions of the proposed chatbot. The process of MVP creation is described in the second paragraph of the third chapter.Chapter 1 Analysis of the chatbot market1.1 A guide to chatbot basics: what is it and how it works?The first paragraph of this work aims to look through theoretical aspect of a chatbot and to give a basic understanding of what a chatbot is. For this purpose, the following questions are stated:Q1: What is a chatbot?Q2: What is an operational principle behind a chatbot?Q3: Which technological approaches for chatbot development are there?Q4: Why the topic is relevant?Best of all is to start the work dedicated to the role of chatbots in business from an attempt to figure out what a chatbot is. For this purpose, several definitions will be presented and compared. Rashid Khan defines chatbot as ?a computer program that processes natural-language input from a user and generates smart and relative responses that are then sent back to the user? (Khan, 2018, p.1). Boris Galitsky says that chatbot is ?a computer system that operates as an interface between human users and a software application, using spoken or written natural language as the primary means of communication? (Galitsky, 2019, p.13). Gartner defines chatbot as ?a domain-specific conversational interface that uses an app, messaging platform, social network or chat solution for its conversations. Chatbots vary in sophistication, from simple, decision-tree-based marketing stunts, to implementations built on feature-rich platforms. They are always narrow in scope. A chatbot can be text- or voice-based, or a combination of both?. All these definitions are very similar to each other and thus help to identify such basic and main elements of chatbots as computer program, natural language processing and conversation. In other words, a chatbot is a program or an application that is developed and used for an online conversation with the user instead of their direct contact with a live human. Chatbots are designed to simulate the behavior of a human as a conversational partner and use different methods of communication such as text, voice, gesture or touch. In the beginning of its own development chatbots were programmed to find out and satisfy the needs of the customers, but now they are already used for many other different roles within a company, helping in improvement of business efficiency and customer experience. The brief history of chatbot development is shown in the following Table 1:Table SEQ Table \* ARABIC 1 Brief history of chatbot developmentYearStage1950Turing test: shows, whether a machine can or can’t think. It can, if the judge, who is communicating with a person and with a computer at the same moment, while all the participants don’t see each other, can’t say, which of the interlocutors is a person.1966ELIZA: parodied the dialogue with the therapist by implementing the technique of active listening.1972PARRY: parodied a person with paranoid schizophrenia. It was based on the behavioral model of such a person, on the concepts and beliefs, and also captured a conversational strategy.1984Racter: was written as “artificially insane” but was not released.1988Jabberwacky: was the first attempt to create an AI-bot with the aim to “simulate natural human chat in an interesting, entertaining and humorous manner”.1990Loebner Prize: the award that takes place in the format of a Turing test and is given to the computer program acting in the most similar to a human way.1991Dr Sbaitso: an AI program with a digital voice, that could speak to a person. Its main aim was to show the variety of digitized voices.1995ALICE: a program, which could conduct a dialogue with a person in a natural language manner, three-times Loebner Prize winner.2000Elbot: had his own artificial intelligence. His key distinction was his ability to use irony, sarcasm, and wit to entertain people.2001Smarterchild: offered fun and personalized conversation.2005Mitsuku: imitated a teenage female who could talk about certain topics, play games and do magic, five-times Loebner Prize winner.2006IBM Watson: was developed and firstly used for TV competition, but now is used to detect information from large amounts of data.2010Siri: a voice assistant bought by Apple and integrated into the iPhones starting with iPhone 4S2012Google Now: developed by Google for Google Search Application. It is used to find answers to the questions, get recommendations, and perform certain actions.2015Alexa: a voice assistant developed by Amazon, launched a market for smart home speakersCortana: developed by Microsoft. It is able to recognize voice commands, set reminders and answer questions using the Bing search engine.2016Facebook Chatbots: launched its own messaging platform with more than 300?000 active chatbots in 2018.Tay: infamous chatbot that imitated the behavior of a teenage girl and closed 16 hours after the launch.2017Woebot: designed for users to learn their emotions.Exactly as stated in the Gartner definition of a chatbot, it can have various levels of intelligence depending, firstly, on its aim or use case, and, secondly, on the development approach. Bots range from simple ones, that answer questions, to the most intelligent ones, that can completely replace an employee. But before studying the development approaches, it is not less important to understand chatbot operating principles.Since the chat bot is used to communicate with a human, it must be able to understand the incoming text and to respond. Thus, the process can be simply described like this:chatbot converts entered voice data into the text by using automatic speech recognition (SR) technology (in case of using a voice by a particular chatbot);chatbot analyzes the text entered;chatbot considers the best response;chatbot sends the selected response back to the user in the text format, in voice format using the Text to Speech (TTS) tools or by completing a particular task.But it is important to realize that understanding human’s speech is not an easy task to recreate, so chatbots use principles of natural language like Natural Language Processing, Natural Language Understanding, Natural Language Generation. Natural language processing helps to divide input data into sentences and words, standardize the text using a number of methods, and most importantly, understand the mood, which is implied by the author. Natural language understanding helps to understand what the user has said in terms of context by using various language objects (such as lexicons, synonyms, and topics), which are later used together with the rules of building dialogues. As a result of this process, the chatbot knows how to react. Natural language generation helps to provide a more personalized experience to the customer. To create a response, which is not specified in advance, the chatbot queries data stores, including integrated server systems and third-party databases. The high-level principle of chatbot operation is, of course, much more complicated.As it was mentioned above the intelligence level of a chatbot is the consequence of the approach, chosen for a chatbot development. This choice, in its turn, depends on natural language abilities and accuracy of results. The most known development approaches are rule-based and machine learning-based.Rule-based bots are also called linguistic bots or menu-driven bots. They use if/then logic for creation of a dialogue. To guarantee the same answer for the questions with the same meaning, language conditions are created. These conditions help to analyze language patterns and to create a correct answer for the questions in advance. For choosing the next step by the user, this type of a chatbot suggests a menu of possible actions, under which lie exact operations. Rule-based bots are very popular in different industries and they are also very often integrated with company’s data systems like CRM. From the description of linguistic bots its advantages and disadvantages can be underlined (see Table 2):Table SEQ Table \* ARABIC 2 Advantages and disadvantages of rule-based approachAdvantagesDisadvantagesConfirmed accuracy of responseLimited functionalityEase of understanding and implementingTwo-step fulfillmentEase of extending a menuLimited natural language conversationsMachine learning or AI based bots tend to be more complex, but at the same time more conversational and predictive. The accuracy of this type of bots is not high at the beginning of their operation but tends to increase over time. The main difference from the rule-based bots is presence of NLP engine, which extract exact information from the natural language input. AI bots are also more personalized, since they use huge amounts of data to become aware of context and NLU to personalize user experience. The problem here is the necessity of huge amounts of data to train the models and also of skilled people, who will do this work. As a rule-based bot, machine learning-based one also has its own advantages and disadvantages (see Table 3):Table SEQ Table \* ARABIC 3 Advantages and disadvantages of machine learning-based approachAdvantagesDisadvantagesAdvanced conversationsComplex process of training, maintaining and improvementA huge number of scenariosNot always high accuracy of responsesSelf-learningHuge amounts of dataThe Hybrid model is also popular as it suggests taking the advantages of both, linguistic and machine learning based, types of bots to create better chatbot experience. In comparison to machine learning based chatbots, hybrid ones make it possible to create conversational platforms without data and provide visibility of the operations inside the system. In comparison to linguistic chatbots, hybrid ones allow for machine learning algorithms to act outside the box of the language rules and by doing so to create smart and complex decisions and findings in the spheres where it is almost impossible to create language patterns.There shouldn’t be any doubts about degree of popularity and speed of development of chatbots: ?By 2020, the average person will have more conversations with bots than with their spouse?. In recent years, the number of owners of smartphones and other mobile devices in the world has increased. These technologies, due to their mobility, allow people to be online constantly. In addition, with decreasing of size of devices, their processors and computing capabilities, on the contrary, increase. Accordingly, users are getting used to faster processes when interacting with their devices. They expect the same fast user experience in their interaction with companies. In addition, the modern users, being with technology on the short leg, do not want companies to restrict communication methods, but rather expect to be able to solve any of their user problems by interacting with technology over a wide range of channels at any time convenient for them. Chatbots suggest the ways of solving these issues.Today, the popularity of chatbots is constantly increasing. According to Peter Gentsch, ?since 2015, more people have been using applications (apps) for communications than social networks. That is almost three billion people worldwide every day. In Europa and in the USA, the platforms WhatsApp (approx. one billion people) and Facebook Messenger (900 million) are mainly used, whereby in Asia, WeChat (700 million) and Line (215 million) dominate? (Gentsch, 2019). This is confirmed by Google Trends data on the Figure 1 below:Figure SEQ Figure \* ARABIC 1. Google search trend for "chatbot" for the last 5 yearsIn Gartner 2019 Hype Cycle for Artificial Intelligence many different technologies are included. Gartner identifies five most significant for business in next 2-5 years: augmented intelligence, chatbots, machine learning, AI governance, intelligent applications. Among these technologies, chatbot is the face of artificial intelligence, being the technology that covers all areas where the interaction between people exists. In HR, helpdesk and self-service chatbots are also used, but they are still mostly developed in the field of customer service, where they create an irreplaceable opportunity to establish an important transition from "customer learns how the service works" to "chatbot learns what the customer wants".The situation with the reasons for the accelerated development and popularity of chatbots is similar to the situation with the definitions of chatbots – different sources interpret them almost in the same way. Thus, Khan highlights three main reasons of chat becoming a buzzword (Khan, 2018, p.2):growth of Internet users: the number of Internet users has grown from 300 million users in 2000 to 4,6 billion users in 2020, which is about 59% of the world population () – to become popular and successful it is necessary for chatbots to become accessible;advancement in technology: machine learning has transitioned from theoretical problems to practical implementations;developer ecosystem: exponential growth of developer community.Deloitte in their research points out three key drivers of chatbot development (Deloitte, 2018):exponential growth of data;faster processing speed;smarter algorithms.They also say that these are the market forces who make a significant push to drive the opportunities of chatbots. From the demand perspective the rise of chatbots conditioned by increasing pressure on call centers and increasing demand for self-service. From the supply perspective – by technological development in artificial intelligence and natural language processing and development of maturity of chatbot platforms.Obviously, a chatbot, in order to avoid irritation from customers, must be carefully worked out. The development of a high-quality chatbot requires significant labor resources, i.e. several qualified developers working full time. Therefore, the final cost of the product can be quite significant, which makes powerful customized chatbots a preference of large companies, almost unattainable for small business. Thus, it is quite possible that the chatbot-as-a-service market will get a significant boost in the future (Gentsch, 2019). Small companies, which are not able to organize their own in-house chatbot development, form a demand for conversational bot constructors. There is already a number of such services (for example, Aimylogic or Botmother), and their number will greatly increase in the close future.Thus, in the first paragraph the answers raised at the beginning were received by comparing different definitions of chatbots, exploring a simple scheme behind chatbot operation, describing the main development approaches of the chatbots and proving the relevance of the topic. Now, it is possible to state, that the popularity of chatbot technologies is not artificial at all since they really can bring a considerable value both for businesses and for the customers, which will be shown in the next part.1.2 Chatbot’s business roles and general use casesIn the first paragraph it was stated and proven, that chatbot is one of the most popular technologies currently. In order to understand its applicability and relevance for business, it is better to conduct a market research. Thus, the second paragraph aims to analyze practical aspects of the chatbots, their roles and function in the market. It is divided into two parts, where the first one tries to give answers on the following questions:Q1: How do chatbots bring value to business?Q2: How is it possible to evaluate the successfulness of chatbot implementation?while the second searches for the answers on the following ones:Q3: Which business functions do the chatbot serve?Q4: In which industries and how are the bots used?1.2.1 Ways of delivering and evaluating the chatbot value for businessOne of the most important questions that should be answered is how do chatbot bring value to business? Since, this technology is so developed nowadays, there should be several ways of delivering benefits to the business. Otherwise, they wouldn’t pay for that technologies, and its popularity couldn’t be proved. The benefits of chatbots in business can be divided into direct and indirect, where direct bring countable value and indirect work more with customer experience.The main benefits are:Quick response: as was already stated modern customers expect the fastest possible customer experience. They like to get quick responses to queries and solve their own user problems by themselves: ?75 % of customers demand “now” service within five minutes of online contact?. Thus, the user-friendliness of the interface and the speed of response to user requests are important characteristics of the service. Chat-bots are helping companies to solve this problem by providing fast and automotive customer service.24/7/365: similar to the rapidness of the service, customers want to have an answer “here and now”, no matter where and when they really are. Young people, who have grown in the age of technologies and who are the future of that technologies are more likely to expect fast user experience: ?Millennials demand instant gratification and immediate access to whatever they desire?. Chatbots can help to solve this issue too, replacing the employees when they are unavailable – for example, at night or at holidays. Strengthening of customer loyalty: ?The number one thing customers want from customer service is faster response times?. The higher is the speed of response to the customer requests, the more comfortable they feel when using the service and, consequently, the higher is their loyalty.Increase of customer engagement: since people nowadays like and are used to online methods of communication, chatbots can help to increase their engagement to the process. They can also do it by personalizing the service and, thus, making customer satisfaction even better. Salesforce found that ?70 % of consumers agree that?technology has made it easier than ever to take their business elsewhere?.Better client understanding: conversational data helps to identify and interpret trends in customer mood and behavior. By analyzing this data, a business can offer better services and products, as well as providing them in a different way.Increase of revenues: smart chatbots can increase the company's revenue by increasing the sales conversion rate. They direct customers towards purchases with the help of tips and recommendations based on understanding and knowledge of customer preferences.Decrease of costs: chatbots help companies to reduce costs by building automated type of relationship with the customers. Thus, businesses can serve a larger number of customers not only without increasing costs, but also reducing them, since it requires a smaller number of employees and their lower level of involvement in communicating with the clients. A large number (up to 80%, depending of the sphere of implication) of user requests can be automated, so chatbots reduce the number of incoming requests and ensure the speed of a first call resolution (FCR).Optimization of staff skills: chatbots help to free up employees' time by reducing the load on employees when receiving a large flow of incoming requests. They achieve this by automating processes such as calls, email, SMS, and social media messages. A chatbot can handle simple problems itself and route the more complicated ones to the right specialist. So, the released time can be later used to solve tasks related to more valuable client interactions.Creation of a new sales channel: a chatbot is not only an assistant in solving queries, but also an independent sales channel, as it can attract customers and provide them with personalized consultations.As it was already mentioned, there are indirect ways of delivering value to business by chatbot. From the list of benefits above, it is seen that most of them do have an impact exactly on a customer journey. For this reason, the following question is formed: how can we evaluate the implementation of chatbots? Key indicators for evaluation of chatbot implementation effectiveness can be divided into several groups:Business performance metrics or, in other words, how well does the chatbot copes with the tasks for which it was created: this is the most important group of metrics, since it indicates, whether an implemented chatbot meets the expectation of a company. The indicators vary differently and depend strongly on chatbots’ functions and utilization. The most common are:Reduce the call center load (one of the most common tasks of chatbots). The metric can count, how decreased hours spent by the employees of the call-center on answering the queries. Since most of the queries in the call center are standard, bots can do them even better than the people.Conversions to purchases rate. It counts the percentage of people whose conversation with a chatbot ended with purchasing of product or service. If bots are used as an online store, then sales are the main metric.Activation rate. One of the advantages of bots is that after they are added to a user's friends, they can sometimes remind them about the business. For example, by reporting new promotions in the store or offering interesting content related to the brand. UTM links can be provided to these messages and target them to users who haven't been on the site for a long time. Based on the results, it’s possible to calculate the percentage of returned users.The growth of CRM. In order to understand whether a chatbot helps the business to expand its customer base or not, it is necessary to track for how many users the chatbot has become the first point of contact with the brand.Increase of the number of brand mentions. To track this metric, it is necessary to track both the mentions of the bot in the media and blogs, and the number of users who have shared the bot on social networks.Metrics that reflect the demand for bot:Number of users. The absolute number of users of a chatbot speaks not so much about its effectiveness, but about the power of the channels, traffic to the site, and the well-thought-out tools that are used to add a bot as a friend to users. However, there are several additional metrics that help to evaluate how well the bot is working:Engaged users: the users who have come into contact with the bot at least once, have responded to its message or written their own. The number of engaged users is measured as a percentage of the total number of people who just added the bot as a friend. In order to evaluate a bot's engagement, it is possible to compare it with the engagement of users in other channels, such as mailing lists or social media advertisements.Active users: the percentage of users who wrote to the bot themselves, and not in response to its next message. This metric reflects one of the main indicators of the bot's effectiveness — its usefulness. If people write to the bot themselves, the service that the system offers is important to them. This metric also correlates with user’s willingness to recommend the bot to friends.Repeated users: the two previous metrics can produce high results simply because people are curious to get in touch with the new technology. However, often the first contact with the bot becomes the last one. Sometimes this is quite enough, for example, if the bot is used to increase brand awareness or to collect user data through a form. But, if the bot was implemented for more systematic and regular use, then low indicators or a drop in this metric is a reason to review the scenarios.The number of read messages. This metric is especially relevant when the bot is used for mailings. For example, to inform customers of an online store about promotions and discounts. It is important to understand that in the field of dialogue commerce, the number of read messages usually exceeds similar indicators for other channels.Metrics that help to understand how effective the dialogues are:The average duration of the session. Depending on the purpose for which the bot was created, this metric can be read in exactly the opposite way. One of the main advantages of bots is their ability to cope with many tasks faster than live operators and users themselves. In such situations, the short duration of the conversation is a good sign, that provides the information about the task completion. In other cases, where bots are created, for example, for entertainment or consultation, it is better when users talk to the bot for as long as possible. These bots are most often used by companies to increase brand awareness or create an emotional connection between the brand and users. Long conversations are also good for media bots, whose task is to engage users in interacting with content.Percentage of errors. Chatbots use natural language technologies and are able to understand messages in normal, natural human language. However, bots often misunderstand people or don't understand them at all. There is nothing wrong with this, since modern dialogue systems protect themselves from errors: they clarify, ask again, or transfer users to live operators in case of misunderstanding. However, it is important to measure the number of errors, track them, and teach the bot to understand the queries, where it has problems.Goal Completion Rate (GCR). Any conversation with a chatbot is dedicated to achieving a certain goal. This can be a goal set by the user (for example, to top up your balance or get an answer to a question) or a goal set by the company (for example, to convert the user into a buyer or persuade them to share the content). The chatbot management system should be able to track the achievement of goals. Analysis of this data helps business to find the moments when the conversation is interrupted, although the goal has not been reached. These points are worth paying attention to and rewriting the script.1.2.2 Chatbot business functions and industry examplesThe scenarios for chatbot implementation can be analyzed from different perspective. For example, it is possible to look and analyze the communication of a person in an ecosystem. From this point of view, it is possible to describe scenarios in such a way:Business-to-Business relationshipBusiness-to-Consumer relationshipConsumer-to-Consumer relationship;Business-to-Employee relationship;Employee-to-Employee relationship.Another way to analyze the directions of chatbot implementation in business is to match them with the specific business functions, the examples of which are shown in the Table 4:Table SEQ Table \* ARABIC 4 Business functions served by the botsDepartmentBusiness functionCustomer serviceProviding answers to frequently asked questionsResolving some of customer queriesMarketingProviding personalized recommendationsBetter understanding of customersSalesSupporting CRM systemsActing as a personal sales assistant/consultantAttracting new customersHuman ResourcesControlling productivity and satisfaction of employeesProviding answers to common HR-related questionsCompleting transactional HR servicesCreating expense reportsProviding help in internal training processesITProviding answers on “IT helpdesk” questionsSupply ChainProviding actual inventory levelsTracking the present status of a shipmentChatbots are also used in many different spheres and industries for different purposes. It is not that simple to list all the industries with specific examples, so the most general cases were highlighted:In finance, banking and insurance: for simplifying operations (clients can manage simple tasks autonomously), for client support (providing personalized help in real time), for internal training and support (simplifying the most complicated and time-consuming tasks). Most of the trends in banking and fintech industry advise focusing at making the conversations shorter, so usually bank chatbots provide simple solutions, such as send/receive money, check the balance, request a statement or find an ATM (Przegalinska et al., 2019). Many Russian banks use chatbots for customer support, for example, Sberbank and Alfabank. Also, it is possible to combine a chat bot with a voice assistance, since both have a similar technological basis. For example, Tinkoff Bank has developed a voice assistant Oleg (most likely named after Oleg Tinkov – the founder of the bank). Oleg not only helps the clients with financial operations – transfers, deposits etc., but can also serve as a private concierge – book tables, buy tickets, search for discounts and so on.In retail and e-commerce: for client experience improvement (satisfaction of all types of client’s requests on all stages of interconnection), for shopping journey improvement (personalized recommendations, purchase help), for personalized marketing (better understanding of user needs and behavior due to collecting and analyzing of personalized data). For example, McDonalds chatbot helps customers to find the closest restaurant and to navigate through the menu. In general, the growth of online shopping over the past 20 years has trained the consumers to make purchases without directly viewing or touching the item. The development of AI, accessing all relevant data in the infrastructure and computing capabilities to analyze this data has created a new type of consumers. Bots in Amazon, Ebay and other online giants can make purchasing decisions that are optimal based on the requirements, preferences, and budgets of their users. Retailers and manufacturers who work with direct customers no longer need to worry about customers whose decisions often depend on emotional responses and are limited by a lack of time and cognitive abilities to make the best choice (Klaus, Zaichkowsky, 2020).In telecom: for solving technical issues, for sales increase (personalized supply), for increase of productivity of employees (solving simple, repetitive and time-consuming tasks). A chatbot is a great opportunity to significantly reduce the quantity of customer requests in telecom. Many internet providers and mobile operators use chatbots in customer support.In energy and utilities: for client support, for client retention (stronger relationship through transparent and simple information about user plans, etc.), for management of installation and maintenance processes. Delivering fast and 24/7 support to the customers is important for energy providers, e.g. British Gas uses a chatbot for simple tasks such as submitting meter readings. That is highly appreciated by a number of customers, who don’t like person-to-person communication about simple everyday problems.In automotive: for increase of customer engagement, for personalized supply (based on budget and needs), for other services. A suitable example is the BMW virtual assistant, operating in Russia. The bot, working both in Facebook and VK, guides the customer through the process of car selection, without using the (sometimes rather complicated) constructor on the website. The assistant can also schedule a test-drive or navigate the user to the closest dealership center.In media and entertainment: for game experience transformation, for unique personalized content, for better conversion. For example, CNN has a chatbot at various platforms, designed to deliver personalized news.In smart home and internet of things: for managing home devices and smart vehicles. A conversational bot can act as an assistant in managing all smart home systems. The term “digital butler” is often used in the literature. According to Gentsch, a digital butler is “a program that is integrated in a technical device, an operating system or an app, and which can take over daily tasks such as shopping, bookings, bank transactions, planning or regulating light and temperature. With time, the personal butler gets more familiar with his owners and can predict their wishes and needs” (Gentsch, 2019, p.98). Every year, home management systems are becoming cheaper and more accessible, and their variety is expanding. Customizable comfort is becoming one of the leading themes in marketing. More and more manufacturers, including Xiaomi, Ikea and Philips, are producing easy-to-use devices for controlling light, heating and security in a private home. The demand and desire to manage this system dictates the need for a virtual butler – customizable and trained to comfort of each individual client.In travel and tourism: for recommendations based on preferences, for increase of loyalty (personalized offers), for client support. For example, Aviasales has a powerful chatbot in almost all popular social media and messengers (Facebook, Telegram, Viber etc.). The chatbot searches tickets, manages route subscriptions, alerts about price changes etc. and basically can minimize the customer’s interactions with the Aviasales’s website itself.In the second paragraph of the first chapter it was described how chatbots are applied in businesses. By answering the stated questions, it was described how chatbots deliver value to the business and how it is possible to measure their success, which business roles and functions chatbots can take over and in which industries they are widely used. These answers again prove the relevance of the topic and the importance of bots in business. All in all, the first chapter gives us an overview of the most important aspects about chatbots: both theoretical and practical. Chatbots are actively used across all industries and business levels, so it is interesting to search for its implementation directions in the existing company.Chapter 2 Chatbot implementation proposals for MTS2.1 MTS: description and historyThis part of the work is dedicated to description of MTS as a company, its position on the market and main operational directions. For these purposes the following questions are stated:Q1: What is MTS now? What do they do and what are their main business intentions?Q2: How did their development look like?MTS or “Mobile TeleSystems” is one of the leading companies in Russia providing mobile and fixed-line telephone services, Internet access, cable and satellite TV broadcasting, digital services and mobile applications, financial and e-commerce services, as well as converged IT-solutions in the field of system integration, Internet of things, monitoring, data processing and cloud computing. MTS makes a significant contribution to economic growth and improvement of life quality of lots of people in the countries of presence by providing innovative services and solutions.In Russia, Belarus and Armenia, MTS Group totals 86.9 million users (see Figure 2: 79.1 million in Russia, 5.6 million in Belarus and 2.2 million in Armenia). In the countries where MTS group operates, it provides mobile communication services in GSM, UMTS and LTE standards.Figure SEQ Figure \* ARABIC 2 Number of MTS subscribers in 2019On the Russian Telecom market, MTS is a traditional leader in key mobile business indicators: the number of users (see Figure 3), revenue and OIBDA.MTS provides fixed telephony, broadband Internet access, and digital cable television services in more than 200 cities in all regions of Russian Federation. In total, more than nine million households are covered by MTS fixed services. The largest fixed-line operator of the MTS Group is ?Moscow city telephone network? (?MGTS?), which serves more than 1.9 million households using GPON technology with data transfer speeds of up to one Gbit/s.Figure SEQ Figure \* ARABIC 3 Comparison of the number of subscribers among Russian providersMTS, through its 100% subsidiary, JSC ?RTC?, owns Russia's largest non-food retail network, having 5,800 communication shops for customer service, mobile device sales, and financial and banking services.MTS is actively diversifying its business and developing new directions. The company, controlling 95% of ?MTS Bank's? capital, provides banking and financial services in electronics stores, financial services and applications on mobile devices, and also operates in the investment services market, being a part of in the capital of ?AFK Sistema?, one of the largest investment companies in Russia.MTS is expanding into new markets through M&A: it has a controlling interest in ?LiteBox?, a developer of cloud-based ticket offices for corporate clients; it owns two leading Russian ticket operators in the market of cultural and entertainment events - ?Ponominalu.ru? and ?Ticketland.ru?; invested in one of the world's leading eSports clubs, ?Gambit Esports?, and one of Russia's largest online services, ??, an online marketplace for workers solving household and business problems.Together with ?Medsi Group?, one of Russia's leading private medical clinics, MTS launched a telemedicine platform for online consultations with doctors, and a ?Smart University? platform for distance education based on its own corporate University.Through its 100% subsidiary, JSC ?Envision group?, MTS provides system integration and IT outsourcing services to meet the demand of the corporate and public sectors for comprehensive Telecom and IT solutions.Today, transforming into an IT company, MTS, along with the corporate networks and broadband, supplies corporate clients with various solutions in the field of the Internet of things, automated management, data collection, processing and storage, monitoring, navigation, security, information security, electronic document management, as well as cloud services under the ?#Cloudmts? brand based on ten own data centers.MTS is the leader machine-to-machine connections sector (M2M) in Russia with the largest (42%) market share by number of SIM cards. The company was the first among еelecom operators to deploy a аederal network for the Internet of things in the NB-IoT standard.With its strong IT expertise, MTS expands the digital ecosystem of OTT, IP, and cloud services: today, more than 15 million users use MTS branded mobile apps.To research promising areas and accelerate the launch of new products and services, the company has an innovation сenter that unites specialists from the MTS Group. The company works closely with the world's leading manufacturers of telecommunications equipment and software, testing and implementing new 5G and IoT technologies.MTS is one of the largest Russian employers in Russia. The Group's companies employ more than 65 thousand people in their markets of presence, and MTS in Russia employs about 27 thousand people. The company is traditionally in the top 5 of the rating of the most attractive Russian employers.In 2019, MTS became number one in the Russian mobile market in absolute terms of total revenue, mobile business revenue, and OIBDA — these figures were 448.1 billion, 312.6 billion, and 209.2 billion rubles, respectively. MTS group's consolidated revenue increased by 8.4% in 2018 to RUB 480.3 billion, while adjusted OIBDA increased by 22.9% to RUB 220.9 billion.MTS is one of the blue-chip companies on the Russian stock market and is one of the largest mobile operators in the world by the size of its subscriber base. Since June 2000, MTS shares have been listed on the New York stock exchange under the code MBT. The largest shareholder of ?MTS? PJSC is ?AFK Sistema?, owning 55.64% of the operator's shares (together with its controlled companies), while the remaining 44.3% of the shares are in free circulation.The history of the company development is shown in the Table 5:Table 5 MTS development historyYearStage1993Company formation1994MTS started its commercial activity in Moscow1997MTS began the regional expansion in Russia2000NYSE IPO exceeds $ 350 million for financial expansion in Russia and CIS countries2001MTS subscriber base exceeds 2 million users2002CIS expansion and launch of operations in Belarus2003Acquisition of the leading Ukrainian mobile operator UMS2004Acquisition of the leading Uzbek mobile operator Uzdunorbita2005Acquisition of the leading Turkmen mobile operator BCTI2006Total rebranding of the company2007Acquisition of the leading Armenian mobile operator VivaCell2008MTS enters into a strategic partnership with VodafoneMTS obtains a license for building an UMTS network in Russia2009MTS starts to develop a single-brand retail network2010MTS purchases a number of regional broadband and KTV operators and starts to consolidate its fixed assetsSuspension of activities in TurkmenistanLaunch of the first LTE network in the CIS in Uzbekistan2011MTS signs a Memorandum with SkartelMTS participates in the Union of LTE operatorsMTS completes the merger of OJSC "Comstar"2012MTS obtains frequencies and a Federal license to provide LTE communication services in Russia and launches its own network in MoscowAcquisition of Tascom and resuming operations in Turkmenistan with about 1 million of subscribers by the end of the yearMTS signs an indicative offer with MTS Bank and Sistema AFC to acquire 25,095 % of the authorized capital in MTS-Bank OJSCSuspension of activities in Uzbekistan2013MTS enters an agreement between Altimo, MTS, Nomihold Security Inc. and other related parties to settle disputes related to investments in Bitel LLC, the former largest mobile operator in KyrgyzstanMTS approves the new version of the MTS dividend policy2014MTS presents a new "3D" strategy, the main focuses of which are "data", "differentiation" and "dividends?2015MTS enters into a strategic partnership with Vodafone in Ukraine and rebrands "MTS Ukraine?2016MTS enters the tower infrastructure rental market: creating a new business to manage and further monetize assets2017MTS enters new markets: cloud services market for large businesses, services for cloud processing of large amounts of data, launching their own IoT platform for deployment of the Internet of things in enterprises, etc.2018MTS creates a digital ecosystem for customers2019MTS approves a new business strategy until 2022, focused on creating a digital ecosystem based on the main telecommunications business and continuing investment in promising growing areas2.2 MTS: main goals and ecosystem descriptionIn the previous part different business directions of MTS were described. It is seen that the company, starting more than 20 years ago, has come a long way. The whole development of MTS was connected with the telecommunication industry and it is difficult to argue with the fact that it has achieved a great success there. But currently it is obvious that MTS is not only about telecom, it surely can go further. That is why this paragraph aims to understand how the future of this company looks like by answering the following questions:Q1: What are the main goals of the company?Q2: Do it already has its own ecosystem and what does it look like?The answer for the first question can be taken from MTS Annual Report, since there can’t be more reliable resource for it. In the report it is stated that the most important strategic priorities of the company are:MTS Strategy CLV 2.0;MTS Ecosystem and radical transformation of the business model.In 2019 MTS presented their new strategy for 2020-2022 years – Client Lifetime Value 2.0 (CLV 2.0). The previous strategy of MTS was ?3D? ("Data, Digitalization, Dividends") aimed at strengthening MTS leadership on Russian telecom and IT markets by increasing the penetration of data and mobile Internet services, promoting innovative digital and converged solutions for a wide range of users, improving the company's operational efficiency and investment attractiveness for shareholders. BY implementing the "3D" strategy, MTS built LTE-Advanced and LTE-Advanced-Pro mobile networks with peak data transfer speeds of up to 700 Mbit/s. In 2018, the company introduced the first commercial 5G technology solutions: it launched a network with LAA technology support to access speeds of up to 979 Mbit/s, and in a number of Russian cities — a network based on Massive MIMO technology. MTS is developing its own transport infrastructure, with a network of fiber-optic communication lines extending over 226 thousand kilometers in Russia.The new CLV 2.0 strategy details the existing strategic goals of MTS and is focused on creation of an ecosystem based on the main telecommunication business with a seamless transition between services.Clients: MTS aims to provide their customer with the best customer experience basing on seamless and comfortable transition between digital storefronts and products by applying deep personalized approach based on artificial intelligence, big data analytics and a single customer ID.Lifetime: MTS wants to focus on a long-term relationship with the client, on increasing customer loyalty and emotional attachment to the brand, including through socially and environmentally responsible actions of the company.Value: MTS wants their clients to consciously receive the benefits from being in the ecosystem. They aim to develop a convenient technology platform for effective interaction with partners and a better customer experience.Before describing an ecosystem of MTS, it is important to understand what an ecosystem is in business terms. The concept of a business-ecosystem firstly appeared in the article, written by James F. Moore and published in Harvard Business Review in 1993. The original definition comes from Moore’s book, where he defines a business-ecosystem as “An economic community supported by a foundation of interacting organizations and individuals — the organisms of the business world. The economic community produces goods and services of value to customers, who are themselves members of the ecosystem. The member organisms also include suppliers, lead producers, competitors, and other stakeholders. Over time, they?coevolve?their capabilities and roles, and tend to align themselves with the directions set by one or more central companies. Those companies holding leadership roles may change over time, but the function of ecosystem leader is valued by the community because it enables members to move toward shared visions to align their investments, and to find mutually supportive roles” (Moore, 1996). Moore defined this term as dynamically developing communities that interact and compete in order to create new value for their customers and for themselves, which means that the creation of ecosystems brings strong advantages both for the companies and for their customers. More than 20 years have passed since the book was written, and the world has also changed significantly during that time – especially in technological terms. There are now many companies all over the world, which have created their own business ecosystems, but the main question here is how it became able to reach this goal? Companies now operate in the quickly changing and more diverse than ever business environment. This environment, in its turn, goes through a digital transformation process, which is a profound transformation of business models, activities, processes and competencies for fully leveraging the changes and opportunities of digital technologies. The rate of development of digital technologies suggests that the ecosystems created by companies are not just business ecosystems, but the digital ones. One of the most important prerequisites for creation of such ecosystems by companies is the business digitalization or, in other words, ubiquitous access and use of data and of digital technologies for conduction of business processes. Having that access, companies prefer a digital business model and try to use digitized processes, based on digital form of analogue data and information. Players interact with each other by using digital platforms, which is a collective environment supporting the customer experience and multiple solutions. Digital platforms become a trusting environment for collaboration. All these terms make it possible for large companies to create their own ecosystems.For MTS development of company’s own ecosystem is now the most important strategic task. MTS wants to turn into a group of businesses that will become a complete ecosystem with a single user experience. By ecosystem the company means united around a single company set of proprietary or partner products and services from completely different industries, where each product or service supports the business of the company. MTS builds its ecosystem in such a way, that it will allow to address as many of the customer’s daily needs as possible. The services and the industries, where company operates, are the building blocks of the ecosystem. The cement of the ecosystem is the single client ID, which allow to increase customer engagement, to collect their data and use it later for promotion of the products or in advertising services. However, it is important to mention, that the clients can’t be forced to use any identifiers and involved in the ecosystem, if there is no additional value of being a part of the ecosystem for themselves. Value occurs when all products and services are integrated with each other, and the entire system works as a single unit.The core of MTS ecosystem are several functional subsystems: end-to-end customer identification, use of Big Data and shared sales channels, loyalty management and customer communications. There are two factors that indicate an ability of MTS to create an ecosystem:MTS has unique knowledge about tens of millions of people in Russia (more than 100 million of subscribers in 2018). This is an essential asset for cross-selling, and its value is constantly growing.As a large Russian company, MTS can become an accelerator of product assets, because Russian market is isolated from global competition and, also, because it is difficult for small and medium-sized companies to find and get funds for development.MTS believes that creating of its own ecosystem is the way to keep their position on the market. The competition between ecosystems in Russia already exists, and companies, that seek to control the entire value creation vertical or try to link several verticals are beginning to dominate. First of all, the company wants to complete the creation of the ecosystem, to create operational links between business lines and centralized infrastructure and to launch new cross-selling mechanisms, so that customers positively evaluate unusual offers from the MTS brand. In the end, they want to become a love-brand, where customers trust any of their services due to the high quality and convenience of use, and to achieve high cross-sales results, - that is a deep penetration of completely different products and services into the MTS subscriber base and a significant number of customers, who will enjoy the products and the services of the MTS ecosystem, even if they are not the users of their basic product, mobile communication.The business model of MTS suggests the following scheme of work:the operation in the main telecommunication business, where MTS has a large market share, helps them to generate cash flows;one part of the generated cash flow goes for the payments to shareholders and maintenance on the high level;the other part of the generated cash flow goes for the reinvestments, where the company focuses on investments into infrastructure, digitization of business and investments into new areas and industries.The current ecosystem of MTS together with the industries and services on which it is built are described on the Figure 4. The availability of these services is shown in the Table 6.-5365754309745Figure 4 MTS Ecosystem descriptionFigure 4 MTS Ecosystem description-536927251529MTS EcosystemMedia & EntertainmentMTS LiveMTS LibraryMTS MusicMTS TVWASD TVFinancialMTS BankMTS MoneyMTS InvestmentsMTS InsuranceHealth120/80MTS FitnessSmartMedMTS CashbackChildrenMTS.RazvivaykaEducationSmart UniversityCommunicationsMy MTSMTS ConnectMTS SearchMTS Who callsMTS GOOD’OKMTS EcosystemMedia & EntertainmentMTS LiveMTS LibraryMTS MusicMTS TVWASD TVFinancialMTS BankMTS MoneyMTS InvestmentsMTS InsuranceHealth120/80MTS FitnessSmartMedMTS CashbackChildrenMTS.RazvivaykaEducationSmart UniversityCommunicationsMy MTSMTS ConnectMTS SearchMTS Who callsMTS GOOD’OK-482487617767TechnologiesMTS Second memoryKaspersky Security for MTS00TechnologiesMTS Second memoryKaspersky Security for MTSTable SEQ Table \* ARABIC 6 The availability of MTS services on different platformsIndustryServiceWebiOS appAndroid appMay be used only by MTS mobile subscribersCommunicationsMyMTSMTS ConnectMTS SearchMTS Who callsMTS GOOD’OKMedia and entertainmentMTS LiveMTS LibraryMTS MusicMTS TVWASD TVFinancialMTS BankMTS MoneyMTS InvestmentsMTS InsuranceHealthMTS 120/80MTS FitnessSmartMedTechnologiesMTS Second memoryKaspersky Security for MTSChildrenMTS.RazvivaykaEducationSmart UniversityMTS CashbackCommunication services are the most common in the ecosystem of the company. The main application is MyMTS – a mobile personal account for the operator's subscribers, which saves the users from visits to the operator's shops and calls to the call-centers, since most of the questions, that arise from subscribers, can be solved by using this application. MTS Connect is an application for online calls to any number including landline, short or other operator. MTS Search allows to track the location, movements, and phone status information of family and friends. MTS Who calls provides customers with the information about the unknown numbers of incoming calls and detecting spam calls. MTS GOOD’OK suggests setting the ring tone by choosing from the large base of music. All these services are available through mobile applications, both for iOS and Android.The other industry that is introduced with a large diversity of services is Media and entertainment. The MTS Live service allows to choose cultural events, buy tickets and ger personalized selections of events. This service is currently available only in Moscow and through the website. MTS Library is an online library with books, audiobooks and magazines in one application designed for iOS and Android. MTS Music is the iOS and Android application, which provides access to the MTS music portal and the ability to listen to any music on the device. MTS TV is a convenient app for watching movies, TV series, cartoons, and television programs online on a smartphone, tablet via iOS and Android based applications, TV and computer via the website. Streaming platform for gamers and eSports players WASD TV provides them with Streamer League, tournaments, broadcasts and games. The platform has free traffic for MTS mobile subscribers.Financial industry is introduceв, first of all, with MTS Bank, which exists since 1993 and provides services for private clients, corporate clients and small businesses. The bank is online, so the access to it is realized through the website and applications designed for iOS and Android. Another financial service provided by MTS is MTS Money, which is also realized through the site and mobile applications designed for iOS and Android. This service helps customers to conduct fast payments and transfers. MTS Investments suggests investing in mutual funds and track your returns in the application designed for iOS and Android. MTS Insurance together with VSK insurance house offers to purchase travelling or mortgage insurance through the website.Health industry suggests three different services: MTS 120/80, MTS Fitness and SmartMed. MTS 120/80 is a free application for controlling the work of a cardiovascular system with the ability of keeping a diary of pressure, monitoring changes in weight and cholesterol levels and learning about the risks of a heart disease. The application is available both for iOS and Android. MTS Fitness is an application that by subscribing suggests individual nutrition and training programs and is also available for iOS and Android devices. SmartMed is the mutual project of MTS and network of clinics MEDSI. It provides clients with distance medical consultations with the ability to choose the time and date of the consultation and to talk with the doctor in chat or bi video-call. The application is also available for iOS and Android.Technologies are introduced by two services: MTS Second memory, which is based on the cloud technologies and allows the customer to save and protect their contacts, photos, videos, important files in the case of the smartphone loss, and Kaspersky Security for MTS, which is a specific version of the same application designed by Kaspersky Lab for MTS.MTS also has one service, totally dedicated to Children. MTS Razvivayka is a full-fledged entertainment service, including cartoons, books, audio stories and games and available on the website and in mobile applications.Education industry is introduced with Smart University online platform. The platform suggests distance individual classes of English language both for children and for adults and Mathematics for the preparation for the state exams. The platform is available on the web and in the applications designed both for iOS and Android.There is one more service, that can be seen as the main one, since it acts as a strong link between the other services. It is MTS Cashback, which allows to accumulate bonuses by using MTS services and by purchasing goods from the partner shops. What is more interesting – this cashback can be received and used not only by MTS subscribers, but by the subscribers of other operators too. The bonuses may be spent:to pay for mobile connection, home internet and TV, entertainment services and applications;to top up the balance of MTS number of family members or friends;to purchase products in MTS retail shop.To conclude, by answering the questions of the second paragraph the main strategic priorities of MTS were highlighted. The first one is the new strategy of the company, that makes emphasis on clients, long relationship and value. The second and very important is development of an ecosystem and becoming a huge IT company as a result.2.3 Chatbot implementation directions for MTSSince one of the main strategic priorities of MTS is development of their own ecosystem, which contains of many different services and directions, it is obvious that the company attempts to bring all the services to the high-quality level. One of the most important steps in this process is to take care about customer experience and customer journey of using the particular service. As it was already described in this work, chatbots help to level up the user experience. This paragraph aims to describe several directions or MTS services, where a chatbot can be implemented and to choose one of the described services for MVP creating in the next chapter. For this purpose, five examples of chatbots are introduced.MTS Cashback service brings one of the most important benefits to company’s ecosystem. It performs like a link between the MTS services by providing the customers with bonuses for purchases. These bonuses impact the cross-sales within the company.For MTS Cashback a machine learning-based bot can be created and implemented. The bot can navigate the customer through the ways of cashback accumulation and expenditure. It can count and plan bonuses by answering on such user questions, for example:What is the current balance of bonuses?How the customer can spend the specific number of bonuses?How the customer can accumulate the specific number of bonuses?For answering these questions, especially about the way of spending bonuses, that bot can use a recommendation system, which will help it to suggest the plan that will fit the preferences of certain customers and, thus, provide them with more personalized plans of expenditures.MTS Live is an e-ticketing service, that by working in a partnership with the main ticket aggregators occupies a significant part of the market. MTS considers this service as very promising one and plans to develop it further. The service provides customers with the information and tickets on such types of events as: cinema, theaters, shows, concerts, children events, festivals, museums, exhibitions, seminars, musicals and excursions. MTS Live is, of course, not the only one on the e-ticketing market and has such large competitors as Bileter.ru, Kassir.ru, Afisha.ru, etc.For MTS Live service a very interesting and non-trivial chatbot can be created, since the service itself is connected to entertainment and leisure. Here chatbot can create a really valuable customer engagement by providing an easy and effective way of searching through the large amount of different entertainments, helping customers to make their choice and becoming their own entertainment organizer.MTS Library is a service that provides a collection of electronic books, audiobooks, digital magazines. It has its own application, where a chatbot can be implemented. The bot can search for a specific book by specified parameters and sent it to the user, help to choose what to read and also, based on a recommendation system, make personalized suggestions for the customers that fit their preferences. Bot can also send news about new books and notifications for the customers not to forget to read. 120/80, an application that helps to control the work of a cardiovascular system, can also have its own chatbot, that may send users the health reports based on the data from them, provide users with some suggestions and recommendations based on the result of the reports, notify users, if some significant changes are seen in their personal dataand so on. This bot can provide a personalized and dedicated relationship with a customer by giving an important information about certain health concerns.MTS Fitness service provides users with training and nutrition plans. The bot in this service can help it to become more personalized and to answer the specific and instant requirements of customers. It can correct current plans by request. The customer may want to deviate from an existing plan due to different reasons like hurting of some body part or pain. The bot can select the exercises and food by the specified restrictions.For further development of a business model and MVP MTS Live service was chosen due to several reasons:media & entertainment is very interesting and diverse, so different things can be created and suggested for the development of customer experience;MTS wants to develop this service in order to continue their participation in the e-ticketing market competition;the volume of the Russian ticket market according to various estimates of industry representatives, is from 45 to 60 billion rubles a year, excluding the cinema segment; moreover, according to PwC's forecast, the industry will grow at an average annual rate of 7.2%.Summing up the second chapter, the development of MTS company has been looked through with the precise description of the current directions for further development of the company. It is obvious now, that MTS is no longer just a telecommunication market player, but, surely, a candidate to become an IT giant. Their current strategic priorities fully comply with their goals and intentions. MTS puts a strong emphasis on the development of their own ecosystem. They have already reached some goals in that, but there is also a lot to be done. Chatbots may help company to achieve their goals by improving customer experience and engagement. Some examples of possible chatbot implementations are described and one of them -MTS Live Chatbot - is chosen for further MVP development.Chapter 3 MTS Live Chatbot proposals3.1 Business model designing for MTS Live ChatbotAs it was stated in the end of the previous chapter, for more detailed analysis and development of proposal was chosen MTS Live service. The first paragraph of the third chapter aims to design a business model for the chatbot of this service. The paragraph is divided into four parts, where in the first part the tool for model designing is described, in the second part – a business model for MTS Live Chatbot is created, in the third part – a specific value for the developing service is described and proposed, and in the fourth part – chatbot scenarios are described.3.1.1 Strategyzer Cloud service for business model designingFor designing the business model for the purposes of this work the Strategyzer Cloud service was chosen. There are three reasons for choosing this service: firstly, this service suggests the tools for designing a business model canvas and a value proposition canvas, which are one of the best ways to build a business model; secondly, this service is developed by the creators of a business model canvas, what confirms its relevance; thirdly, it provides an ability for a mutual work on a project.This service suggests an online platform, where it is possible to create different business projects and design business models for each of them. It makes the process really easier and faster, since the canvases are already formed – it is necessary only to choose the needed one. Strategyzer helps to make the process of designing a business model more available and interesting.3.1.2 Design of Business Model Canvas for MTS Live ChatbotOne of the best ways to get an understanding of how the product will work is to describe its business model. Business model can be defined as the description of the articulation between different business model components or building blocks to produce a proposition that can generate value for consumers and thus for the organization. For describing a business model Business Model Canvas should be used. It is a visual chart with nine building blocks: customer segments, value propositions, channels, customer relationships, revenue streams, key resources, key activities, key partnerships and cost structure. The Business Model Canvas for MTS Live Chatbot is shown on the Figure 5.Figure SEQ Figure \* ARABIC 5 MTS Live Chatbot Business Model CanvasCustomer segments building block helps to define the groups of people that the company aims to reach. The segments can be assigned, for example, by common needs or common behaviors of the customers. In the case of MTS Live Chatbot customers are people who are interested in the organization of their leisure time, who like different kinds of entertainments and who live in Moscow, since the service is now available only there. In other words, it is a mass market, since it is hard to distinguish between different customer segments. The value, given by the product, focuses on a large group of customers with the same needs. It is possible to assume that, for example, people from 16 to 35 years old are more likely to search for the events, but it is really hard to highlight the specific segments by socio-demographic features. The average socio-demographic portrait of the customer will strongly depend on the type of the event (more young people tend to visit concerts more often than theaters, while the elder ones – vice versa) and on the type of the channel (Telegram has younger audience than WhatsApp). Thus, more precise highlighting of the specific segments is a full-fledged independent task.Value propositions building block helps to define the value creators, specific products and services, for each of the customer segment. By satisfying customer needs value proposition performs not just as a bundle of products or services, but as a bundle of benefits, which customer gets in order of choosing the particular product or service. Value proposition is one of the most important blocks in the business model of the company because it should always have something innovative and unusual: either in the product or service itself, or in their features. There is even the separate Value Proposition Canvas, which helps to determine more accurate the values of the products or services. The uniqueness of MTS Live Chatbot is that, in fact, it is the first chatbot for such services, at least among competitors, in e-ticketing. As was mentioned in the Chapter 1, a chatbot brings more customer engagement, which means, that users have better user experience talking to a bot, while they are using the service. Thus, value proposition of MTS Live Chatbot is not only to help customer solve their needs in the organization of their leisure time, but to do it in more quick, efficient and customer-friendly way. The Value Proposition Canvas for MTS Live Chatbot will be described in the next part of this paragraph. Channels building block helps to define the ways, by which a company communicates with its customer segments and delivers its value propositions to them. For MTS Live Chatbot, due to the specifics of chatbots, three types of channels can be distinguished:website () – currently the website is the only channel of MTS Live service, chatbot can be implemented to it;mobile application – it doesn’t exist now, but in the long-term MTS plans to develop it, so chatbot can be implemented there too (both for iOS and Android platforms);messengers – the most widespread in the region of presence messengers should be used for chatbot implementation, these are Telegram, WhatsApp and Viber.The website and mobile application are own direct channels, that reach customer segments through the web sales. Messengers are more likely to be partner indirect channels. Customer relationships building block helps to define the type of relationship that is established between the company and each of its customer segment. In the case of MTS Live Chatbot two types of the relationship are used:self-service relationship is about no direct relationship between the service provider and the customer, since everything is done in such a way, that the customer can solve any problems themselves;automated services relationship, as self-service relationship, provides the ability to the customer to do everything without any connection with the company representatives, but, besides, it identifies the clients (for example, by ID or by the behavioral patterns) and provides them with specific and personalized recommendations.Revenue streams building block helps to represent the cash generated from each of the company’s customer segment. The revenue in the case of MTS Live Chatbot, as well as in the MTS Live service itself, is generated from the commission that is taken from the event providers.Key resources building block helps to define the crucial assets, without which the company won’t work. All types of resources are taken into account: physical, intellectual, financial or human. For MTS Live Chatbot such resources can be highlighted:Human resources: software developers/solution designers/user experience designers/testing analysts (people who develop the platform and later maintain the quality of its work), data analysts/data scientists/data engineers (people who develop and later constantly improve the recommendation system used in the service), product managers/product owners (people who are responsible for the progress of the product), operational managers.IT infrastructure: website, mobile applications, conversation technology platform.Data base: conversational big data, speech big data, training big data.Client base: all subscribers of MTS mobile connection and users of other MTS services at the start, new clients over time.R&D results in AI.Key activities building block helps to define the main actions taken by the company in order of the successful operation. In the case of MTS Live Chatbot the key activities are:chatbot development & maintenance;data gathering & analysis – personal conversational profiles creation for better understanding of clients and for building of the recommendation system;product management;R&D.Key partnerships building block helps to define the network of partners and suppliers. Partnerships can be created by non-competitors, competitors, for development of new businesses, for assuring of reliable supplies. In the case of MTS Live Chatbot key partnerships are:Ponominalu.ru – the ticket aggregator service that was bought by MTS;Ticketland.ru – another ticket aggregator service that was bought by MTS;Rambler Kassa – the partner service for cinema tickets sales;online payment systems like Visa, MasterCard, MIR, ApplePay, GooglePay, SamsungPay;event providers of all types of entertainments offered by the service;AI and ML conversation technology providers.Cost structure building block helps to represent all costs that are taken for business to operate. The main costs of MTS Live Chatbot are:salaries;IT infrastructure maintenance;asset management;R&D;marketing cannibalization – the creation, for example of a Telegram chatbot (which will be described later in this chapter) will steal the users of MTS Live website, the only current channel of the service, and reduce its sales volume by that.3.1.3 Design of Value Proposition Canvas for MTS Live ChatbotAs it was already mentioned, value proposition is one of the most important blocks of the business model. It allows you to set the business apart from the competitors, to highlight its strengths and fix them in the minds of consumers. Value proposition is a succinct statement of an informational message that contains all the value of the product and brand. For the development of value proposition, as well as for the business models, a specific canvas is used – Value Proposition Canvas. This canvas consists of two parts: customer profile and value model. Each part is divided into three blocks that describe specific features of the client or the product. Best of all is to create a value proposition for each of the selected customer segments in Business Model Canvas. Since in MTS Live Chatbot Business Model Canvas there is only one customer segment – there should be only one value proposition. For better design of Value Proposition Canvas a small survey was conducted among proactive audience, who use such services for an organization of their leisure time.Customer profile, the first part of the Value Proposition Canvas, helps to describe specific customer needs, which should be solved by appropriate value proposition. Customer profile contains of three parts. In the case of MTS Live Chatbot it looks like this (see Figure 6):Figure SEQ Figure \* ARABIC 6 Customer profile of mass market segmentJobs to be done (which tasks the customer is trying to solve by using the service):search for an appropriate entertainment or event in order to find a way to spend their leisure time;compare several events by some features, if it is hard for them to choose from the first glance;purchase tickets for a chosen event using online payment tools;get personalized recommendations and suggestions based on the preferences;create individual weekend/week/month plans;solve technical issues and problems related to the work of the service.Pains (and fears, negative aspects of using the service, which customers try to avoid):high commission which is often taken from the customers by ticket aggregators;poor choice of events not indented for a wide audience;no online payments at all or lack of some their types;compulsion to use different platforms for different types of events;bad interface from both technical and design perspectives.Gains (positive aspects of using the service):bonuses for using the service;notifications which help not to forget or miss a planned event;personalized recommendations that totally fit the preferences of the customers;ability to find everything in one place;absence of technical issues and problems;good customer experience with quick, clear and comfortable interface.Value map, the second part of the Value Proposition Canvas, helps to describe the service from a customer perspective. It also consists of three parts. For MTS Live Chatbot it looks like this (see Figure 7):Figure SEQ Figure \* ARABIC 7 Value model for mass market segmentProducts & services (the list of offered functions that should be realized in the service):bot helps to find specific events from the amount suggested from MTS Live service, and makes ?search for an appropriate entertainment or event? done;bot compares chosen events by specified features and makes ?compare several events? done;bot help to purchase tickets by using online payment systems and makes ?purchase tickets for a chosen event? done;bot sends suggestions and recommendations worked out by the recommendation system and makes ?get personalized recommendations and suggestions based on the preferences? done;bot saves client plans and information about upcoming events, for which the tickets were purchased, and makes ?create weekend/week/month individual plans? done;bot solves technical issues by replacing the call-center and makes ?solve technical issues and problems related to the work of the service? done.Pain relievers (specific features of the service that ease customer’s pains and fears):no commission at all for tickets purchasing relieves ?high commission? pain;differentiated choice that will suit any of different preferences of customers relieves ?poor choice of events? pain;partnerships with the most popular, widespread and comfortable online payment systems relieves ?no online payment? pain;the presence of all types of events relieves ?compulsion to use different platforms? pain;easy and comfortable design relieves ?bad user interface from both technical and design perspectives? pain.Gain delivers (specific features of the service that create benefits for the customers):MTS Cashback program and MTS Premium Program deliver ?bonuses? gain for the users of the bot;event notifications can be set up in order to deliver ?notifications? gain and help customers not to forget about already planned events;recommendation system based on ML helps to deliver ?recommendations and suggestions that totally fit the preferences of the customer? gain;wide choice of events and of their types delivers ?the ability to find everything in one place? gain;easy interface & the ability for self-service issues solving deliver ?the absence of technical issues? gain;high quality user interface delivers ?good customer experience with quick, clear and comfortable interface? gain.3.1.4 MTS Live Chatbot abilitiesAfter designing Business Model and Value Proposition Canvases for MTS Live Chatbot, it becomes possible to create a chatbot proposal by describing its main scenarios. The scenarios of the communication between user and chatbot depend on the particular user’s sequence of actions, but the main are based on the functions suggested by the bot. Thus, the scenarios can be considered as modules, where each module describes a certain function. On the very first step of communication bot suggests choosing the action from the following menu:Search for an eventCompare eventsBuy ticketsGet recommendationsCreate plansSolve technical problemThe first type of communication between user and chatbot develops when the user starts to search for an appropriate entertainment or event. Bot helps to search through a large amount of different entertainments, such as cinema, theaters, shows, concerts, children events, festivals, museums, exhibitions, seminars, musicals and excursions. The user searches for a particular entertainment by choosing its type, time and place. The specific scenarios for this function will be proposed and described later in this work.The second type of communication occurs when the user finds and likes several events and can’t decide for sure, which event to choose. Bot helps to compare several events. Chatbot may suggest more detailed description of the events and their comparison by type, genre, duration, start and end time, location and rating. It provides additional information in order to make the choice easier. The results of the survey showed that the ability to compare will be a gain of the service.The third type of communication develops, when the user has already decided where to go and is ready to make a purchase. Bot helps them to buy tickets for the chosen event with the use of different online payment systems. It is better to implement all main online payment ways to make the customer journeys as much seamless and comfortable as possible.The fourth type of communication is one of the most complicated and sophisticated in terms of realization. For customers, who can’t complete choosing events with the help of first two functions, or for those, who don’t have spare time, recommendations can be implemented and used. Recommendation systems try to predict, which objects will match their preferences. In other words, these systems may suggest exactly such content, that will be loved by the customer. The recommendation systems are created by using big data and machine learning techniques. The privilege of MTS Live Chatbot can be the existence of huge client data base in MTS. On its base it is possible to create recommendations for each of the customer group and then develop them over time by collecting more data from interaction of users with the bot. The idea of the fifth type of communication also occurred after conducting the survey. In terms of speed and variety of life, it is important for users, especially for the proactive ones, to know their plans. Bot helps customers not to forget about their plans. It saves information about tickets purchased through the service and shows it to the customers by request. They may ask to show the plans for a specific day, a weekend, a week or even a month. What is not less important, chatbot also sends notifications before the planned event in order the customers don’t completely forget about their plans.The last type of communication is also very important. By adding this function to the chatbot, company can save their costs – money spent on their call-center. Since MTS Live service works currently as a website, it builds a self-service relationship with its customers, but, nevertheless, all technical issues are solved by calls. Chatbot can perform this function instead of the call-center. Solving customer’s technical issues and problems will be also described later.In the first paragraph of the third chapter the chatbot for MTS Live service was described by designing its business model using the Business Model Canvas and the Value Proposition Canvas suggested by Strategyzer Cloud Service. The scenarios of the communication with the bot were described more like modules that are based on the specific functions of the bot or, in other words, the type of communication established between the bot and the user. 3.2 Creation of MTS Live Chatbot MVPThe second paragraph of the third chapter aims to create an MVP for the described chatbot. MVP is a minimum viable product. It is created with the minimum number of necessary features in order to satisfy first customers and get a feedback for further development.The main features of MTS Live Chatbot MVP are:it is created on the base of Telegram API, so it is a Telegram bot;the bot is created with the rule-based approach, since there was no data to be able to use machine learning-based approach; it contains of two function from the list of described in the previous paragraph: searching for an entertainment and solving technical issues;three types of entertainments were taken for an MVP: theaters, concerts and museums.The whole code of the bot is provided in the Appendix.3.2.1 Preparation for the development of MVPChoice of Telegram as a platform and specifics of working with it For MVP implementation a research of technologies that are used for bots’ implementations was made. As a result, it was figured out that generally bots are based on such technologies of web services as a chat. However, the main idea of the bots is an interface to process the user’s messages via chat bot. In other words, the bot serves as a client software that can read data from users and send some information back to them. Nowadays, there are several popular ways to create bots. Some of these methods imply the interaction with official web interface, which is amazing for users without any developer skill, but these approaches are handicapped due to their limitations. The limitations lead to a poor functionality, or, in other words, developers do not have an opportunity to integrate ML or other flexible features and settings. To use all possible capabilities, we can use an approach used as a unique product or as an additional feature to its product. For instance, a chat assistant for support services. In general, the idea of these products is simple, but can be extremely complicated in implementation, because it leads to the developing of a new architecture. By obvious reason this approach could not be used for described MVP. Fortunately, there is another option, which allows to avoid a complexity of infrastructure creation. This option, provided by chat platforms such as WhatsApp or Telegram, includes an integration with well-developed platform’s API. For example, the API, produced by Telegram, has features allowing to send messages to users, to read the user’s open information and to get all message history from user’s iterations. Having studied all possible options, it was decided to use Telegram bot API.To begin with, Telegram bot API is based on two general interfaces: Webhooks and Long polling. The Webhooks is an interface that interacts with chat messages using a client web server. When the bot gets new data, it sends this data to the server. Thus, this method requires to create a backed side or service, which can get POST requests. The body of the requests is a JSON file with last updates containing none-handle objects with message or callbacks. Despite the advantages of Webhook interface, it requires not only a server, but also an SSL certificate and some other security features, which creates a certain field of obstacles. Fortunately, there is a second interface – the Long polling, which helps to avoid obstacles with security routine. The idea is that, the users polls a Telegram server and check updates, moreover, they can easily move Long polling bot to Webhook in the future. In addition to data interfaces, Telegram created APIs for sending photo, video etc. to the user, which lets the bot interact as a real person in case of ability to share data. Finally, it was decided to use Long polling for the MTS Live Telegram Bot MVP due to its convenience.Choice of programming language, data base type and development approachTo implement the bot or even to interact with Telegram API, it is possible to use a computer language that supports requests interface and multi-threaded computations. In this case the Python language was chosen as a main programming language, due to the amazing API for interacting with Telegram interface. A database, that supports asynchronous requests to provide maximum efficiency, was needed for the bot infrastructure. As it was figured out there are two main types of databases. The first one is SQL-like databases, which are broadly used, but for the case of this work have some disadvantages such as integrity requirement. For some purposes integrity is a good feature, but in the described case events can have different structures, that may lead to useless memory usage. Moreover, a quick database to work by chat scenario was needed, since it was decided not to use cache and other technologies to save time for MVP realization. Second type of databases is the no SQL databases, which save data in JSON format and have an opportunity to store data in RAM, thus providing the users with fast answers. Thereby, the Mongo DB database was chosen. It is one of the most famous no SQL databases. Finally, telebot library was used for convenient work with Telegram API.The main idea of MTS Live Telegram bot MVP was to create a bot, that is able to give recommendations to users. Generally speaking, a real ML was not implicitly implemented in the described bot due to the lack of necessary data for real ML algorithms. However, the recommendations without ML were implemented to show that ML plays a support role and the concept of ML implementation was developed based on the “non-robust” architecture. The inline keyboards were used to implement filters menus. Moreover, almost all user’s communications go through inline interface. Inline architecture in telegram API implies the callback behavior. The core framework (telebot library) helps to track callbacks, so it is not an issue to work with them. However, callbacks have one tremendous disadvantage, which is a lack of the opportunity to transfer data inside itself. That issue can be solved by caching the database. However, caching is a hard and time-consuming process for the described MVP, so this problem is solved through Mongo DB, to have an ability to store date in RAM (can be used as some propinquity of caching simulation). 2368551826895{'_id': ObjectId('5eb02d63316bb90172659f72'), 'adress': 'просп. Пятилеток, 1', 'metro': ['Проспект Большевиков'], 'name': 'Ледовый дворец', 'link': '', 'location': [59.921534, 30.46789], 'districts': ['Невский район','Красногвардейский район','Центральный район']}0{'_id': ObjectId('5eb02d63316bb90172659f72'), 'adress': 'просп. Пятилеток, 1', 'metro': ['Проспект Большевиков'], 'name': 'Ледовый дворец', 'link': '', 'location': [59.921534, 30.46789], 'districts': ['Невский район','Красногвардейский район','Центральный район']}2336803712210Figure SEQ Figure \* ARABIC 8 JSON structure of first three collections0Figure SEQ Figure \* ARABIC 8 JSON structure of first three collectionsIn accordance with the business logic, the databases model was needed for two purposes. The first one was to store the events data and to store/cache user’s preferences. Also, since a way to store user’s requests history in order to sale or use it in the future should be created, a structure of database was invented. It consists of seven collections, six of which can be simply convoluted to two, but making the development processes longer. First three collections have the similar JSON structure and serve to store information about places of events (for instance, theaters). The structure of these collections has the next format (see Figure 8):Second group of three collections stores event information, and has the next format (see Figure 9):4292362067152Figure SEQ Figure \* ARABIC 9 JSON structure of second three collectionsFigure SEQ Figure \* ARABIC 9 JSON structure of second three collections31813541275{'_id': ObjectId('5ebbda10fa9d0dd5cba7c681'), 'date': 'None', 'name': 'Ромео и Джульетта', 'description': 'С. Прокофьев. ?Ромео и Джульетта? Государственный академический театр классического балета ...', 'cost': 'от 800 ?', 'link': '', 'theatre': 'Московский международный Дом музыки', 'picture': 'diploma/a7fba8ff924c4208bf11618b899f2bb3187b9f4a.jpg', 'address': 'г. Москва, Космодамианская наб., д. 52, стр. 8'}{'_id': ObjectId('5ebbda10fa9d0dd5cba7c681'), 'date': 'None', 'name': 'Ромео и Джульетта', 'description': 'С. Прокофьев. ?Ромео и Джульетта? Государственный академический театр классического балета ...', 'cost': 'от 800 ?', 'link': '', 'theatre': 'Московский международный Дом музыки', 'picture': 'diploma/a7fba8ff924c4208bf11618b899f2bb3187b9f4a.jpg', 'address': 'г. Москва, Космодамианская наб., д. 52, стр. 8'}Finally, the last collection is dedicated to the user’s information and serves as a caching machine. The structure of this collection is demonstrated at Figure 10:4330702767330Figure SEQ Figure \* ARABIC 10 JSON structure of the last collectionFigure SEQ Figure \* ARABIC 10 JSON structure of the last collection43307041275{'_id': ObjectId('5ec003b552b6b3484672552b'), 'telegram_id': 278224179, 'chat_id': 278224179, 'name': 'Anton', 'history': {'request': ['Theaters', 'Tomorrow', 'AnyOption']}, 'operations': {'last_db_body': 'Theaters', 'next': [ObjectId('5ebbdae2fa9d0dd5cba7c725'), ObjectId('5ebbdae2fa9d0dd5cba7c726'), ObjectId('5ebbdae2fa9d0dd5cba7c727'), ObjectId('5ebbdae2fa9d0dd5cba7c728')]}, 'theaters': {'passed': [[ObjectId('5ebbdae2fa9d0dd5cba7c6ed'), ObjectId('5ebbdae2fa9d0dd5cba7c6fb'), ObjectId('5ebbdae2fa9d0dd5cba7c717')]]}}.{'_id': ObjectId('5ec003b552b6b3484672552b'), 'telegram_id': 278224179, 'chat_id': 278224179, 'name': 'Anton', 'history': {'request': ['Theaters', 'Tomorrow', 'AnyOption']}, 'operations': {'last_db_body': 'Theaters', 'next': [ObjectId('5ebbdae2fa9d0dd5cba7c725'), ObjectId('5ebbdae2fa9d0dd5cba7c726'), ObjectId('5ebbdae2fa9d0dd5cba7c727'), ObjectId('5ebbdae2fa9d0dd5cba7c728')]}, 'theaters': {'passed': [[ObjectId('5ebbdae2fa9d0dd5cba7c6ed'), ObjectId('5ebbdae2fa9d0dd5cba7c6fb'), ObjectId('5ebbdae2fa9d0dd5cba7c717')]]}}.3.2.2 Description of chatbot architecture and development processGeneral logicBefore describing the deep technical and business architecture of the bot, it is necessary to describe the general logic of the MVP. The described MVP is organized to work with two main branches. The first branch is “Search for events”, which is based on simple structure of consecutive polls (options) or filters. It was decided to use this approach, because it perfectly fits a concept of interaction with the bot and allows to use created code to integrate ML in future if it is needed. The second branch, “Solve technical problems”, serves as a problem solver or an additional call-center.For the first branch or consecutive polls, the inline keyboard was used. That is a feature of Telegram API, which allows to show options through buttons interface. At the first menu, the bot offers the user to select a type of events such as theaters, concerts or museums. Then, at the second step the user can choose time or event. For this step four different options were developed: Now (events in range of 4 next hours), Today (events that are going today), Tomorrow (events on the next day), Specific day (custom filter for any day). Third menu offers to select appropriate location based on the user’s preferences – the user can select events by current location, metro station and district, or skip this filter.After basic filters are formed, the bot asks several questions in case of additional information such as current location or choice of date. Then a special algorithm searches for appropriated events in the database. If the events are found, the user receives 3 recommendations and a menu of the next step. In the next step menu, the user can choose either Next events (allowing to get more recommendation by established filter) or return to main menu. More detailed information is shown on the Figure 11 below:Figure SEQ Figure \* ARABIC 11 General logic of the first branchThe second branch is much more simple than the first one, because it hasn’t any smart handlers. However, it is based on the same interface as the first part (inline keyboards). Thus, technical issue menu provides users with several options such as ?Cannot buy a ticket??, ?Problems with cashback??, ?Event was canceled??, ?Did not get a ticket??, ?Other? or ?Return to the main menu?. Each option leads to predefined answers. The logic of the second branch is shown on the Figure 12 below:Figure SEQ Figure \* ARABIC 12 General logic of the second branchBlock 1 – startAccording to the telegram rules, the entrance point of a bot starts with “/start” command, on which a unique document is created in the database and the users are redirected to main_menu() function. This stage does not have business logic and serves just to the fulfillment of the conditions. To handle /start command, bot.message_handler decorator was used (see Figure 13):32067543180@bot.message_handler(commands=['start'])def start_menu(message): if not db.Users.find_one({"telegram_id": message.from_user.id}): db.Users.insert_one({"telegram_id": message.from_user.id, "chat_id": message.chat.id, "name": message.from_user.first_name, "history": {"request": []} }) return main_menu(message)0@bot.message_handler(commands=['start'])def start_menu(message): if not db.Users.find_one({"telegram_id": message.from_user.id}): db.Users.insert_one({"telegram_id": message.from_user.id, "chat_id": message.chat.id, "name": message.from_user.first_name, "history": {"request": []} }) return main_menu(message)3181351928495Figure 13 "/start" codeFigure 13 "/start" codeBlock 2 - Main menu66421037788856642103796030Figure 14 Main user interfaceFigure 14 Main user interface664210243903500The main menu is the most important part of a user interface and architecture at all, because it is a core or start point for all interactions, moreover each scenario of the bot leads to the main menu at the end of itself. The main menu is implemented through bot.message_handler decorator and can be called by the command /menu. Also, it should be mentioned that in situations where the bot is waiting for user’s response the command /menu should not work, but a very nice decorator cancel_option was made to solve that issue. For inline callbacks it calls through a callback named ?Menu?. The business logic here is to provide the user with an ability to come back to the beginning, in other words, it is an analogy of Welcome page or Main page on websites (see Figure 14 and 15):1778002798445Figure 15 "Main menu" codeFigure 15 "Main menu" code17821423966@bot.message_handler(commands=['menu'])def main_menu(message): bot.send_message(message.chat.id, 'Выберите дальнейшие действия', parse_mode='HTML', reply_markup=keyboard_main_menu())# callback@bot.callback_query_handler(func=lambda call: True)def callback_inline(call): if call.data == 'Menu': main_menu(call.message)0@bot.message_handler(commands=['menu'])def main_menu(message): bot.send_message(message.chat.id, 'Выберите дальнейшие действия', parse_mode='HTML', reply_markup=keyboard_main_menu())# callback@bot.callback_query_handler(func=lambda call: True)def callback_inline(call): if call.data == 'Menu': main_menu(call.message)1778002747645Block 3 - Query of pollsThe query part focuses on obtaining user’s preferences or filters according to events. The scenario of this part is to offer filters to user by three consecutive polls. The first poll consists of three questions dedicated to the type of event, such as ?Theaters?, ?Concerts? and ?Exhibitions?. Then the bot offers to select the time of event, which is represented by buttons ?Now?, ?Today?, ?Tomorrow?, and ?Defined day?. At the last step the user can select the location of the event by making a choice between ?Near?, ?Metro?, ?District? and ?Any option? options. Thus, there are 48 possible scenarios of filtrations. Finally, when the user selects all preferences the process goes to Block 4 described below.To implement query of pools parts, the integrated keyboards were used. They are very nice for user experience purpose but have a huge disadvantage - the inability to transfer the data through them. However, this issue was solved thanks to a smart trick. Fortunately, Python allows to implement decorators with static fields, that helps to implement cache. The query of pools part consists of three functions, wrapped in a compose function, which is in turn wrapped in the decorator with a cache. These functions are where_processing(), when_processing(), location_processing(). The idea of these functions is to obtain the user’s preferences of place, location and time respectively. A composed_control() was used as a decorator for processing() function. Such uncommon structure was used to implement a hint with a cache. The fact is that the answer for callbacks goes through processing() function and thus compose_control() stores previous information in cache and transfers it to the next part of the architecture (Block 4).Compose control catches the two parameters body, which is a user’s answer on the poll (When, Where, Location) on the step that goes to the wrapped function and stores it in cache dict with the key value of user’s id in telegram. Obviously, all calls of pools go through the callback’s handler.Figure 16 Block 3 architectureFigure SEQ Figure \* ARABIC 17 Block 3 user interface2698758766175Figure 18 Block 3 compose controllerFigure 18 Block 3 compose controller2698751270# decorator / cache controllerdef compose_control(fun): compose_control.cache = {} def inner(message, *args, **kwargs): body = kwargs["body"] step = kwargs["step"] user = str(message.chat.id) if user not in compose_control.cache: compose_control.cache[user] = {} compose_control.cache[user].update({step: body}) return fun(message, *args, **kwargs) return inner# Polls controller@compose_controldef processing(message, step, *, body): user = str(message.chat.id) if step == 'Where': when_processing(message) if step == 'When': location_processing(message) if step == 'Location' and len(compose_control.cache[user]) == 3: activities = compose_control.cache[user] compose_control.cache.pop(user) compose_processing(message, activities)#callbacks@bot.callback_query_handler(func=lambda call: True) if call.data == 'Theater': processing(call.message, step="Where", body="Theaters") if call.data == 'Museum': …. if call.data == 'Concert': processing(call.message, step="Where", body="Concerts") # when if call.data == "Now": processing(call.message, step="When", body="Now") …... if call.data == 'DefinedDay': processing(call.message, step="When", body="DefinedDay") # location if call.data == "Near": processing(call.message, step="Location", body="Near") ... if call.data == 'AnyOption': processing(call.message, step="Location", body="AnyOption")00# decorator / cache controllerdef compose_control(fun): compose_control.cache = {} def inner(message, *args, **kwargs): body = kwargs["body"] step = kwargs["step"] user = str(message.chat.id) if user not in compose_control.cache: compose_control.cache[user] = {} compose_control.cache[user].update({step: body}) return fun(message, *args, **kwargs) return inner# Polls controller@compose_controldef processing(message, step, *, body): user = str(message.chat.id) if step == 'Where': when_processing(message) if step == 'When': location_processing(message) if step == 'Location' and len(compose_control.cache[user]) == 3: activities = compose_control.cache[user] compose_control.cache.pop(user) compose_processing(message, activities)#callbacks@bot.callback_query_handler(func=lambda call: True) if call.data == 'Theater': processing(call.message, step="Where", body="Theaters") if call.data == 'Museum': …. if call.data == 'Concert': processing(call.message, step="Where", body="Concerts") # when if call.data == "Now": processing(call.message, step="When", body="Now") …... if call.data == 'DefinedDay': processing(call.message, step="When", body="DefinedDay") # location if call.data == "Near": processing(call.message, step="Location", body="Near") ... if call.data == 'AnyOption': processing(call.message, step="Location", body="AnyOption")Block 4 - Polls prepossessingThe pools prepossessing part is focused on constructing recommendations based on previous users’ answers. A peculiarity of this part is that it has not any implicit business value. This block is responsible for processing of data obtained on previous step. However, there are some cases where a user interacts with the bot. These cases arise when a user should give additional information. Such situations are possible when a user selected Defined day, Near, District or Metro options.This part begins with compose_processing() function with blocks that are responsible for assembling criteria intended for database extraction. It should be mentioned that compose_processing() starts with checking the integrity of input cache and cleaning of cache in compose_control decorator. In some cases compose_processing() is a final point of pools prepossessing part, but there are cases when the bot should get an additional information from the user. It is important that compose_processing() guarantees only date filtering in case of absent additional information. For the cases when the user should give additional info, several functions such as current_day_preposition(), near_preposition(), metro_preposition() and block_preposition() were developed. The function current_day_preposition() serves to get custom date of event; other cases of date preferences do not need additional filtering. With regard to location composing there is only one case when compose_processing() is enough to generate recommendations. Also, the bot can ask for current user’s locations by using near_preposition() function, wrapped in special decorator allowing to read GPS data from Telegram. The functions metro_preposition() and block_preposition() focus on getting metro station and district respectively; these functions are based on matchmaking with dict. After all parameters received, the bot makes a request to the database and forms a list of recommendation and then the process moves to last step.Analyzing user feedback, it was figured out that when the bot asks to send additional info, such as metro or locations, users want to have a cancel option. Thus, a nice decorator cancel_option, that allows to return an input function by getting messages “cancel” or “/menu”, was implemented: Figure 19 Block 4 architectureFigure SEQ Figure \* ARABIC 20 Block 4 cancel option user interfaceFigure SEQ Figure \* ARABIC 21 Block 4 Polls preprocessing user interface3181352632075Figure 22Figure 223181352603500Figure 23 Backward realizationFigure 23 Backward realization318135-28575# Decorator | Cancel option | back is function in case of returndef cancel_option(func=None, *, back=None): if func is None: return lambda x: cancel_option(x, back=back) @wraps(func) def wrapper(message, *args, **kwargs): # Check for cancel option if message.text.lower() == 'отмена' or message.text.lower() == '/menu': bot.send_message(message.chat.id, 'Попробуем в следующий раз!', reply_markup=telebot.types.ReplyKeyboardRemove()) return back(message) else: return func(message, *args, **kwargs) return wrapper# Decorator | Cancel option | back is function in case of returndef cancel_option(func=None, *, back=None): if func is None: return lambda x: cancel_option(x, back=back) @wraps(func) def wrapper(message, *args, **kwargs): # Check for cancel option if message.text.lower() == 'отмена' or message.text.lower() == '/menu': bot.send_message(message.chat.id, 'Попробуем в следующий раз!', reply_markup=telebot.types.ReplyKeyboardRemove()) return back(message) else: return func(message, *args, **kwargs) return wrapperBlock 5 Final processingThis block is responsible for sending recommendations to users or final processing. The idea of this part is to get prepossessed filtered recommendations and deliver them to the user. Also, the purpose of this stage is providing payment link to the user. A recommendation card consists of two messages where the first message is a picture of an event and the second one is a description of the event, including name, price, time, place, address and description. Thus, from business side the idea of this block is to attract a person to buying a ticket. There are many ways to make a user to buy a ticket, from various marketing techniques to ML recommendations based on previous orders. As it was mentioned above, the sending uses send_recommendations() function, that does not have a cache interface and gets all necessary information from the database. By default send_recommendations() provides a user with three events and completes events query with keyboard_more() inline keyboard, which is responsible for next actions. At the next action the user can choose between two options that are ?More? and ?Main menu?. ?Main menu? option returns a user to the beginning of the filtering step, while ?More? leads to sending the next three events. It is necessary to mention that at each call of send_recommendations(), the user’s profile is changed. In case when there was no any recommendation found, the user gets messages with some apologies and then the bot returns Main menu interface. At the beginning of send_recommendations() the bot gets data from the user’s document in the database and gets the next field from which the bot obtains the id’s of recommendations for current session. Then the bot checks if there are any recommendations left. After this query of recommendations is sent, the bot reforms a next list and sends it to the database. This architecture was used to avoid possible problems with data leak, because cache interface is nice when there are 10-50 users online, but if there is 1 million, it may be stumbled upon memory issues. However, by using this approach the load to the database is increased.Figure 24 Final processing architectureFigure SEQ Figure \* ARABIC 25 Final user interfaceBlock 6 Technical issuesIn addition to recommendation functionality it was decided to implement support service in framework of the bot to reduce the load on the call-center. In described implementation, a support service is a query of possible issues with predefined answers. Services like voice assistance were not implemented due to complexity and time-consuming reasons, indeed companies spend a lot of resources to such kind of realization. However, the purpose was not to implement complicated technologies, but to show the possible variation of places for its implementation.Several scenarios for users in this block were organized. The beginning of a user’s journey starts from main menu with a button “Technical issues”. Then the user is transferred to the technical issue menu, where the bot offers six options: “Cannot buy a ticket?”, “Problems with cashback?”, “Event was canceled?”, “Did not get ticket”, “Other” and “Main menu”. Each of the options goes to a predefined answer except of “Event was canceled?” and “Main menu”. The Main menu option returns the user to the main menu and “Event was canceled” leads to an additional menu where a user can choose between two buttons – “Cinema” and “Other”, which in turns lead to predefined answers.The technical issue part does not have any complicated tricks with a cache or database, instead it is based on the inline keyboards scheme used in previous parts. There are two possible ways to access the technical issues menu – entering “issue” command and calling callback Issue; both of them lead to to call of issues_menu(). Then the issue_menu() send six inline buttons to the user according to business scenario. The answer on callback returns functions give_cashback_info(), event_issues_menu(), give_no_ticket_info(), issue_preprocessing(), where each of the functions just sends a predefined answer to the user, except event_issues_menu(), which offers two additional options leading to returning of issue_kino(), issue_other().Figure 26 Block 6 architecture Figure SEQ Figure \* ARABIC 27 Block 6 user interfaceIn the second paragraph of the third chapter the MVP development of chatbot for MTS Live service was described. This MVP was developed on the base of Telegram API by using Python programming language and Mongo DB database. Despite the fact that the developed MVP doesn’t consist of a full chatbot, described in the first paragraph, it still conveys the meaning of a business model.ConclusionAs part of the work dedicated to chatbot development business prospects, the conclusions were formulated. They correspond to the goals and objectives set at the beginning of the work.Thus, in the first paragraph of the first chapter the basic theoretical overview of a chatbot was given. This overview contains of comparison of several chatbot definitions, description of a simple scheme behind chatbot operation, analysis of such development approaches of the chatbots as rule-based and machine learning-based. From the research described in the first paragraph it also becomes clear that chatbot is one of the most popular and relevant technologies currently. It is also possible to state, that the popularity of chatbot technologies is not artificial at all since they really can bring a considerable value both for businesses and for the customers. This value is described in the second paragraph of the first chapter together with the metrics that can be used to evaluate the success of the bot implementation. The value of chatbot for a business can be either direct or countable, like increase of revenue or decrease of costs, and indirect, which improves the product or service and creates better customer experience, bringing, by doing so, the value also to the customers. The first chapter ends with the examples of how chatbot serve certain business functions and how they are used across different industries.In the second chapter the development of MTS company is looked through with the precise description of the current directions for further development of the company. It becomes obvious that MTS is a candidate to become an IT giant. Their current strategic priorities fully comply with their goals and intentions. They pay a lot of attention to the development of their ecosystem, where they have already reached significant results. Chatbots may help the company to achieve their goals by improving customer experience and engagement. That is why in the end of the second chapter some examples of possible chatbot implementations are described and one of them – MTS Live Chatbot – is chosen for further MVP development.In the third and last chapter MTS Live Chatbot business model is described by designing the Business Model Canvas and the Value Proposition Canvas. The possible pains, gains and customer’s expectations are highlighted. They help to create a unique value proposition and show, which specific functions of the bot will serve that goal. In the second part of the last chapter the particular MVP is developed. This MVP is based on the Telegram API and contains two described in the business model functions: searching for an event and solving technical issues. The developing process is described precisely. MTS Live Telegram Bot is completed and after some testing may be used by MTS.This work is, of course, only a part of the global work that needs to be done to create an MVP for the whole chatbot described by the business model. The completion of this work can bring MTS Live service a strong market advantage, since there is no comparable service on the e-ticketing market right now. This chatbot will surely improve the customer experience of the service users and make MTS one step closer to becoming a huge love-brand.List of referencesGalitsky, B. (2019). Developing enterprise chatbots. San Jose, CA: SpringerGentsch, P. (2019). AI in Marketing, Sales and Service, Bots as a New Customer Interface and Operating System (pp. 81-125). London, Great Britain: Palgrave MacmillanKhan, R. (2018). Build better chatbots. Bangalore, India: ApressMoore, J. (1996). The Death of Competition: Leadership and Strategy in the Age of Business Ecosystems. New York, NY: HarperBusinessSingh, A. (2019). Building an enterprise chatbot. Delhi, India: ApressAraujo, T. (2018). Living up to the chatbot hype. Computers in human behavior, 85, 183-189. doi: 10.1016/j.chb.2018.03.051 Klaus, P., Zaichkowsky, J. (2020). AI voice bots: a services marketing research agenda. Journal of Services Marketing. doi: 10.1108/JSM-01-2019-0043 Mohammad, H.J. (2018). Artificial intelligence and the future of work: Human-AI symbiosis in organizational decision making. Business Horizons, 61, 577-586. doi: 10.1016/j.bushor.2018.03.007Przegalinska, A. et al. (2019). In bot we trust: A new methodology of chatbot performance measures. Business Horizons, 62, 785-797. doi: 10.1016/j.bushor.2019.08.005Chatbot point of view (2018). The Netherlands: DeloitteChatbots: the definitive guide (2020). Retrieved April 5, 2020, from : theory and practice (2017, July 19). Retrieved May 20, 2020, from experience: Creating value through transforming customer journeys. (2016, July 1). Retrieved May 10, 2020, from Glossary. Retrieved May 5, 2020, from ’s Market Guide for Conversational platforms. (2019, July 30)Gartner's Top 10 Strategic Predictions for 2017 and Beyond. (2016, October 18). Retrieved May 16, 2020, from businesses are winning with chatbots and AI. (2018, January 25). Retrieved April, 29, 2020, from Chatbots & AI Are Changing the Face of Energy Providers. (2019, August 30). Retrieved April 30, 2020, from to Improve Your Customer Service Response Times. (2018, April 28). Retrieved May 10, 2020, from DB Documentation: Annual report 2018. (2019, May 27). Retrieved March 10, 2020, from Annual report 2019. (2020, May 21). Retrieved May 31, 2020, from Shows Customer Loyalty Hangs in the Balance: "State of the Connected Customer" Report. (2016, October 24). Retrieved April 29, 2020, from Cloud Services: Gartner Hype Cycle highlights how AI is reaching organizations in many different ways. (2019, September 12). Retrieved April 30, 2020, from 24/7 business is the future. (2017, March 10). Retrieved May 10, 2020, from Documentation: Исследование российского билетного рынка (2018). Retrieved March 30, 2020 from Как и почему в МТС решили сформировать экосистему (2019б June 5). Retrieved April 10, 2020 from Как российские компании строят экосистемы: что происходит и чего ожидать (2020, February 6). Retrieved March 30, 2020, from Пишем telegram-бота на python с помощью библиотеки telebot (2019, April 16). Retrieved March 15, 2020, from - Artificial IntelligenceAPI - Application Programming InterfaceCRM - Customer Relationship ManagementGPON - Gigabit Passive Optical NetworksGPS - Global Positioning SystemGSM - Global Standard for MobileID - Identification DataIoT - Internet of ThingsIT - Information TechnologiesJSON -JavaScript Object NotationLAA - License Assisted AccessLTE - Long-Term EvolutionM&A - Merger and AcquisitionMIMO - Multiple-Input and Multiple-OutputML - Machine LearningMVP - Minimum Viable ProductNB-IoT - NarrowBand-Internet of ThingsNLG - Natural Language GenerationNLP - Natural Language ProcessingNLU - Natural language understandingOIBDA - Operating income before depreciation and amortizationR&D - Research and DevelopmentRAM - Random Access MemorySQL - Structured Query LanguageSSL - Secure Sockets LayersUI - User InterfaceUMTS - Universal Mobile Telecommunications SystemUX - User ExperienceAppendix MTS Live Telegram Bot MVP Codesrc/bot.pyfrom settings import TOKEN, MONGO_HOST, MONGO_PORTimport datetimeimport telebotfrom keyboards import *# from src.keyboards import *import pandas as pdfrom math import radians, cos, sin, asin, sqrtfrom functools import wrapsfrom blocks import districts# calculate distancedef haversine(lat1, lon1, lat2, lon2): # convert decimal degrees to radians lon1, lat1, lon2, lat2 = map(radians, (lon1, lat1, lon2, lat2)) # haversine formula dlon = lon2 - lon1 dlat = lat2 - lat1 a = sin(dlat / 2) ** 2 + cos(lat1) * cos(lat2) * sin(dlon / 2) ** 2 c = 2 * asin(sqrt(a)) km = 6367 * c return km# Decorator | Cancel option | back is function in case of returndef cancel_option(func=None, *, back=None): if func is None: return lambda x: cancel_option(x, back=back) @wraps(func) def wrapper(message, *args, **kwargs): # Check for cancel option if message.content_type== 'text' and (message.text.lower() == 'отмена' or message.text.lower() == '/menu'): bot.send_message(message.chat.id, 'Попробуем в следующий раз!', reply_markup=telebot.types.ReplyKeyboardRemove()) return back(message) else: return func(message, *args, **kwargs) return wrapper# Mongo dbfrom pymongo import MongoClientbot = telebot.TeleBot(TOKEN)# Подключение к Mongoclient = MongoClient(MONGO_HOST, MONGO_PORT)db = client['DiplomaBotMTC']# @bot.message_handler(commands=['p'])# def magic_menu(message):# path = glob.glob('/home/anton/Garbadge/diploma/*.*')# final_check = 0# # bot.send_photo(message.chat.id, (open(path[0], "rb")))# for i in range(0, len(path)):# n = 0# corner = 7000# while n == 0:# try:# img = Image.open(path[i])# img.thumbnail((corner, corner))# img.save(path[i])# bot.send_photo(message.chat.id, (open(path[i], "rb")))# bot.send_message(message.chat.id, 'Succes:' + str(path[i].split('\\')[-1]))# bot.send_message(message.chat.id, str(i))# bot.send_message(message.chat.id, str(img.size))# n = n + 1# except:# # bot.send_message(message.chat.id, str(corner))# corner -= 100# bot.send_message(message.chat.id, str(final_check))@bot.message_handler(commands=['start'])def start_menu(message): if not db.Users.find_one({"telegram_id": message.from_user.id}): db.Users.insert_one({"telegram_id": message.from_user.id, "chat_id": message.chat.id, "name": message.from_user.first_name, "history": {"request": []} }) return main_menu(message)@bot.message_handler(commands=['menu'])def main_menu(message): bot.send_message(message.chat.id, 'Выберите дальнейшие действия', parse_mode='HTML', reply_markup=keyboard_main_menu())@bot.message_handler(commands=['issue'])def issues_menu(message): bot.send_message(message.chat.id, 'Выберите дальнейшие действия', parse_mode='HTML', reply_markup=keyboard_issues_menu())def where_processing(message): bot.send_message(message.chat.id, 'Куда бы вы хотели пойти?', parse_mode='HTML', reply_markup=keyboard_where())def when_processing(message): # db.Users.update_one({"telegram_id": message.from_user.id}, {"$set": {"last_request.where": activity}}) bot.send_message(message.chat.id, 'Когда вы планируете?', parse_mode='HTML', reply_markup=keyboard_when())def location_processing(message): # db.Users.update_one({"telegram_id": message.from_user.id}, {"$set": {"last_request.when": activity}}) bot.send_message(message.chat.id, 'Где … ?', parse_mode='HTML', reply_markup=keyboard_location())def compose_control(fun): compose_control.cache = {} def inner(message, *args, **kwargs): body = kwargs["body"] step = kwargs["step"] user = str(message.chat.id) if user not in compose_control.cache: compose_control.cache[user] = {} compose_control.cache[user].update({step: body}) return fun(message, *args, **kwargs) return inner@compose_controldef processing(message, step, *, body): user = str(message.chat.id) if step == 'Where': when_processing(message) if step == 'When': location_processing(message) if step == 'Location' and len(compose_control.cache[user]) == 3: activities = compose_control.cache[user] compose_control.cache.pop(user) compose_processing(message, activities)# choice scenariodef compose_processing(message, activities: dict = {}): # Unpuck input mask = ["Where", "When", "Location"] filter_mask = [activities.get(i) for i in mask if activities.get(i, False)] print(filter_mask) # check for integrity if len(filter_mask) != 3: bot.send_message("Что-то пошло не так, давайте попробуем снова") return main_menu(message) user = db.Users.find_one({'telegram_id': message.from_user.id}) if not user: db.Users.insert_one({"telegram_id": message.from_user.id, "chat_id": message.chat.id, "name": message.from_user.first_name, "history": {"request": []} }) # collect data to database db.Users.update_one({"telegram_id": message.chat.id}, {"$push": {"history.request": activities}}) where, when, location = filter_mask print(where, when, location) # script 1.1.1 db_name = f'{where}Events' if when == 'Tomorrow' and location == 'AnyOption': step = 0 tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=1) after_tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=2) events = [i for i in db[db_name].find({'date': {"$gte": tomorrow, "$lt": after_tomorrow}})] db.Users.update_one({'telegram_id': message.from_user.id}, {"$set": {"operations.next": [i["_id"] for i in events], "operations.last_db_body": where}}) return send_recommendations(message) if when == 'Today' and location == 'AnyOption': step = 0 today = datetime.datetime.now() tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=1) events = [i for i in db[db_name].find({'date': {"$gte": today, "$lt": tomorrow}})] db.Users.update_one({'telegram_id': message.from_user.id}, {"$set": {"operations.next": [i["_id"] for i in events], "operations.last_db_body": where}}) return send_recommendations(message) if when == 'DefinedDay' and location == 'AnyOption': bot.send_message(message.chat.id, "Введите дату в формате день месяц, например 21 мая", reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, current_day_preposition, db_name_body=where) if when == 'Now' and location == 'AnyOption': today = datetime.datetime.now() tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(hours=2) events = [i for i in db[db_name].find({'date': {"$gte": today, "$lt": tomorrow}})] db.Users.update_one({'telegram_id': message.from_user.id}, {"$set": {"operations.next": [i["_id"] for i in events], "operations.last_db_body": where}}) return send_recommendations(message) if when == 'DefinedDay' and location == 'Metro': bot.send_message(message.chat.id, "Введите дату в формате день месяц, например 21 мая", reply_markup=keyboard_cancel()) mes = "Введите станцию метро, например чкаловская" bot.register_next_step_handler(message, current_day_preposition, metro_preposition, mes, where) if when == 'Tomorrow' and location == 'Metro': tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=1) after_tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=2) events = [i for i in db[db_name].find({'date': {"$gte": tomorrow, "$lt": after_tomorrow}})] bot.send_message(message.chat.id, "Введите станцию метро, например чкаловская", reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, metro_preposition, events, where) if when == 'Today' and location == 'Metro': today = datetime.datetime.now() tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=1) events = [i for i in db[db_name].find({'date': {"$gte": today, "$lt": tomorrow}})] bot.send_message(message.chat.id, "Введите станцию метро, например чкаловская", reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, metro_preposition, events, where) if when == 'Now' and location == 'Metro': today = datetime.datetime.now() tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(hours=2) events = [i for i in db[db_name].find({'date': {"$gte": today, "$lt": tomorrow}})] bot.send_message(message.chat.id, "Введите станцию метро, например чкаловская", reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, metro_preposition, events, where) if when == 'DefinedDay' and location == 'Block': bot.send_message(message.chat.id, "Введите дату в формате день месяц, например 21 мая", reply_markup=keyboard_cancel()) mes = 'Введите район например, Адмиралтейский район,' bot.register_next_step_handler(message, current_day_preposition, block_preposition, mes, where) if when == 'Tomorrow' and location == 'Block': tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=1) after_tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=2) events = [i for i in db[db_name].find({'date': {"$gte": tomorrow, "$lt": after_tomorrow}})] bot.send_message(message.chat.id, 'Введите район например, Адмиралтейский район', reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, block_preposition, events, where) if when == 'Today' and location == 'Block': today = datetime.datetime.now() tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=1) events = [i for i in db[db_name].find({'date': {"$gte": today, "$lt": tomorrow}})] bot.send_message(message.chat.id, 'Введите район например, Адмиралтейский район', reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, block_preposition, events, where) if when == 'Now' and location == 'Block': today = datetime.datetime.now() tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(hours=2) events = [i for i in db[db_name].find({'date': {"$gte": today, "$lt": tomorrow}})] bot.send_message(message.chat.id, 'Введите район например, Адмиралтейский район', reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, block_preposition, events, where) if when == 'Today' and location == 'Near': today = datetime.datetime.now() tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=1) events = [i for i in db[db_name].find({'date': {"$gte": today, "$lt": tomorrow}})] bot.send_message(message.chat.id, 'Отправьте геолокацию', reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, near_preposition, events, where) if when == 'Now' and location == 'Near': today = datetime.datetime.now() tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(hours=2) events = [i for i in db[db_name].find({'date': {"$gte": today, "$lt": tomorrow}})] bot.send_message(message.chat.id, 'Отправьте геолокацию', reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, near_preposition, events, where) if when == 'DefinedDay' and location == 'Near': bot.send_message(message.chat.id, "Введите дату в формате день месяц, например 21 мая", reply_markup=keyboard_cancel()) mes = "Отправьте геолокацию" bot.register_next_step_handler(message, current_day_preposition, near_preposition, mes, where) if when == 'Tomorrow' and location == 'Near': tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=1) after_tomorrow = datetime.datetime.now().replace(hour=0, minute=0) + datetime.timedelta(days=2) events = [i for i in db[db_name].find({'date': {"$gte": tomorrow, "$lt": after_tomorrow}})] bot.send_message(message.chat.id, "Отправьте геолокацию", reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, near_preposition, events, where)@cancel_option(back=main_menu)def near_preposition(message, events, db_name_body): db_name = f'{db_name_body}Events' try: latitude, longitude = message.location.latitude, message.location.longitude events_place = [i["theatre"] for i in events] place = [] for i in db[db_name_body].find({'name': {"$in": events_place}}): location = i.get("location") km = haversine(location[0], location[1], latitude, longitude) place.append([i["name"], km]) place = pd.DataFrame(place, columns=["name", "place"]) place = place.sort_values(by=["place"]) place = list(place["name"][place["place"] >= 3]) print(place) events = [i for i in events if i['theatre'] in place] db.Users.update_one({'telegram_id': message.from_user.id}, {"$set": {"operations.next": [i["_id"] for i in events], "operations.last_db_body": db_name_body}}) return send_recommendations(message) except: bot.send_message(message.chat.id, 'Неверный формат. Отправьте геолокацию', parse_mode='HTML') bot.register_next_step_handler(message, near_preposition, events, db_name_body)@cancel_option(back=main_menu)def block_preposition(message, events, db_name_body): block = message.text.lower() events_place = [i["theatre"] for i in events] place = [i['name'] for i in db[db_name_body].find({'name': {"$in": events_place}}) if block in [m.lower() for m in i['districts']]] events = [i for i in events if i['theatre'] in place] db.Users.update_one({'telegram_id': message.from_user.id}, {"$set": {"operations.next": [i["_id"] for i in events], "operations.last_db_body": db_name_body}}) return send_recommendations(message)@cancel_option(back=main_menu)def metro_preposition(message, events, db_name_body): station = message.text.lower() print(station) events_place = [i["theatre"] for i in events] print(events_place) place = [i['name'] for i in db[db_name_body].find({'name': {"$in": events_place}}) if station in [m.lower() for m in i['metro']]] print(place) events = [i for i in events if i['theatre'] in place] db.Users.update_one({'telegram_id': message.from_user.id}, {"$set": {"operations.next": [i["_id"] for i in events], "operations.last_db_body": db_name_body}}) return send_recommendations(message)@cancel_option(back=main_menu)def current_day_preposition(message, fun=None, mes=None, db_name_body=None): # try: print("bd_name", db_name_body) db_name = f'{db_name_body}Events' date = message.text.lower().strip().split(" ") if date[0] == 'отмена': return main_menu int(date[0]) mnt = {'январь': 1, 'февраль': 2, 'март': 3, 'апрель': 4, 'май': 5, 'июнь': 6, 'июль': 7, 'август': 8, 'сентябрь': 9, 'октябрь': 10, 'ноябрь': 11, 'декабрь': 12, 'января': 1, 'февраля': 2, 'марта': 3, 'апреля': 4, 'мая': 5, 'июня': 6, 'июля': 7, 'августа': 8, 'сентября': 9, 'октября': 10, 'ноября': 11, 'декабыря': 12} if len(date) == 2: if mnt.get(date[1]) and (0 < int(date[0]) < 32): day = datetime.datetime(2020, mnt[date[1]], int(date[0])) day_later = day + datetime.timedelta(days=1, minutes=1) print(day, day_later) events = [i for i in db[db_name].find({'date': {"$gte": day, "$lt": day_later}})] print(len([i["_id"] for i in events])) if fun: bot.send_message(message.chat.id, mes, reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, fun, events, db_name_body) else: db.Users.update_one({'telegram_id': message.from_user.id}, {"$set": {"operations.next": [i["_id"] for i in events], "operations.last_db_body": db_name_body}}) return send_recommendations(message)# except:# bot.send_message(message.chat.id, 'Неверный формат\n Введите дату в формате'# ' день месяц, например 21 мая', parse_mode='HTML')# bot.register_next_step_handler(message, current_day_preposition, fun, mes, db_name_body)def send_recommendations(message): step = 0 print("------------------") user = db.Users.find_one({'telegram_id': message.from_user.id}) events = user.get("operations", {}).get("next", {}) print("number events:", len(events)) # get last datebase collection = user["operations"]["last_db_body"] db_name_body = f"{collection}Events" print("Name of collection:", db_name_body) events = [i for i in db[db_name_body].find({'_id': {'$in': events}})] print("len of found events:", len(events)) if events: for event in events: print("name of place", event["theatre"]) metro = db[collection].find_one({"name": event["theatre"]}).get("metro") if metro: metro = ", ".join(metro) else: metro = " " step += 1 if len(event["description"]) > 350: event["description"] = event["description"][0:347] + "..." mes = f'<b> {event["name"]} : </b> \n' \ f'<b>Время</b>: {" ".join(event["date"].isoformat().split("T"))[:-3]} \n' \ f'<b>Метро</b>: {metro}\n' \ f'<b>Цена</b>: {event.get("cost", "~")}\n' \ f'<b>Место</b>: {event["theatre"]}\n{event["link"]}\n' \ f'<b>Описание</b>: {event["description"]}' if len(events) == step or step == 2: try: bot.send_photo(message.chat.id, (open(event["picture"], "rb"))) except: pass bot.send_message(message.chat.id, mes, parse_mode='HTML') bot.send_message(message.chat.id, 'Дальнейшие опции', parse_mode='HTML', reply_markup=keyboard_more()) db.Users.update_one({'telegram_id': message.from_user.id}, {"$push": {"theaters.passed": [i["_id"] for i in events[:3]]}, "$set": {"operations.next": [i["_id"] for i in events[3:]]}}) return None if step < 2: try: bot.send_photo(message.chat.id, (open(event["picture"], "rb"))) except: pass bot.send_message(message.chat.id, mes, parse_mode='HTML') else: mes = "К сожалению рекомендаций нет" bot.send_message(message.chat.id, mes, parse_mode='HTML', reply_markup=keyboard_main_menu())# SUPPORT PARTdef give_buy_ticket_info(message): bot.send_message(message.chat.id, "Информация", parse_mode='HTML', reply_markup=keyboard_main_menu())def give_cashback_info(message): bot.send_message(message.chat.id, "Информация", parse_mode='HTML', reply_markup=keyboard_main_menu())def event_issues_menu(message): bot.send_message(message.chat.id, "Выберите опции", parse_mode='HTML', reply_markup=keyboard_event_issues_menu())def give_no_ticket_info(message): bot.send_message(message.chat.id, "Информация", parse_mode='HTML', reply_markup=keyboard_main_menu())def issue_preprocessing(message): bot.send_message(message.chat.id, "Введите проблему", parse_mode='HTML', reply_markup=keyboard_cancel()) bot.register_next_step_handler(message, issue_processing)def issue_kino(message): bot.send_message(message.chat.id, "Информация", parse_mode='HTML', reply_markup=keyboard_main_menu())def issue_other(message): bot.send_message(message.chat.id, "Информация", parse_mode='HTML', reply_markup=keyboard_main_menu())@cancel_option(back=start_menu)def issue_processing(message): bot.send_message(message.chat.id, "Спасибо за обращение, Ваша проблемма будет расмотрена", parse_mode='HTML') main_menu(message)# CallBacks# Проверка коллбеков@bot.callback_query_handler(func=lambda call: True)def callback_inline(call): call.pass_user_data = True if call.message: # next line is necessary due to telegram bug call.message.from_user.id = call.message.chat.id bot.delete_message(chat_id=call.message.chat.id, message_id=call.message.message_id) # where menu if call.data == 'Theater': processing(call.message, step="Where", body="Theaters") if call.data == 'Museum': processing(call.message, step="Where", body="Exhibitions") if call.data == 'Concert': processing(call.message, step="Where", body="Concerts") # when if call.data == "Now": processing(call.message, step="When", body="Now") if call.data == 'Today': processing(call.message, step="When", body="Today") if call.data == 'Tomorrow': processing(call.message, step="When", body="Tomorrow") if call.data == 'DefinedDay': processing(call.message, step="When", body="DefinedDay") # location if call.data == "Near": processing(call.message, step="Location", body="Near") if call.data == 'Metro': processing(call.message, step="Location", body="Metro") if call.data == 'Block': processing(call.message, step="Location", body="Block") if call.data == 'AnyOption': processing(call.message, step="Location", body="AnyOption") if call.data == 'Step': where_processing(call.message) if call.data == 'More': send_recommendations(call.message) if call.data == 'Menu': main_menu(call.message) # issue menu if call.data == 'Issue': issues_menu(call.message) if call.data == 'Issue1': give_buy_ticket_info(call.message) if call.data == 'Issue2': give_cashback_info(call.message) if call.data == 'Issue3': event_issues_menu(call.message) if call.data == 'Issue4': issue_preprocessing(call.message) if call.data == 'IsKino': issue_kino(call.message) if call.data == 'IsOther': issue_other(call.message) bot.answer_callback_query(call.id)bot.polling(none_stop=True)src/keyboards.pyimport telebot# Меню после свободного вводаdef keyboard_where(): keyboard = telebot.types.InlineKeyboardMarkup() # btm_1 = telebot.types.InlineKeyboardButton('Кино', callback_data='Cinema') btm_2 = telebot.types.InlineKeyboardButton('Театр', callback_data='Theater') btm_3 = telebot.types.InlineKeyboardButton('Музей', callback_data='Museum') btm_4 = telebot.types.InlineKeyboardButton('Концерт', callback_data='Concert') btm_5 = telebot.types.InlineKeyboardButton('Отмена', callback_data='Menu') # btm_5 = telebot.types.InlineKeyboardButton('Ресторан', callback_data='Restaurant') keyboard.add(btm_2, btm_3, btm_4) keyboard.add(btm_5) # keyboard.add(btm_4, btm_5) return keyboard# Меню после свободного вводаdef keyboard_when(): keyboard = telebot.types.InlineKeyboardMarkup() btm_1 = telebot.types.InlineKeyboardButton('Прямо сейчас', callback_data='Now') btm_2 = telebot.types.InlineKeyboardButton('Сегодня', callback_data='Today') btm_3 = telebot.types.InlineKeyboardButton('Завтра', callback_data='Tomorrow') btm_4 = telebot.types.InlineKeyboardButton('Конкретный день', callback_data='DefinedDay') btm_5 = telebot.types.InlineKeyboardButton('Отмена', callback_data='Menu') keyboard.add(btm_1, btm_2) keyboard.add(btm_3, btm_4) keyboard.add(btm_5) return keyboard# Меню после свободного вводаdef keyboard_location(): keyboard = telebot.types.InlineKeyboardMarkup() btm_1 = telebot.types.InlineKeyboardButton('Рядом', callback_data='Near') btm_2 = telebot.types.InlineKeyboardButton('Выбор по станции', callback_data='Metro') btm_3 = telebot.types.InlineKeyboardButton('Выбор по району', callback_data='Block') btm_4 = telebot.types.InlineKeyboardButton('Всё равно', callback_data='AnyOption') btm_5 = telebot.types.InlineKeyboardButton('Отмена', callback_data='Menu') keyboard.add(btm_1, btm_2) keyboard.add(btm_3, btm_4) keyboard.add(btm_5) return keyboarddef keyboard_issues_menu(): keyboard = telebot.types.InlineKeyboardMarkup() btm_1 = telebot.types.InlineKeyboardButton('Не получается купить билет?', callback_data='Issue1') btm_2 = telebot.types.InlineKeyboardButton('Не начислен Cashback?', callback_data='Issue2') btm_3 = telebot.types.InlineKeyboardButton('Хотите вернуть билет?', callback_data='Issue3') btm_4 = telebot.types.InlineKeyboardButton('Билет после оплаты не пришёл на почту?', callback_data='Issue3') btm_5 = telebot.types.InlineKeyboardButton('Другой вопрос', callback_data='Issue4') btm_6 = telebot.types.InlineKeyboardButton('Главное меню', callback_data='Menu') for i in [btm_1, btm_2, btm_3, btm_4, btm_5, btm_6]: keyboard.add(i) return keyboarddef keyboard_event_issues_menu(): keyboard = telebot.types.InlineKeyboardMarkup() btm_1 = telebot.types.InlineKeyboardButton('Кино', callback_data='IsKino') btm_2 = telebot.types.InlineKeyboardButton('Другое', callback_data='IsOther') btm_3 = telebot.types.InlineKeyboardButton('Главное меню', callback_data='Menu') for i in [[btm_1, btm_2], [btm_3]]: keyboard.add(*i) return keyboarddef keyboard_cancel(): keyboard = telebot.types.ReplyKeyboardMarkup(True, True) keyboard.row('Отмена') return keyboarddef keyboard_main_menu(): keyboard = telebot.types.InlineKeyboardMarkup() btm_1 = telebot.types.InlineKeyboardButton('Выбрать', callback_data='Step') btm_2 = telebot.types.InlineKeyboardButton('Тех.Поддержка', callback_data='Issue') keyboard.add(btm_1, btm_2) return keyboard# Меню после свободного вводаdef keyboard_more(): keyboard = telebot.types.InlineKeyboardMarkup() btm_1 = telebot.types.InlineKeyboardButton('Еще', callback_data='More') btm_2 = telebot.types.InlineKeyboardButton('Главное меню', callback_data='Menu') keyboard.add(btm_1, btm_2) return keyboardsrc/settings.pyTOKEN='1052027692:AAEnnj-NFyTMBYfhhLiomGu9PAwv0gfPFDI'# MongoMONGO_HOST = 'localhost'MONGO_PORT = 27017src/blocks.pydistricts = {'район арбат': [55.751138, 37.590003], 'район басманный': [55.766567, 37.671229], 'район замоскворечье': [55.734157, 37.63429], 'район красносельский': [55.778041, 37.654574], 'мещанский район': [55.780066, 37.628801], 'пресненский район': [55.763432, 37.562389], 'таганский район': [55.74001, 37.666971], 'тверской район': [55.770127, 37.606918], 'район хамовники': [55.729199, 37.574525], 'район якиманка': [55.730826, 37.607565], 'район аэропорт': [55.803312, 37.542599], 'район беговой': [55.783833, 37.57696], 'район бескудниковский': [55.870056, 37.551636], 'район войковский': [55.827247, 37.497342], 'район головинский': [55.846765, 37.510601], 'район восточное дегунино': [55.884277, 37.558841], 'район западное дегунино': [55.872157, 37.518937], 'район дмитровский': [55.891027, 37.52863], 'район коптево': [55.832515, 37.529043], 'район левобережный': [55.865419, 37.465937], 'район молжаниновский': [55.936812, 37.380237], 'район савёловский': [55.799694, 37.570914], 'район сокол': [55.805938, 37.504376], 'район тимирязевский': [55.825527, 37.557071], 'район ховрино': [55.869041, 37.489491], 'район хорошёвский': [55.782289, 37.528208], 'район алексеевский': [55.812949, 37.650163], 'район алтуфьевский': [55.879849, 37.582278], 'район бабушкинский': [55.867081, 37.665812], 'район бибирево': [55.894768, 37.6077], 'район бутырский': [55.814123, 37.589204], 'район лианозово': [55.898487, 37.570007], 'район лосиноостровский': [55.881268, 37.69419], 'район марфино': [55.830002, 37.588745], 'район марьина роща': [55.796931, 37.614374], 'район медведково': [55.871248, 37.637389], 'район останкинский': [55.81908, 37.621705], 'район отрадное': [55.86206, 37.600262], 'район ростокино': [55.833562, 37.661608], 'район свиблово': [55.851839, 37.647711], 'район северный': [55.929757, 37.546695], 'район ярославский': [55.862858, 37.69746], 'район богородское': [55.819241, 37.703415], 'район вешняки': [55.730771, 37.815184], 'район восточный': [55.818983, 37.866235], 'район гольяново': [55.824162, 37.79613], 'район ивановское': [55.771479, 37.824005], 'район измайлово': [55.783681, 37.772783], 'район косино-ухтомский': [55.717061, 37.86345], 'район метрогородок': [55.823616, 37.755832], 'район новогиреево': [55.748154, 37.804108], 'район новокосино': [55.740167, 37.861725], 'район перово': [55.751994, 37.767456], 'район преображенское': [55.797296, 37.722487], 'район соколиная гора': [55.772775, 37.730625], 'район сокольники': [55.799947, 37.677158], 'район выхино-жулебино': [55.696357, 37.824553], 'район капотня': [55.63784, 37.799724], 'район кузьминки': [55.69864, 37.773547], 'район лефортово': [55.753635, 37.704817], 'район люблино': [55.677717, 37.748726], 'район марьино': [55.652664, 37.744774], 'район некрасовка': [55.683793, 37.928704], 'район нижегородский': [55.728423, 37.723807], 'район печатники': [55.685158, 37.723807], 'район рязанский': [55.724718, 37.7676], 'район текстильщики': [55.708917, 37.734371], 'район южнопортовый': [55.713086, 37.670474], 'район восточное бирюлёво': [55.594585, 37.678649], 'район западное бирюлёво': [55.58786, 37.639644], 'район братеево': [55.633434, 37.765058], 'район даниловский': [55.706457, 37.64277], 'район донской': [55.697798, 37.61839], 'район зябликово': [55.620423, 37.746076], 'район москворечье-сабурово': [55.642692, 37.671139], 'район нагатино-садовники': [55.671422, 37.64171], 'район нагатинский затон': [55.682849, 37.681568], 'район нагорный': [55.664659, 37.61547], 'район северное орехово-борисово': [55.618278, 37.704817], 'район южное орехово-борисово': [55.604264, 37.733132], 'район царицыно': [55.627387, 37.652768], 'район северное чертаново': [55.632205, 37.605113], 'район центральное чертаново': [55.61388, 37.604098], 'район южное чертаново': [55.591889, 37.600361], 'район академический': [55.688005, 37.572684], 'район северное бутово': [55.568914, 37.570519], 'район южное бутово': [55.542396, 37.531523], 'район гагаринский': [55.698041, 37.558535], 'район зюзино': [55.654066, 37.589608], 'район коньково': [55.643414, 37.530588], 'район котловка': [55.676209, 37.597199], 'район ломоносовский': [55.678778, 37.533239], 'район обручевский': [55.660917, 37.518479], 'район тёплый стан': [55.631427, 37.489877], 'район черёмушки': [55.664649, 37.561347], 'район ясенево': [55.607514, 37.534577], 'район внуково': [55.610845, 37.296685], 'район дорогомилово': [55.739468, 37.547656], 'район крылатское': [55.763194, 37.423716], 'район кунцево': [55.74261, 37.398482], 'район можайский': [55.717634, 37.422755], 'район ново-переделкино': [55.646081, 37.357169], 'район очаково-матвеевское': [55.689649, 37.448554], 'район проспект вернадского': [55.678407, 37.498635], 'район раменки': [55.707152, 37.51379], 'район солнцево': [55.645918, 37.40168], 'район тропарёво-никулино': [55.660318, 37.468488], 'район филёвский парк': [55.749805, 37.494584], 'район фили-давыдково': [55.727136, 37.469359], 'район куркино': [55.891209, 37.387379], 'район митино': [55.84537, 37.365828], 'район покровское-стрешнево': [55.823823, 37.445779], 'район строгино': [55.803783, 37.402695], 'район северное тушино': [55.861479, 37.428118], 'район южное тушино': [55.843434, 37.431423], 'район хорошёво-мневники': [55.777707, 37.492078], 'район щукино': [55.80059, 37.473519]}#!/usr/bin/env python# coding: utf-8# In[1]:import seleniumimport pandas as pdfrom selenium import webdriverfrom selenium.mon.keys import Keysfrom selenium.webdriver.support.select import Selectimport jsonimport requestsimport datetimeimport timeimport osimport shutilimport threadingimport re# In[11]:from pymongo import MongoClient# Подключение к Mongoclient = MongoClient('localhost', 27017)db1 = client['DiplomaBotMTC']# In[20]:# Подгружаем драйверdriver = webdriver.Chrome()# In[21]:# get main pagedriver.get("")time.sleep(2)# click on more buttoncheck = Truewhile check: try: driver.find_element_by_xpath( "//button[@class='button_red color_white col-12 d-flex justify-content-center color_one f_w_bold p_v_12 align-self-center border_style_one']").click() except: check = Falseprint("links->DONE")# get blocksblocks = driver.find_elements_by_xpath("//div[@class='col-sm-6 col-md-4 ng-star-inserted']")# get linklinks = [block.find_element_by_class_name("ng-star-inserted").get_attribute("href") for block in blocks]print("links:", len(links))links = [link for link in links if link]# In[22]:def get_blocks_data(links): driver = webdriver.Chrome() final = [] for link in links: try: event = decode_block(link, driver) final += event except: pass db.TheatersEvents.insert_many(final) print("one courite is ready")# In[23]:def get_date(info): dates = {'апреля': 4, 'мая': 5, 'июня': 6, 'июля': 7, 'августа': 8, 'сентября': 9, 'октября': 10, 'ноября': 11, 'декабря': 12} date = info date = date.split(" ") date[1] = str(dates[date[1]]) date[2] = date[2][-3:-1] date = "/".join(date).replace(",", "") date = datetime.datetime.strptime(date, "%d/%m/%y/%H:%M") return date# In[24]:def decode_block(link, driver): output = [] driver.get(link) time.sleep(1) driver.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN) time.sleep(0.30) driver.find_element_by_tag_name('body').send_keys(Keys.PAGE_DOWN) check = True while check: try: button = driver.find_element_by_xpath( "//button[@class='d-none d-sm-block w-100 button_white m_t_30 ng-tns-c44-0 ng-star-inserted']") button.click() except: check = False name = driver.find_element_by_class_name("p_v_10-sm").text try: description = driver.find_element_by_class_name("current_description_desktop").text.replace("\n", "") except: description = "None" theater = driver.find_elements_by_class_name("w-50")[2].text adress = driver.find_elements_by_class_name("w-50")[3].text infos = driver.find_elements_by_class_name("p_v_20") try: img_link = driver.find_element_by_class_name("event_image div").get_attribute("style") img_link = re.findall("(https.+)\"", img_link)[0] img_name = img_link.split("/")[-1] p = requests.get(img_link) path = f'diploma/{img_name}' out = open(path, "wb") out.write(p.content) out.close() picture = path except: picture = "None" for i in infos: text = i.text try: date = re.findall("\d+\s.+\s\d+:\d+", text)[0] date = get_date(date) except: date = "None" price = re.findall("Цена\n(.+)\n", text)[0] if not price: price = "None" output.append({"date": date, "name": name, "description": description, "cost": price, "link": link, 'theatre': theater, 'picture': picture, 'address': adress}) return output# In[25]:courutines = []n = round(len(links) / 5)links = [links[i:i + n] for i in range(0, len(links), n)]for i in links: courutines.append(threading.Thread(target=get_blocks_data, args=(i,)))for i in courutines: i.start()# In[148]:temp1 = []for i in temp: name = i adress = list(df['address'][df['theatre'] == i])[0] adress = str(adress) cords = requests.get( f"{adress}&apikey=90ed786a-a789-45a1-b782-5f0f9a60bf14") cords = cords.json()["response"]["GeoObjectCollection"]["featureMember"][0]['GeoObject']['Point']['pos'] cords = [float(i) for i in cords.split(" ")] cords = [cords[1], cords[0]] place = {'name': name, 'adress': adress, 'location': cords} temp1.append(place)# In[ ]:# In[149]:# districtfor i in temp1: location = i['location'] place = [] for block in blocks: latitude = list(block.values())[0][0] longitude = list(block.values())[0][1] km = haversine(location[0], location[1], latitude, longitude) name = list(block.keys())[0] place.append([name, km]) place = pd.DataFrame(place, columns=["name", "place"]) place = place.sort_values(by=["place"]) place = list(place["name"][place["place"] >= 3]) i.update({'districts': place[0:4]})# In[150]:# metrosfor i in temp1: location = i['location'] place = [] for block in metro: latitude = list(block.values())[0][0] longitude = list(block.values())[0][1] km = haversine(location[0], location[1], latitude, longitude) name = list(block.keys())[0] place.append([name, km]) place = pd.DataFrame(place, columns=["name", "place"]) place = place.sort_values(by=["place"]) place = list(place["name"][place["place"] >= 3]) i.update({'metro': place[0:4]})# In[45]:blocks = []for i in text: cords = requests.get( f"Москва,{i}&apikey=90ed786a-a789-45a1-b782-5f0f9a60bf14") cords = cords.json()["response"]["GeoObjectCollection"]["featureMember"][0]['GeoObject']['Point']['pos'] cords = [float(i) for i in cords.split(" ")] cords = [cords[1], cords[0]] blocks.append({i: cords})# In[ ]:for i in blocks.keys(): location = blocks[i] km = haversine(location[0], location[1], latitude, longitude) place.append([i["name"], km]) place = pd.DataFrame(place, columns=["name", "place"]) place = place.sort_values(by=["place"]) place = list(place["name"][place["place"] >= 3]) ................
................

In order to avoid copyright disputes, this page is only a partial summary.

Google Online Preview   Download

To fulfill the demand for quickly locating and searching documents.

It is intelligent file search solution for home and business.

Literature Lottery

Related download