You are on page 1of 54

Practical Bot Development: Designing

and Building Bots with Node.js and


Microsoft Bot Framework Szymon
Rozga
Visit to download the full and correct content document:
https://textbookfull.com/product/practical-bot-development-designing-and-building-bot
s-with-node-js-and-microsoft-bot-framework-szymon-rozga/
More products digital (pdf, epub, mobi) instant
download maybe you interests ...

Building Bots with Microsoft Bot Framework Creating


intelligent conversational interfaces 1st Edition
Kishore Gaddam

https://textbookfull.com/product/building-bots-with-microsoft-
bot-framework-creating-intelligent-conversational-interfaces-1st-
edition-kishore-gaddam/

Developing bots with Microsoft Bots Framework: create


intelligent bots using MS Bot Framework and Azure
Cognitive Services 1st Edition Srikanth Machiraju

https://textbookfull.com/product/developing-bots-with-microsoft-
bots-framework-create-intelligent-bots-using-ms-bot-framework-
and-azure-cognitive-services-1st-edition-srikanth-machiraju/

Introducing Azure Bot Service Building Bots for


Business Waghmare

https://textbookfull.com/product/introducing-azure-bot-service-
building-bots-for-business-waghmare/

Beginning AI Bot Frameworks: Getting Started with Bot


Development 1st Edition Manisha Biswas

https://textbookfull.com/product/beginning-ai-bot-frameworks-
getting-started-with-bot-development-1st-edition-manisha-biswas/
Building Telegram Bots: Develop Bots in 12 Programming
Languages using the Telegram Bot API 1st Edition
Nicolas Modrzyk

https://textbookfull.com/product/building-telegram-bots-develop-
bots-in-12-programming-languages-using-the-telegram-bot-api-1st-
edition-nicolas-modrzyk/

Hands On Chatbots and Conversational UI Development


Build chatbots and voice user interfaces with Chatfuel
Dialogflow Microsoft Bot Framework Twilio and Alexa
Skills 1st Edition Srini Janarthanam
https://textbookfull.com/product/hands-on-chatbots-and-
conversational-ui-development-build-chatbots-and-voice-user-
interfaces-with-chatfuel-dialogflow-microsoft-bot-framework-
twilio-and-alexa-skills-1st-edition-srini-janarthanam/

Practical Node.js: Building Real-World Scalable Web


Apps Azat Mardan

https://textbookfull.com/product/practical-node-js-building-real-
world-scalable-web-apps-azat-mardan/

REST API Development with Node.js: Manage and


Understand the Full Capabilities of Successful REST
Development Doglio

https://textbookfull.com/product/rest-api-development-with-node-
js-manage-and-understand-the-full-capabilities-of-successful-
rest-development-doglio/

The Definitive Guide to AdonisJs: Building Node.js


Applications with JavaScript Christopher Pitt

https://textbookfull.com/product/the-definitive-guide-to-
adonisjs-building-node-js-applications-with-javascript-
christopher-pitt/
Practical Bot
Development
Designing and Building Bots
with Node.js and Microsoft
Bot Framework

Szymon Rozga
Practical Bot
Development
Designing and Building
Bots with Node.js and Microsoft
Bot Framework

Szymon Rozga
Practical Bot Development: Designing and Building Bots with Node.js and
Microsoft Bot Framework
Szymon Rozga
Port Washington, New York, USA

ISBN-13 (pbk): 978-1-4842-3539-3 ISBN-13 (electronic): 978-1-4842-3540-9


https://doi.org/10.1007/978-1-4842-3540-9
Library of Congress Control Number: 2018949897

Copyright © 2018 by Szymon Rozga


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or
part of the material is concerned, specifically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way,
and transmission or information storage and retrieval, electronic adaptation, computer software,
or by similar or dissimilar methodology now known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark
symbol with every occurrence of a trademarked name, logo, or image we use the names, logos,
and images only in an editorial fashion and to the benefit of the trademark owner, with no
intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if
they are not identified as such, is not to be taken as an expression of opinion as to whether or not
they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of
publication, neither the authors nor the editors nor the publisher can accept any legal
responsibility for any errors or omissions that may be made. The publisher makes no warranty,
express or implied, with respect to the material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Natalie Pao
Development Editor: James Markham
Coordinating Editor: Jessica Vakili
Cover designed by eStudioCalamar
Cover image designed by Freepik (www.freepik.com)
Distributed to the book trade worldwide by Springer Science+Business Media New York,
233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505,
e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com. Apress Media, LLC is a
California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc
(SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com/
rights-permissions.
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook
versions and licenses are also available for most titles. For more information, reference our Print
and eBook Bulk Sales web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available
to readers on GitHub via the book's product page, located at www.apress.com/978-1-4842-3539-3.
For more detailed information, please visit www.apress.com/source-code.
Printed on acid-free paper
Table of Contents
About the Author���������������������������������������������������������������������������������xi
About the Technical Reviewers���������������������������������������������������������xiii
Preface�����������������������������������������������������������������������������������������������xv

Chapter 1: Introduction to Chat Bots����������������������������������������������������1


The Expectations Game����������������������������������������������������������������������������������������3
What Is a Chat Bot?�����������������������������������������������������������������������������������������������4
Why Now?�����������������������������������������������������������������������������������������������������������11
Advancements in Artificial Intelligence���������������������������������������������������������11
Messaging Apps as a Conversational Intelligence Platform��������������������������13
Voice-Activated Intelligent Assistants�����������������������������������������������������������14
Why Should We Create Bots?������������������������������������������������������������������������������15
Bot Anatomy��������������������������������������������������������������������������������������������������������18
Bot Runtime���������������������������������������������������������������������������������������������������18
Natural Language Understanding Engine������������������������������������������������������20
Conversation Engine��������������������������������������������������������������������������������������22
Channel Integration���������������������������������������������������������������������������������������25
Conclusion����������������������������������������������������������������������������������������������������������27

Chapter 2: Chat Bot Natural Language Understanding�����������������������29


Natural Language Machine Learning Background����������������������������������������������32
Common NLP Tasks���������������������������������������������������������������������������������������������41
Syntax������������������������������������������������������������������������������������������������������������41
Semantics������������������������������������������������������������������������������������������������������41

iii
Table of Contents

Discourse Analysis����������������������������������������������������������������������������������������42
Common Bot NLU Tasks��������������������������������������������������������������������������������������42
Cloud-Based NLU Systems���������������������������������������������������������������������������������44
Enterprise Space�������������������������������������������������������������������������������������������������45
Conclusion����������������������������������������������������������������������������������������������������������46

Chapter 3: Language Understanding Intelligent Service (LUIS)����������47


Classifying Intents�����������������������������������������������������������������������������������������������50
Publishing Your Application���������������������������������������������������������������������������������58
Extracting Entities�����������������������������������������������������������������������������������������������64
Age, Dimension, Money, and Temperature�����������������������������������������������������67
DatetimeV2����������������������������������������������������������������������������������������������������69
E-mails, Phone Numbers, and URLs��������������������������������������������������������������77
Number, Percentage, and Ordinal������������������������������������������������������������������77
Entity Training�����������������������������������������������������������������������������������������������������79
Custom Entities���������������������������������������������������������������������������������������������������83
Simple Entities����������������������������������������������������������������������������������������������84
Composite Entities�����������������������������������������������������������������������������������������94
Hierarchical Entities������������������������������������������������������������������������������������102
List Entities��������������������������������������������������������������������������������������������������107
Regular Expressions Entities�����������������������������������������������������������������������109
Prebuilt Domains�����������������������������������������������������������������������������������������������109
A Historical Point�����������������������������������������������������������������������������������������111
Phrase Lists������������������������������������������������������������������������������������������������������112
Active Learning�������������������������������������������������������������������������������������������������115
Dashboard Overview�����������������������������������������������������������������������������������������116
Managing and Versioning Your Application�������������������������������������������������������118
Integrating with Spell Checking������������������������������������������������������������������������121

iv
Table of Contents

Import/Export Application���������������������������������������������������������������������������������124
Using the LUIS Authoring API����������������������������������������������������������������������������125
Troubleshooting Your Models����������������������������������������������������������������������������126
Conclusion��������������������������������������������������������������������������������������������������������128

Chapter 4: Conversation Design�������������������������������������������������������129


Common Use Cases������������������������������������������������������������������������������������������130
Common Consumer Cases��������������������������������������������������������������������������130
Common Enterprise Cases��������������������������������������������������������������������������138
Representing Conversations�����������������������������������������������������������������������������141
Bot Responses��������������������������������������������������������������������������������������������������144
Building Blocks��������������������������������������������������������������������������������������������144
Authentication and Authorization in Bots����������������������������������������������������149
Specialized Cards����������������������������������������������������������������������������������������151
Other Functions�������������������������������������������������������������������������������������������������156
Conversational Experience Guidelines��������������������������������������������������������������157
Focus�����������������������������������������������������������������������������������������������������������157
Don’t Pretend the Bot Is a Human���������������������������������������������������������������158
Do Not Gender Bots�������������������������������������������������������������������������������������160
Always Present the Next Best Action�����������������������������������������������������������160
Have a Consistent Tone�������������������������������������������������������������������������������161
Utilize Rich Content�������������������������������������������������������������������������������������162
Be Forgiving������������������������������������������������������������������������������������������������162
Avoid Getting Stuck�������������������������������������������������������������������������������������163
Don’t Abuse Proactive Messaging���������������������������������������������������������������163
Provide a Clear Path to Humans������������������������������������������������������������������163
Learn from Your Users���������������������������������������������������������������������������������165
Conclusion��������������������������������������������������������������������������������������������������������166

v
Table of Contents

Chapter 5: Introducing the Microsoft Bot Framework����������������������167


Microsoft Bot Builder SDK Basics���������������������������������������������������������������������168
Bot Framework End-to-End Setup��������������������������������������������������������������������187
Step 1: Connecting to Azure������������������������������������������������������������������������188
Step 2: Creating the Bot Registration����������������������������������������������������������191
Step 3: Securing Our Bot�����������������������������������������������������������������������������194
Step 4: Setting Up Remote Access��������������������������������������������������������������195
Step 5: Connecting to Facebook Messenger�����������������������������������������������197
Step 6: Deploying to Azure���������������������������������������������������������������������������204
What Did We Just Do?���������������������������������������������������������������������������������������210
Microsoft Azure�������������������������������������������������������������������������������������������210
Bot Channels Registration Entry������������������������������������������������������������������211
Authentication���������������������������������������������������������������������������������������������212
Connectivity and Ngrok�������������������������������������������������������������������������������212
Deploying to Facebook Messenger�������������������������������������������������������������213
Deploying to Azure���������������������������������������������������������������������������������������214
Key Bot Builder SDK Concepts��������������������������������������������������������������������������214
Sessions and Messages������������������������������������������������������������������������������215
Waterfalls and Prompts�������������������������������������������������������������������������������221
Dialogs���������������������������������������������������������������������������������������������������������225
Invoking Dialogs������������������������������������������������������������������������������������������232
Recognizers�������������������������������������������������������������������������������������������������235
Building a Simple Calendar Bot������������������������������������������������������������������������239
Conclusion��������������������������������������������������������������������������������������������������������241

vi
Table of Contents

Chapter 6: Diving into the Bot Builder SDK��������������������������������������243


Conversation State��������������������������������������������������������������������������������������������243
Messages����������������������������������������������������������������������������������������������������������246
Addresses and Proactive Messages�����������������������������������������������������������������251
Rich Content������������������������������������������������������������������������������������������������������253
Buttons��������������������������������������������������������������������������������������������������������������259
Cards�����������������������������������������������������������������������������������������������������������������265
Suggested Actions��������������������������������������������������������������������������������������������272
Channel Errors��������������������������������������������������������������������������������������������������276
Channel Data�����������������������������������������������������������������������������������������������������276
Group Chat��������������������������������������������������������������������������������������������������������282
Custom Dialogs�������������������������������������������������������������������������������������������������286
Actions��������������������������������������������������������������������������������������������������������������294
Extra Notes on Actions��������������������������������������������������������������������������������300
Libraries������������������������������������������������������������������������������������������������������������302
Conclusion��������������������������������������������������������������������������������������������������������304

Chapter 7: Building an Integrated Bot Experience����������������������������305


A Word on OAuth 2.0�����������������������������������������������������������������������������������������306
Setting Up Google APIs��������������������������������������������������������������������������������������307
Integrating Authentication with Bot Builder������������������������������������������������������315
Seamless Login Flow����������������������������������������������������������������������������������������323
Integrating with the Google Calendar API���������������������������������������������������������336
Implementing the Bot Functionality������������������������������������������������������������������345
Conclusion��������������������������������������������������������������������������������������������������������353

vii
Table of Contents

Chapter 8: Extending Channel Functionality�������������������������������������355


Deeper Slack Integration����������������������������������������������������������������������������������355
Connecting to Slack������������������������������������������������������������������������������������������362
Experimenting with the Slack APIs�������������������������������������������������������������������370
Simple Interactive Message������������������������������������������������������������������������������379
Multistep Experience����������������������������������������������������������������������������������������391
Conclusion��������������������������������������������������������������������������������������������������������406

Chapter 9: Creating a New Channel Connector���������������������������������407


The Direct Line API��������������������������������������������������������������������������������������������408
Custom Web Chat Interface�������������������������������������������������������������������������������411
Voice Bots���������������������������������������������������������������������������������������������������������428
Twilio�����������������������������������������������������������������������������������������������������������429
Integrating Our Bot with Twilio��������������������������������������������������������������������������431
Integrating with SSML��������������������������������������������������������������������������������������447
Final Touches����������������������������������������������������������������������������������������������������452
Conclusion��������������������������������������������������������������������������������������������������������457

Chapter 10: Making the Chat Bot Smarter����������������������������������������459


Spell-Checking��������������������������������������������������������������������������������������������������462
Sentiment����������������������������������������������������������������������������������������������������������471
Supporting Multiple Languages������������������������������������������������������������������������474
QnA Maker��������������������������������������������������������������������������������������������������������482
Computer Vision������������������������������������������������������������������������������������������������489
Conclusion��������������������������������������������������������������������������������������������������������496

viii
Table of Contents

Chapter 11: Adaptive Cards and Custom Graphics���������������������������499


Adaptive Cards��������������������������������������������������������������������������������������������������501
A Working Example��������������������������������������������������������������������������������������512
Rendering Custom Graphics�����������������������������������������������������������������������������518
Conclusion��������������������������������������������������������������������������������������������������������545

Chapter 12: Human Handoff��������������������������������������������������������������547


We Still Need Humans��������������������������������������������������������������������������������������548
Chat Bots from a Customer Service Perspective����������������������������������������������548
Always-On Chat Bot�������������������������������������������������������������������������������������549
Sometimes-On Chat Bot������������������������������������������������������������������������������549
CSR-Facing Chat Bot�����������������������������������������������������������������������������������550
Typical Customer Service System Concepts�����������������������������������������������������550
Integration Approaches�������������������������������������������������������������������������������������552
Custom-Built Interface��������������������������������������������������������������������������������552
On Platform�������������������������������������������������������������������������������������������������552
Product��������������������������������������������������������������������������������������������������������554
Facebook Messenger Handover Sample�����������������������������������������������������������557
Conclusion��������������������������������������������������������������������������������������������������������570

Chapter 13: Chat Bot Analytics���������������������������������������������������������571


Common Data Questions�����������������������������������������������������������������������������������572
Generic Data������������������������������������������������������������������������������������������������572
Demographics���������������������������������������������������������������������������������������������573
Sentiment����������������������������������������������������������������������������������������������������574
User Retention���������������������������������������������������������������������������������������������575
User Session Flows�������������������������������������������������������������������������������������576

ix
Table of Contents

Analytics Platforms�������������������������������������������������������������������������������������������577
Integrating with Dashbot and Chatbase������������������������������������������������������������581
Conclusion��������������������������������������������������������������������������������������������������������590

Chapter 14: Applying Our Learnings: Alexa Skills Kit�����������������������591


Introduction�������������������������������������������������������������������������������������������������������591
Creating a New Skill������������������������������������������������������������������������������������������595
Alexa NLU and Automatic Speech Recognition�������������������������������������������������598
Diving Into Alexa Skills Kit for Node������������������������������������������������������������������607
Other Options����������������������������������������������������������������������������������������������������621
Connecting to Bot Framework��������������������������������������������������������������������������624
Implementation Decisions Around Bot Framework and Alexa Skills Kit
Integration���������������������������������������������������������������������������������������������������624
Sample Integration��������������������������������������������������������������������������������������628
Conclusion��������������������������������������������������������������������������������������������������������639

Index�������������������������������������������������������������������������������������������������641

x
About the Author
Szymon Rozga has 15 years of hands on experience in the software
development industry. He found a passion working on front end
applications on Wall Street. The interest in attention to user interface
details would take him on a tour of the different user interface technologies
on the Windows, Web and iOS/Android platforms. He has managed teams
of engineers on a variety of projects and since 2016, he has dedicated
his time to building chat bots for clients across text and voice channels.
He has built a practice around the technologies at BlueMetal, An Insight
Company, and is involved in a handful of chat bot projects at any time. As
Chief Architect of Emerging Technologies, he keeps cognitively flexible by
reading and watching presentations about new technologies, educating
clients, leading discovery sessions, scoping and guiding engagements,
mentoring engineers and helping clients apply technologies such as Chat
Bots, Blockchain and Augmented Reality to business problems.
In his spare time, he enjoys taking walks, reading fiction, going to the
beach, playing guitar, and spending time with his wife Kim, his son Teddy,
and his Golden Retriever, Chelsea.

xi
About the Technical Reviewers
Alp Tunc is a software engineer with a master of science degree from Ege
University in Izmir, Turkey. He has 20 years of experience in the industry as
a developer/architect/project manager on projects of various sizes. He has
hands-on experience in a broad range of technologies. Besides technology,
he loves freezing moments in spectacular photographs, trekking into the
unknown, running, reading, and listening to jazz. He loves cats and dogs.

Jim O’Neil is a Microsoft Azure MVP and senior architect at BlueMetal


(an Insight Company), a modern application consulting firm
headquartered in Watertown, Massachusetts, where he is primarily
focused on designing and implementing IoT solutions for a variety of
industries. A former Microsoft Developer Evangelist for the Northeast
United States, he remains active in the New England software community
as a speaker and organizer of technical and nonprofit events, namely, New
England GiveCamp. In his spare time, he noodles around in genealogy and
DNA testing through which he’s found both of his birth parents’ families.

xiii
Preface
In mid-2016, I started work on a fascinating project. A client wanted to have
users with type 2 diabetes be able to get advice from an automated coach, in
other words, a chat bot. It was a fascinating idea. I had many questions. Why
would anyone want to have a natural language conversation with a machine?
Is it possible to make this thing smart enough to accomplish its goals? How
do you even begin creating a chat bot? Through which means are users
supposed to interact with it? When the project ended, we quickly realized
that the technologies we just utilized, natural language understanding,
Microsoft’s Bot Framework, and custom machine learning models, could
serve as the technical base for a wide array of natural language applications
between users and computing systems. Natural language interfaces, after
all, were all the rage. The Alexa-powered Echo Dot had just been released,
and the general population was quickly becoming fascinated with the idea
of communicating with digital assistants by talking to them. My friend and I
jumped on the opportunity to become experts in this space.
We tried many of the different platforms such as Api.ai (now
DialogFlow), Wit.ai, and Watson Conversation but decided to focus on
Microsoft’s Bot Framework as we felt it best complemented the enterprise
space. Chat bot startups sprung up across the landscape promising the
best bot or bot platform. The field became saturated, and our customers
started paying attention. Suddenly, I found myself talking to multiple
clients a day. Initially, these were high-level mentorship sessions. What is
a chat bot? How does it work? What channels does it work with? Does it
learn by itself? Can it integrate with live chat?
Starting around mid-2017, these conversations slowly shifted from
educating clients to scoping the development effort for all types of use
cases. Clients were starting to apply the technology to solve their business

xv
Preface

problems. In the second half of 2017, while working on delivering multiple


chat bot implementations, a colleague of mine connected me to the editors
who would make this book happen. Taking on this project was an easy
decision to make; it was a fascinating topic, it was a new space, and it had
lots of possibilities. Being slightly on the naïvely optimistic side about a
three-month old’s sleep patterns, I jumped on the opportunity.
I decided to write the book in the same way I would mentor engineers
on the topics. It is divided roughly into three sections. First, I introduce the
topics of chat bots and machine learning (ML) in Chapters 1 and 2.
Although chat bots can, and often do, exist independently of any ML
algorithms, the truth is that users expect chat bots to exhibit some forms
of intelligence, minimally a bit of natural language understanding. As
such, I want to set the state on ML and how it may be applied in natural
language conversations. Chapter 3 is a deep dive into Microsoft’s Language
Understanding Intelligence Service (LUIS), which we will utilize to create
natural language understanding models for our chat bot.
The second section is all about hands-on Bot Framework
development. Chapter 4 introduces the concept of conversation design,
which is the practice of modeling a chat bot conversation. Chapter 5 guides
us through the creation of a Bot Framework chat bot connected to a LUIS
model and its deployment into an Azure app service. In Chapter 6, we take
a step back to examine the features and capabilities of the Bot Builder SDK,
and in Chapter 7 we integrate our chat bot with an OAuth implementation
and external APIs. Chapter 8 is a deeper exploration into Slack bots, and,
finally, Chapter 9 explores the ability to connect any channel to our chat
bot via the Direct Line API. We marry Twilio Voice into the picture to create
a chat bot we can talk to via a phone.
The third section addresses a few additional topics that are essential
to chat bot development. Chapter 10 adds extra intelligence abilities to
our chat bots by focusing on a select set of Microsoft’s Cognitive Services.
Chapter 11 explores two manners of creating custom cards for our chat
bots: adaptive cards and custom graphic renderings. We explore human

xvi
Preface

handover in Chapter 12, we learn about chat bot analytics in Chapter 13,
and, finally, in Chapter 14 we put all our newly gained knowledge to work
by creating a simple Alexa skill using Amazon’s Alexa Skills Kit and then
replicate the same experience using a Bot Framework bot.
The chat bot space is dynamic. During the development of this
book, Facebook acquired Wit.ai and shifted its focus to natural language
understanding, Google acquired Api.ai, LUIS changed user interfaces not
once but twice, the Bot Framework was officially released and moved to
Azure, QnA Maker was officially released, Alexa’s user interface changed after
I had written all the content, and Microsoft announced tons of new features
at Build 2018 (which luckily did not drastically change the topics treated
in this book). We have reached a point where the subjects of this book are
relatively stable. It is my hope that the content is essential to any developer
looking to begin chat bot development using Microsoft’s Bot Framework.
This project has been a humbling experience and would not have
been possible without a small group of people for whose support I
am forever grateful. I would like to thank my wife Kim, without whose
patience, kindness, support, and late-night help with editing I would
have never completed the process. I would also like to thank Jeff Dodge
for the collaboration on building our chat bot practice, Bob Familiar for
introducing me to the Apress team, and BlueMetal for allowing me the
room to work on this project. Big thanks to Matt, Jimmy, and Andrew, and
my parents, Hanna and Krzysztof Rozga, for providing much needed moral
support and words of encouragement during times when I felt I was white
knuckling it. I would also like to acknowledge the Apress editors Natalie
and Jessica for their support during the book writing process.
This book is dedicated to Teddy.

—Szymon Rozga
June 1, 2018
Port Washington, New York

xvii
CHAPTER 1

Introduction to
Chat Bots
In recent years, chat bots and artificial intelligence (AI) have become
a hot topic in the tech sector and the public imagination. Chat bots,
computer programs that can communicate using natural language, are
doing everything from ordering pizza to buying clothes to saving money
on parking tickets1 to negotiating among themselves.2 Initially, developing
a chat bot was tantamount to developing an integration with a messaging
platform. There was no easy way to represent a conversation flow in code.
When Microsoft created the Bot Framework and the Bot Builder SDK, this
changed. Microsoft created a rich environment in which the developer
was liberated from the concerns of integrating with individual channels
and could focus on writing code that performed the conversational tasks
a chat bot needs to accomplish. The Bot Builder SDK provided a generic
approach to the development of conversational experiences. Microsoft’s
Bot Connectors implemented the logic to translate from the generic format
to channel-specific messages.

1
 obot Lawyers Makes Case Against Parking Tickets:
R
http://www.npr.org/2017/01/16/510096767/
robot-lawyer-makes-the-case-against-parking-tickets
2
Deal or no deal? Training AI bots to negotiate: https://code.facebook.com/
posts/1686672014972296/deal-or-no-deal-training-ai-bots-to-negotiate/

© Szymon Rozga 2018 1


S. Rozga, Practical Bot Development, https://doi.org/10.1007/978-1-4842-3540-9_1
Chapter 1 Introduction to Chat Bots

The result is that chat bot development has become significantly more
accessible to millions of developers. Engineers no longer have to learn the
ins and outs of integrating with something like Facebook’s Messenger APIs
or Slack’s Web API. Instead, developers focus on core bot logic and the
conversational experience. Microsoft worries about the rest.
The Bot Builder SDK is available for .NET and Node.js and is run as
an open source MIT-licensed project on GitHub.3 The team is active in
both development and responding to the various issues that development
teams run into. And the team is friendly to boot!
In December 2017, Microsoft made both the Bot Framework and the
Language Understanding Intelligence Service (LUIS) generally available.
LUIS is Microsoft’s natural language service that will aid us in adding
conversational intelligence to our bots. The Bot Framework is now also
called the Azure Bot Service; the two refer to the same thing. As implied
by the name, the Azure Bot Service is now a full-fledged part of Microsoft’s
Azure cloud offering. Microsoft has also provided free tiers of the service so
we can play with the framework to our heart’s content. All of the samples
and techniques in the book can be experimented with at no cost!
Over the last years, all the big tech companies like Microsoft, Facebook,
and Google, as well as many smaller ones, have been taking a stab at
creating the best and easiest-to-use chat bot development frameworks.
The field is very dynamic. Frameworks come and go. Things seem
to change daily. Despite the space’s dynamic nature, Microsoft’s Bot
Framework remains the best platform for developing powerful, fast, and
flexible chat bots. I am thrilled to take you on a journey through chat bot
development using this tool.

3
 icrosoft Bot Builder SDK on GitHub: https://github.com/Microsoft/
M
BotBuilder

2
Chapter 1 Introduction to Chat Bots

The Expectations Game


For more than two years now, a substantial chunk of my conversations with
customers has been spent on discussing chat bot capabilities, what they are,
and, more importantly, what they are not. Our culture largely confounds
chat bot abilities with artificial intelligence, and it is easy to see why. Some
chat bots employ rich natural language capabilities, leading us to imagine
there is more to them. Likewise, voice-based digital assistants such as
Cortana, Alexa, and Google Assistant live in our homes and may be spoken
to like real humans. Why wouldn’t chat bots display more intelligence?
The culture is additionally permeated with references to the likes of
IBM’s Watson on Jeopardy,4 the New York Times’ feature on the Google
Brain team5 and their feats in language translation using deep learning,
self-driving cars, and AlphaZero destroying the world’s highest-rated
chess-playing engine after only four hours of learning how to play chess.6
These and many other stories highlight the investment and interest in
these techniques, foreshadowing the kind of AI-driven interactions with
our devices that we are heading toward. Developments in the field of AI
have changed the way we interact with, as well as what we expect from,
our technology. Assigning human attributes and abilities to our devices is
becoming more prevalent. Thinkers in the cognition and science-fiction
spaces have long grappled with this possibility as popularized by Asimov’s
Three Laws of Robotics, a set of rules that robots obey to ensure the robots
don’t go after humans. And now that there are some clear and concrete AI
examples in the real world, that kind of reality seems so much closer.

4
I BM Watson: The inside story of how the Jeopardy-winning supercomputer
was born, and what it wants to do next: http://www.techrepublic.com/
article/ibm-watson-the-inside-story-of-how-the-jeopardy-winning-
supercomputer-was-born-and-what-it-wants-to-do-next/
5
The Great A.I. Awakening: https://www.nytimes.com/2016/12/14/magazine/
the-great-ai-awakening.html
6
Google’s AlphaZero Destroys Stockfish In 100-Game Match: https://www.chess.
com/news/view/google-s-alphazero-destroys-stockfish-in-100-game-match

3
Chapter 1 Introduction to Chat Bots

Yet, reality does not match the expectations set forth by AI’s successes
in some very specific problem areas. Although we have made tremendous
leaps and bounds in terms of natural language processing, computer
vision, emotion detection, and so forth, composing all of these pieces
into a human-like intelligence, usually referred to as Artificial General
Intelligence AGI, is not yet within our grasp and is not a realistic target for
chat bots. For every article that celebrates the tremendous achievements
in the AI space, there’s a matching article downplaying the hype around
the same technology and showing examples of why this type of AI is still
far from perfect (think of the articles showing all the images that computer
vision algorithms still can’t correctly classify). As with any technology
that has been hyped up in the media, we must be reasonable with the
expectations we set on it.
Are our bots going to be agents with human-level intelligence having
conversations with our users? No. Given the technology and the tasks
we want our bots to accomplish, can we make our bots perform those
tasks very well? Absolutely. This book aims to equip the reader with
the necessary skill to build compelling, engaging, and useful chat bots.
It is up to the engineer how much of the latest AI techniques you want
to incorporate during this journey. Certainly, these techniques are not
required for a great chat bot.

What Is a Chat Bot?


At the most basic level, a chat bot, also referred to simply as a bot
throughout this book, is a computer program that can take user input
in natural language and return text or rich media to the user. The user
communicates with the chat bot via a messaging app, such as Facebook
Messenger, Skype, Slack, and others, or via a voice-activated device such as
the Amazon Echo, Google Home, or Harmon Kardon’s Invoke powered by
Microsoft’s Cortana.

4
Chapter 1 Introduction to Chat Bots

Figure 1-1 illustrates our first bot built using Microsoft Bot Framework.
This bot simply returns the same message to the user prefixed by the string
“echo: ”. The logic that runs this experience on the Bot Framework is brain-­
dead simple.

var bot = new builder.UniversalBot(connector, [


    function (session) {
        // for every message, send back the text prepended by
echo:
        session.send('echo: ' + session.message.text);
    }
]);

Figure 1-1. A simple echo bot

5
Chapter 1 Introduction to Chat Bots

This is a chat bot. Basic and not terribly useful, right? We can just as
easily create a YouTube bot that, given user text input, searches for videos
on that topic and sends the user links to those videos (Figures 1-2 and 1-3).

Figure 1-2. Cats are OK

This is another basic bot that does just one thing, and it kind of does
it well. It integrates with the YouTube API, uses your input as a search
parameter, and returns what are referred to in the Bot Framework as cards,
something we will explore later in the book. The images make for a richer
and more engaging experience—a bit more interesting but still rather
basic.

6
Chapter 1 Introduction to Chat Bots

Figure 1-3. Dogs are way better!

The code for this one is shown next. We make a request to YouTube
and translate the response from YouTube format to Bot Framework cards.

const bot = new builder.UniversalBot(connector, [


    session => {
        const url = vsprintf(urlTemplate, ­
[session.message.text]);

        request.get(url, (err, response, body) => {


            if (err) {
                console.log('error while fetching video:\n' + err);
                
session.endConversation('error while fetching
video. please try again later.');

7
Chapter 1 Introduction to Chat Bots

                return;
            }

            const result = JSON.parse(body);


            // we have at most 5 results
            let cards = [];

            result.items.forEach(item => {
                const card = new builder.HeroCard(session)
                    .title(item.snippet.title)
                    .text(item.snippet.description)
                    .images([
                        builder.CardImage.create(session, item.
snippet.thumbnails.medium.url)
                    ])
                    .buttons([
                        builder.CardAction.openUrl(session,
'https://www.youtube.com/watch?v=' +
item.id.videoId, 'Watch Video')
                    ]);
                cards.push(card);
            });

            const reply = new builder.Message(session)


                .text('Here are some results for you')
                .attachmentLayout(builder.AttachmentLayout.
carousel)
                .attachments(cards);

            session.send(reply);
        });
    }
]);

8
Chapter 1 Introduction to Chat Bots

OK, how about this? We can have a bot that, given a statement, can
tell whether it’s a neutral, positive, or negative statement and return an
appropriate response (Figure 1-4). We don’t show it, but the code for this
one is as straightforward as the earlier examples: we fetch a sentiment
score from a simple sentiment REST API and use it to render an answer.

Figure 1-4. A simple example of utilizing AI to drive a conversation

This is a simple example showing how easy our code can integrate with
AI, if we were to go that route. Bots don’t always have to follow a question-­
response pattern. Bots can reach out to users proactively. For example, we
could have a fraud alert bot (Figure 1-5).

9
Chapter 1 Introduction to Chat Bots

Figure 1-5. Proactive user messaging

A bot can be more task driven. Imagine, for example, a calendar


bot that can create appointments, check availability, edit or delete
appointments, and give you a summary of your calendar (Figure 1-6).

Figure 1-6. A simple calendar bot integrated with Google Calendar

10
Chapter 1 Introduction to Chat Bots

Now things are starting to get a bit more interesting. We are starting to
take natural language and to act on it.

W
 hy Now?
Why are bots becoming such a big deal? Certainly, they have existed in
all kinds of incarnations in old-school apps like IRC7 and AOL Instant
Messenger.8 And these were not little experiments. IRC bots have been
around for a long time. I remember interacting with quite a few bots over
IRC. Being young and naïve when it came to technology, I initially thought
there was an actual human responding to my messages. I quickly grasped
the idea that there was a machine sitting somewhere responding to what I
was writing. The more I interacted with IRC bots, the more I treated them
like a command line. This, however, was all pretty niche technology at the
time. The public wasn’t interacting with bots on a daily basis so there was
no need to cater to natural language interactions.
Today, the way we interact with the technology around us is
completely different, and it is driven by three forces: advancements in AI,
the idea of messaging apps as a conversational intelligence platform, and
voice-activated conversational interfaces.

Advancements in Artificial Intelligence


Throughout the 20th century, computer scientists, biologists, linguists,
and economists have made tremendous strides in the fields of cognition,
artificial intelligence, artificial life, machine learning, and deep learning.
The very concept of a computer program executing instructions, the

7
IRC Bots: https://en.wikipedia.org/wiki/IRC_bot
8
SmarterChild: https://en.wikipedia.org/wiki/SmarterChild

11
Chapter 1 Introduction to Chat Bots

Universal Turing Machine9 and the idea of a computer architecture that


can digitally store code and execute the code taking inputs and producing
outputs, and the Von Neumann architecture,10 are recent in human history
standards but are the underlying concepts that our work on computers is
based on. The beginnings of the ideas around neural networks were first
published in 1943 by McCulloch and Pitts in their paper “A logical calculus
of the ideas immanent in nervous activity.”11 In 1950, Asimov included
the Three Laws of Robotics in his book I, Robot.12 That same year, the
first paper describing how a computer can play chess, “Programming a
Computer for Playing Chess” by Claude Shannon, was published. He went
on to essentially inventing the field of information theory.13 From the 1960s
and onward, the amount of research and growth in the space has been
mind-blowing; we see proof of this every day in media coverage of the
latest AI applications.
Suffice it to say, since the 1960s, machine learning and the process of
building our own models using a variety of algorithms have become better
performing and more accessible. Libraries such as scikit-learn for Python
and Google’s Tensor Flow, among many others, are well documented with
strong community support. The big technology firms have also invested
enough in their computational capacity and power to be able to work on

9
 niversal Turing Machine: https://en.wikipedia.org/wiki/
U
Universal_Turing_machine
10
Von Neumann Architecture: https://en.wikipedia.org/wiki/
Von_Neumann_architecture
11
A Logical Calculus of Ideas Immanent in Nervous Activity: http://www.cs.cmu.
edu/~epxing/Class/10715/reading/McCulloch.and.Pitts.pdf
12
The Three Laws of Robotics: https://en.wikipedia.org/wiki/
Three_Laws_of_Robotics
13
Programming a Computer for Playing Chess: http://archive.
computerhistory.org/projects/chess/related_materials/
text/2-0%20and%202-1.Programming_a_computer_for_playing_chess.
shannon/2-0%20and%202-1.Programming_a_computer_for_playing_chess.
shannon.062303002.pdf

12
Chapter 1 Introduction to Chat Bots

some of the most computationally intensive tasks in a reasonable time


frame. Microsoft, Amazon, Google, IBM, and others are now involved in
cloud platforms in one way or another. The next step has been to offer
some of these machine learning algorithms on demand. If we simply
examine Microsoft’s Cognitive Services as an example, we find 30 APIs at
the time of this writing. These include computer vision tools like Face and
Emotion Detection, Content Moderation, and OCR capabilities. It also
includes language tools such as Natural Language Processing, Linguistic
and Text Analytics, and Natural Language Understanding. It even includes
search and knowledge tools such as Recommendations engines and
Sematic Search. The availability of services that any developer can plug
into at any time to access these powerful features at a reasonable cost is
a significant reason why intelligent systems are becoming so much more
prevalent in our lives and is one of the great pieces of infrastructure that
our bots can take advantage of. We will look at Microsoft’s Cognitive
Services in Chapter 10.

 essaging Apps as a Conversational


M
Intelligence Platform
Mobile messaging apps have become all the rage in recent years. Snapchat,
Slack, Telegram, iMessage, FB Messenger, WhatsApp, and WeChat are
some of the most used apps on a mobile user’s phone. In fact, their usage
has surpassed that of social networks such as Facebook. According to
Business Insider, messaging apps began being more used than social
networks sometime around the first quarter of 2015, and the trend has
continued since then. Although this book will not get into details around
all the relevant players in the U.S. and global markets, the key point is that
Asia-based messaging apps such as WeChat and LINE have figured out the
best way to grow usage via chat apps and how to monetize that usage. The
monetization trend has not yet fully caught up to the U.S. market, but firms

13
Another random document with
no related content on Scribd:
parmi les guides les plus actifs de la civilisation contemporaine, en
bien comme en mal.
— … Pas plus qu’un représentant qualifié du travail, de cette
formidable puissance qui s’appelle « les syndicats ouvriers ». Le
camarade Jouhaux n’a jamais songé à se présenter, et nul n’y pense
pour lui. L’Académie échantillonne les anciennes forces dirigeantes
de la communauté, non pas celles qui ne sont apparues que depuis
Richelieu. En cela elle manque d’imagination. Mais cela viendra un
jour. Par degrés. Très lentement. Comme toutes les vieilles
institutions, l’Académie ne peut évoluer qu’en ayant l’air de ne pas
évoluer. A cet égard elle est presque logée à la même enseigne que
l’Église catholique.
— Et, poursuivit Pamphile, est-ce qu’elle sert à quelque chose,
l’Académie ? J’avoue que je ne discerne pas bien à quoi. Vous
n’allez point, n’est-ce pas, me parler du Dictionnaire. Il serait
dérisoire d’assembler depuis quatre siècles quarante personnes, en
aucune façon du reste, pour la plus grande part, préparées par leur
profession à ce travail, et de les habiller en vert pomme, uniquement
pour rédiger un Dictionnaire !
— Rien de plus certain. Mais, Pamphile, à quoi sert aux Anglais
de mettre, dans l’abbaye de Westminster, les statues de leurs
grands hommes, dont la plupart ne se recommandent point des
mérites de leurs sculpteurs ?
— L’Angleterre les veut ainsi honorer ; ce faisant, elle s’honore
elle-même. Cela lui donne, aux yeux des étrangers et de ses
propres citoyens, quelque grandeur.
— L’Académie Française, pareillement, est une sorte de musée,
mais de personnages encore en vie. Et voyez un peu, entre
parenthèses, l’évolution qui s’est faite dans l’esprit national : en
associant lorsqu’elle fut créée, de grands seigneurs et de simples
écrivains, son fondateur entendait relever ceux-ci devant l’opinion ;
du moins c’est ainsi qu’on le considéra bientôt. A cette heure, c’est
plutôt la présence des écrivains qui relève, devant l’opinion, la
qualité de ceux de ses membres qui ne sont point des
professionnels de la pensée écrite. De là vient même cette erreur
générale, dont vous venez de vous faire l’écho, que pour faire partie
de l’Académie, l’on devrait être auteur. Cela prouve l’éminente
situation des écrivains dans la société contemporaine — en France,
car il n’en est pas tout à fait de même ailleurs. On peut dire que les
lettres de noblesse de la profession littéraire, chez nous, datent de
1635, année, comme chacun sait, de la fondation de l’Académie.
C’est pourquoi les écrivains tiennent tant à en être ; et la sélection
distinguée de la compagnie lui vaut, à l’étranger, une estime qui
n’est pas sans exercer une salutaire influence. L’Académie, on l’a vu
pendant la guerre, et depuis, est un excellent agent de propagande
nationale.
— Voilà pour l’étranger. Mais à l’intérieur ?
— A l’intérieur, au point de vue strictement littéraire, il est bien
possible qu’elle ne serve pas à grand’chose, malgré les
récompenses dont elle est dispensatrice. Indirectement, il n’en est
pas de même.
— Indirectement ?
— Elle agit comme frein régulateur. Il n’est pas d’écrivain de
quelque mérite, c’est-à-dire de quelque ambition, qui ne se figure
avoir l’épée d’académicien dans son plumier. Cela n’est pas sans
exercer une action, après tout bienfaisante, sur sa manière de
concevoir l’œuvre d’art, et son respect de la langue. Par essence, la
profession est anarchique, elle se place au-dessus des conventions
morales et sociales. Il arrive qu’on s’en aperçoive un peu trop, bien
qu’il ne me semble pas mauvais, en somme, qu’il en soit ainsi. Mais
son désordre et, si j’ose dire, son irrespect souvent heureux,
seraient bien plus grands encore si les écrivains ne songeaient
parfois à se réserver, le temps venu, les faveurs de celle qu’entre
eux ils appellent « la vieille dame ».
— Cela me paraît vrai… et je n’y avais point pensé.
— Mon cher Pamphile, ce qu’il y a toujours de plus difficile à
distinguer, c’est ce qu’on a quotidiennement sous les yeux,
justement parce qu’on a l’habitude de le voir, et qu’alors on n’y fait
plus attention. Telles sont les actions et les réactions des différents
éléments de la société contemporaine les uns sur les autres.
— Vous parliez tout à l’heure des prix, si nombreux, que
l’Académie distribue chaque année. Vous n’avez pas l’air d’y porter
grand intérêt.
— C’était pour aller vite, et parce que j’avais autre chose à dire.
En réalité, ils aident à vivre quelques modestes et sérieux
travailleurs que leurs ouvrages n’enrichissent pas, dans le domaine
de l’histoire, même littéraire, et de la morale. Pour ceux de pure
littérature, il n’en va pas tout à fait ainsi, par cette raison sans doute
qu’il y en a trop, et que l’attention s’y égare. Peut-être aussi parce
que, agissant, comme je l’ai dit, à la manière d’un frein, l’Académie
suit de loin le goût du public et les tendances des auteurs, au lieu de
les provoquer.
— Mais il y a aussi les prix de vertu, les prix d’encouragement
aux familles nombreuses, que sais-je encore !
— Oui. Cela est, en principe, excellent. Toutefois je n’envisage
pas sans une certaine inquiétude ce développement des attributions
de l’Académie. Son budget est considérable, elle dispose d’une
large fortune, qui va sans cesse en grandissant. Elle en fait, certes,
le meilleur usage. Pourtant je redoute que, comme celle des
congrégations, cette fortune ne finisse par susciter des convoitises
administratives, encouragées par quelques éléments extrêmes de
l’opinion publique.
— Et alors ?
— Alors, il y aura une crise de l’Académie, extérieure à elle, et
peut-être intérieure.
— Vous le regretteriez ?
— Je l’avoue. L’Académie demeure, quoi qu’on puisse dire, une
jolie plume au chapeau de la communauté française. Elle fait
quelque bien, et nul mal. Elle est connue, du moins de nom, du
dernier des paysans et des ouvriers. Elle est la preuve antique, et
toujours vivante à leur regard, qu’il est chez nous d’autres
puissances que celles de l’argent et de la politique. Cela n’est pas
rien.

— Mais enfin, demanda Pamphile, est-il exact qu’il existe, à


l’Académie, une droite et une gauche ?
— Il n’y a guère là qu’une apparence. La vérité est que, dans une
compagnie qui se recrute par cooptation, il faut bien voter pour ou
contre quelqu’un, et par conséquent former des groupes qui
s’accordent chacun, un peu d’avance, sur le choix d’un candidat.
Sinon le scrutin offrirait des résultats encore plus imprévus que ceux
dont, parfois, s’étonne le public. Ce n’est que dans ce sens que l’on
peut dire, parlant grossièrement, qu’il existe une droite et une
gauche à l’Académie.
— Alors l’Académie ne fait pas de politique ?
— Certes non ! A quoi cela lui servirait-il ? Elle ne peut exercer,
en cette matière, aucune action. Il faut se souvenir seulement que,
depuis trois quarts de siècle, elle agit, ou prétend agir, à la manière
d’un frein, comme je vous l’ai dit — ce qui tient un peu, sans doute, à
l’âge moyen de ses membres, assez élevé, et à leurs origines
sociales. C’est ainsi qu’elle tend ordinairement à l’opposition. Sous
le second Empire, elle était libérale. Sous le régime actuel, elle est
plutôt conservatrice.
« Je souhaiterais vous faire observer que, du temps du second
Empire, son attitude prenait une certaine importance politique, du fait
que les discours de ses membres étaient une des rares
manifestations d’opinion qui parvinssent aux Français. Les
délibérations mêmes du corps législatif n’étaient pas publiques. Mais
aujourd’hui que tout le monde peut dire n’importe quoi à l’occasion
de n’importe quoi et au sujet de n’importe qui, un discours
académique demeure, dans tous les sens du terme, « académique »,
et voilà tout. A peine s’émeut-on légèrement quand un immortel
qualifie le coup d’État du 2 décembre « d’opération de police un peu
rude ».
« Pour en revenir aux élections à l’Académie, et à cette fameuse
division en droite et en gauche, il est à noter que, dans les moments
mêmes où les augures déclarent gravement que la majorité
appartient à la droite, cela n’empêche jamais un candidat passant
pour être « de gauche » d’être élu ; et réciproquement. C’est que les
relations personnelles entre un candidat et ses électeurs, et aussi la
prise en considération sérieuse de ses titres, jouent au bout du
compte un plus grand rôle que cette prétendue division politique.
Seulement…
— Seulement quoi ?
— Pamphile, avez-vous remarqué qu’il est souvent beaucoup
plus aisé, surtout avec le scrutin uninominal, de prévoir le résultat
d’une élection au suffrage universel que d’une élection au suffrage
restreint — d’un député que d’un sénateur ? C’est que, plus le corps
électoral est réduit, et plus les possibilités de combinaisons, plus les
tractations, secrètes ou avouées, sont nombreuses. C’est ce qui se
passe, malgré le secours de l’Esprit Saint, pour l’élection d’un pape.
C’est ce qui arrive aussi quelquefois aux élections académiques
pour certains fauteuils.
— Et cela est décevant pour la galerie !
— Rassurez-vous. Si le candidat battu est académisable, il aura
bientôt sa revanche.
— Mais qu’est-ce qu’un candidat véritablement académisable ?
— Ah ! vous m’en demandez trop !… On est académisable pour
des titres non littéraires, un rang distingué dans l’armée, la
diplomatie, l’Église, la politique. On n’est pas académisable, même
si l’on est un écrivain, un historien, un philosophe de valeur, sans
une certaine « tenue » mondaine, ou tout au moins bourgeoise…
Verlaine n’était pas académisable, et M. Jean Aicard l’était… Encore
une fois l’Académie est un cercle : on ne doit pas donner à craindre
par ses mœurs, ses fréquentations, son caractère, que l’on
compromettra, aux yeux du vulgaire, la réputation du cercle.
— Vous venez de me dire que les fonctions d’homme politique
rendent académisable. Le public s’en étonne.
— Il en fut toujours ainsi. C’est une vieille tradition. Il peut arriver
seulement que, à de certains instants, il y ait trop d’hommes
politiques à l’Académie. Mais c’est que celle-ci, comme tous les
autres corps électoraux, est sujette à des engouements…
« Par ailleurs, il est des candidats non académisables qui sont
malgré tout candidats. Il en est dont on s’amuse. Il en est aussi de
charmants. Je veux, demain, que vous fassiez la connaissance de
mon ami Covielle : il est candidat, par principe, à tous les fauteuils
vacants.

— Il n’est jamais entré dans ma pensée, nous dit Covielle, même


au cas où je devrais vivre plus longtemps qu’Arganthonius, roi de
Gadar, lequel, au dire de Pline l’Ancien, vit briller l’aurore de sa cent
quatre-vingtième année, que je serais véritablement un jour de
l’Académie. Je me présente infatigablement : ce qui n’est pas du tout
la même chose.
« Je me présente parce que j’ai fait une découverte. C’est que les
membres de l’Académie Française sont les seuls humains, en
France, chez lesquels on puisse pénétrer, sur simple lettre
d’audience, sans avoir jamais eu l’honneur de leur avoir été
présenté ! Quand on n’a pas de relations, ou bien uniquement,
comme moi, des relations ennuyeuses, c’est un avantage
inappréciable. Une tradition bienveillante, ancienne et généreuse,
veut qu’ils ne puissent refuser d’accueillir aucun candidat. J’imagine
pourtant que ces immortels sont aussi occupés que les ordinaires
mortels ; tout le monde, de notre temps, a quelque chose à faire, les
minutes sont comptées. Cependant je crois qu’il est sans exemple
qu’un académicien ait jamais refusé le quart d’heure d’usage à
n’importe quel candidat, même au candidat que je suis : cela est
admirable et touchant.
« Il ne saurait y avoir façon plus agréable d’employer son temps.
Il doit y avoir un art de recevoir les impétrants à l’Académie qui
s’apprend peu à peu, et dont les principes se sont transmis, tendant
à la perfection, pendant quatre cents ans. Aucun de ceux que j’ai
vus ne m’a promis sa voix. Ils sont incapables d’une telle erreur de
goût, dérisoire et grossière. Ils m’ont fait savoir, au contraire, qu’ils
ne me l’accorderaient point. Mais avec quel souci des nuances,
quelle courtoisie ! Depuis que je suis né, je n’avais entendu dire si
grand bien de moi ; même il ne m’est jamais arrivé d’en penser
autant.
« Je ne serai jamais de l’Académie. Je n’ai jamais nourri cette
illusion. Mais j’en viens parfois à songer que c’est dommage : parce
que, si j’en étais, une grâce particulière descendrait peut-être sur ma
tête, qui me prêterait le talent d’inspirer un si subtil et délicat plaisir
en vous disant « non ». Les femmes elles-mêmes ne le possèdent
pas à ce point. Ajoutez à cela qu’après vous avoir parlé de vous, de
façon si flatteuse, on vous parle quelquefois des autres — des
autres candidats. On ne vous en dit jamais de mal : cela serait
contraire aux principes. Mais on ne vous en dit pas de bien ; on y
met une gentille malice. Et puis, cinq minutes encore, on vous parle
d’autre chose, et l’on vous en parle d’une manière divine. J’ai trouvé
là ce que j’ai souhaité toute ma vie, et ce qui, toute ma vie, m’avait
manqué, une conversation.
« Je crois me souvenir que vous écrivez dans les journaux. Je
vous supplie de ne point rapporter ces confidences : trop de gens
après cela voudraient être candidats, et je répugne à imposer ce
surcroît de charges à ceux dont je garde un si reconnaissant
souvenir. Ce serait, vous l’estimerez sûrement comme moi, mal
payer l’agrément si rare dont j’ai joui. Je préfère d’ailleurs, par pur
égoïsme, garder pour moi ce secret délicieux, et en user.
« Car je veux être candidat à l’Académie jusqu’à ma mort. J’y
suis fermement décidé ; cette vocation s’est révélée à mon esprit et
à mon cœur. Réfléchissez qu’il y a toujours de trente à trente-cinq
visites à faire, chaque fois — quatre cent vingt-cinq minutes de cette
causerie d’où l’on sort rasséréné, avec l’impression qu’on est
quelqu’un. Pour retomber dans la plate réalité, pour recommencer à
se juger à sa mince valeur, il faut se retrouver avec des gens qui ne
sont pas académiciens, tels que vous. Tandis que là, même les
regards, ô miracle, même les regards ne vous découragent point.
« Je vais vous avouer une chose : même si je pouvais être de
l’Académie, je ne le voudrais pas, afin d’avoir l’occasion de me
représenter. Et je compte recommencer toutes les fois que
l’occasion s’en offrira. Ce sera désormais ma carrière. »
CHAPITRE XXI

OÙ L’ON VA…

Pamphile vient de publier son premier roman. Il est à cette heure


le poulain, ou l’un des poulains, d’un éditeur actif ; il sait, à vingt-
quatre ans, soigner ses intérêts d’écrivain avec une intelligence et
un bonheur qui m’émerveillent, en me choquant un peu ; il collabore
à quelques-unes de ces revues où les jeunes gens d’aujourd’hui
s’appliquent à couvrir des apparences d’une intellectualité grave un
lyrisme sous-jacent, peut-être plus amoral et individualiste encore
que celui des générations précédentes — toutefois aristocratique et
anti-démocratique. Enfin il s’efforce d’être de son temps. C’est bien
naturel, je ne songe pas un instant à le lui reprocher.
J’ai lu son ouvrage avec curiosité, et aussi avec intérêt. Un
intérêt véritable, je vous assure. D’abord ce n’est pas ça du tout que
j’aurais écrit, je n’y aurais jamais pensé. C’est bien quelque chose.
S’il faisait ce que j’ai fait, à quoi servirait-il qu’il eût pris la plume ?
Son roman n’est nullement à mettre de côté, encore qu’il ne soit pas
entièrement satisfaisant. Il est imparfaitement composé, il montre, à
côté de trouvailles, d’expressions neuves et ingénieuses, des
faiblesses singulières, une méconnaissance parfois inquiétante du
génie de la langue. Il unit, dans un mauvais mariage, ainsi que l’a
déjà marqué M. Robert Lejeune au sujet de quelques-uns de ses
contemporains émules, « au style à images vives et incohérentes,
très mauvais pour les yeux fatigués, le style en sauts de carpe, où
des tronçons de phrases se tordent, se retournent, échantillons de
toutes les inversions, ellipses, anacoluthes, possibles en français ».
Ce qui me paraît plus inquiétant encore, c’est qu’il emploie les
mots à contresens, ou tout au moins de façon fort plate, parce qu’il
ignore leur origine et leur histoire, qu’il ne connaît point l’art de leur
rendre leur fraîcheur et leur jeunesse en les allant retremper à ces
sources. Nous sommes en vérité à une époque où, en toute
occurrence, la monnaie de papier, dont la valeur change à chaque
instant, a remplacé l’étalon d’or.
Tout cela me gêne. Tout cela me donne le sentiment d’une chose
qui n’est pas faite pour durer, d’une œuvre qui n’a pas le souci d’être
un chef-d’œuvre, mais seulement un objet de consommation
immédiate — le sentiment, enfin, de « la mode » remplaçant « l’art ».
C’est fait pour cette année-ci, non pour l’éternité. Ça n’est pas en
bronze ni en marbre, mais en soie légère.
Et pourtant c’est plein de qualités ! D’abord cela constitue, sur
notre époque, un précieux document. C’est vu avec des yeux de
sauvage qui parle comme il voit. Cela révèle des tas de choses que
je n’aurais su ni discerner ni décrire avec mes vieux outils, ces outils
d’un si bon métal, et dont la trempe a résisté aux siècles. C’est
assez creux dans l’invention générale, et d’une construction lâche,
mais si riche dans l’observation du détail, de « l’accident ». Et c’est
l’accident qui fait la réalité. Et puis, c’est amusant ! Il n’y a pas à dire,
c’est amusant ! Peut-être seulement comme la dernière création d’un
grand couturier, non pas d’un grand sculpteur ni d’un grand peintre.
Mais c’est toujours ça. Et j’y sens davantage la manifestation directe
d’un tempérament, malgré l’insuffisance de la technique, peut-être
même à cause de cette insuffisance comme chez beaucoup de
peintres de nos jours.
Enfin, chose curieuse, les ouvrages mêmes de ceux qui
s’affirment, avec le plus d’assurance, anti-romantiques, semblent
bien souvent beaucoup plus anti-classiques qu’anti-romantiques. Je
veux dire qu’on n’y rencontre guère le souci de la mesure et de la
composition. Marcel Proust lui-même est un écrivain rare et
remarquable. Mais si, comme on le voulait aux époques classiques
— et du reste comme le voulaient encore les grands romantiques, —
l’art consiste dans le choix, où est l’art, dans cette prose qui veut tout
dire, et ne choisit rien ? Pourtant elle en a. Mais ce n’est pas celui-ci.
Autre caractère à signaler. Cette littérature de jeunes,
singulièrement intelligente, manque singulièrement de jeunesse et
d’ingénuité. Souvent d’humanité. Ce sont des qualités qu’on
rencontre toutefois dans le Nono de Gaston Roupnel, dans la Nêne
de Pérochon. Mais c’est justement peut-être parce que ces œuvres
en manifestent qu’elles paraissent discutables, qu’elles n’ont pas,
dans notre France contemporaine, la place qu’on leur accorderait
ailleurs, en Angleterre par exemple. Le courant ne se dirige pas de
ce côté.
C’est par cette recherche, excessive parfois, et comme
« cocaïnique » de l’intelligence, et par ce défaut d’ingénuité, que les
tendances de notre littérature contemporaine diffèrent en effet de
celles de la littérature contemporaine anglo-saxonne ; et c’est,
j’imagine, pour cette cause qu’elle a tant de peine, malgré tous ses
efforts, à paraître une littérature « d’action ». Elle a parfois une
propension malheureuse à confondre le roman d’action et le roman
d’aventures.
Il serait assez facile de démontrer que c’est juste le contraire.
Mais, d’un point de vue tout extérieur, qui n’est point cependant
sans signification, ces deux littératures, l’anglaise et la française,
offrent de nos jours une apparence commune : l’abondance de la
production.
Cela vient d’abord de ce que, dans les deux pays, la
« demande » est très supérieure à ce qu’elle était il y a un demi-
siècle. Beaucoup plus de personnes ont appris à lire, et lisent en
effet. En même temps les classes qui ont, assez récemment, appris
à lire, bénéficient de plus gros salaires et de plus de loisirs. Dans les
deux pays ce progrès de l’instruction générale, et ces loisirs, sont le
fruit du développement des institutions démocratiques. Il ne semble
pas, en France du moins, que tous les écrivains en témoignent à
celles-ci une égale gratitude.
Mais il n’y a pas que cet accroissement du nombre des lecteurs.
Il y a aussi augmentation du nombre des auteurs.
Dans les pays anglo-saxons ceux-ci, depuis longtemps, ne se
recrutaient pas uniquement dans la peu nombreuse aristocratie qui a
passé par les établissements secondaires de Harrow, d’Eton, de
Rugby ou de Windsor, par les grandes universités de Cambridge et
d’Oxford ; ou aux États-Unis, dans les écoles analogues. Ils venaient
d’un peu partout : témoin Kipling, Wells, Conrad, Jack London, Mark
Twain et tant d’autres.
Notre belle langue écrite, depuis quatre siècles, est une plante de
culture intensive, qui n’a pu croître que sur le terrain des études
classiques, et, par suite, jusqu’à l’époque actuelle, à la faveur d’un
enseignement secondaire fondé sur la connaissance plus ou moins
approfondie — plutôt moins que plus — des langues anciennes. Cet
enseignement n’était donné qu’aux enfants de la bourgeoisie. C’est
lui qui formait presque tous nos écrivains. On compterait sur les
doigts d’une seule main ceux qui, au XIXe siècle, et même au XXe
siècle, ne sont point sortis d’un lycée, d’un collège — ou d’un
séminaire. Tout cela, je l’ai déjà signalé au début de ce petit livre.
Cependant supputez la population de ces établissements
d’enseignement secondaire en 1850 et de nos jours : en trois quarts
de siècle, elle a triplé. Cela tient à deux causes : il y a plus de
familles en état de faire donner cet enseignement à leurs enfants ; et
il y a, en raison des sollicitudes du régime, plus de bourses
accordées à des enfants pauvres. La concurrence des
établissements religieux élargit encore le chiffre de cette population.
Il est clair, que, si l’on apprend à écrire à un plus grand nombre
de jeunes gens, il y en aura aussi un plus grand nombre qui écriront.
Il existe donc en somme, de nos jours, plus d’hommes de lettres,
pour la même raison qu’il y a plus d’avocats, de médecins et
d’ingénieurs.
Il faut ajouter à cela que l’enseignement primaire, par ses écoles
normales, a créé une culture primaire supérieure, qui a produit elle-
même quelques écrivains, et de mérite : tel ce Pergaud, dont la
guerre nous a privés.
C’est donc une floraison extrêmement drue à laquelle nous
assistons. Elle donne des fleurs de toutes sortes, qui n’ont pas
toutes le même parfum, ni le même éclat, ni la même rareté. On en
discerne toutefois appartenant à des espèces neuves, encore non
classées, et dont un botaniste dirait, à tout le moins, qu’on en
pourrait tirer quelque chose en la cultivant, car l’impression générale
est celle-ci :
Beaucoup d’œuvres, plus qu’auparavant, montrent une
personnalité forte, des mérites d’ordres divers, annonçant, en
quelque mesure, un renouveau. Fort peu — peut-être moins
qu’auparavant — qui soient entièrement satisfaisantes, offrent un
caractère définitif… On dirait de la littérature d’une démocratie qui
s’aristocratise.
TABLE DES MATIÈRES

CHAPITRE I.
CONSULTATION 5
CHAPITRE II.
LES DÉBUTS DE PAMPHILE 11
CHAPITRE III.
L’AMATEUR 17
CHAPITRE IV.
LA PROFESSION « SECONDE » 22
CHAPITRE V.
PREMIERS ESSAIS, PREMIERS ÉCHECS 28
CHAPITRE VI.
EXPÉRIENCES PERSONNELLES 34
CHAPITRE VII.
LE CONTE 39
CHAPITRE VIII.
DU JOURNALISME 44
CHAPITRE IX.
TYPES DE JOURNALISTES 50
CHAPITRE X.
POLÉMIQUES LITTÉRAIRES CONTEMPORAINES 55
CHAPITRE XI.
UNE OPINION POLITIQUE POUR L’ÉCRIVAIN 59
CHAPITRE XII.
ESPOIRS ET REGRETS 64
CHAPITRE XIII.
VACHES GRASSES ET VACHES MAIGRES 69
CHAPITRE XIV.
PUBLICITÉ LITTÉRAIRE 75
CHAPITRE XV.
LA CRITIQUE 80
CHAPITRE XVI.
PRIX LITTÉRAIRES 86
CHAPITRE XVII.
L’ÉCRIVAIN ET L’ARGENT 91
CHAPITRE XVIII.
LE MARIAGE DE L’ÉCRIVAIN. L’ÉCRIVAINE 97
CHAPITRE XIX.
SALONS LITTÉRAIRES 101
CHAPITRE XX.
L’ÉCRIVAIN ET L’ACADÉMIE 107
CHAPITRE XXI.
OÙ L’ON VA… 118
IMPRIMERIE CRÉTÉ
CORBEIL (S.-ET-O.)
5527-25
*** END OF THE PROJECT GUTENBERG EBOOK L'ÉCRIVAIN ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying copyright
royalties. Special rules, set forth in the General Terms of Use part of
this license, apply to copying and distributing Project Gutenberg™
electronic works to protect the PROJECT GUTENBERG™ concept
and trademark. Project Gutenberg is a registered trademark, and
may not be used if you charge for an eBook, except by following the
terms of the trademark license, including paying royalties for use of
the Project Gutenberg trademark. If you do not charge anything for
copies of this eBook, complying with the trademark license is very
easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund from
the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law in
the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name
associated with the work. You can easily comply with the terms of
this agreement by keeping this work in the same format with its
attached full Project Gutenberg™ License when you share it without
charge with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the terms
of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears, or
with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:

You might also like