<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Smriti Bajaj on Medium]]></title>
        <description><![CDATA[Stories by Smriti Bajaj on Medium]]></description>
        <link>https://medium.com/@smritibajaj22?source=rss-6ca40cf7da19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rIwnx7SBdvOw5qoddLSO3g.jpeg</url>
            <title>Stories by Smriti Bajaj on Medium</title>
            <link>https://medium.com/@smritibajaj22?source=rss-6ca40cf7da19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 10:14:28 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@smritibajaj22/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Blockchain development using Python and Ganache]]></title>
            <link>https://smritibajaj22.medium.com/blockchain-development-using-python-and-ganache-part-1-98ebd0865c1?source=rss-6ca40cf7da19------2</link>
            <guid isPermaLink="false">https://medium.com/p/98ebd0865c1</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[ganache]]></category>
            <category><![CDATA[cryptocurrency]]></category>
            <category><![CDATA[ethereum]]></category>
            <dc:creator><![CDATA[Smriti Bajaj]]></dc:creator>
            <pubDate>Thu, 01 Jul 2021 13:55:54 GMT</pubDate>
            <atom:updated>2023-02-19T22:32:51.000Z</atom:updated>
            <content:encoded><![CDATA[<p><em>Disclaimer- This part focuses more on the theoretical aspects and etherscan.io.</em></p><p>I know I’m a sweet-toothed, fan of ganache but this “<a href="https://www.trufflesuite.com/ganache">Ganache</a>” tastes a little code-like. It’s easy to get and use but we’ll see it in the next part because first, Blockchain. Blockchain is among the hippest technology gossips out there in terms of numbers, buzzing cryptocurrency, accounts, blocks, gas, gas price and other jargon. So, let’s witness the inevitable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*M9YAyiYjFDP1VceX.jpg" /></figure><p>Blockchain is a chain of blocks containing transactions. It is a decentralized database that keeps a permanent record of all transactions. Once a record is written to a blockchain, it can’t be altered. The core concepts of blockchain include:</p><ol><li><strong>Block</strong>: A block itself has three primary components. The block is made up of the information for the current transaction, a cryptographic hash of the previous block, and a timestamp. Each block uses an RPC protocol to communicate.</li><li><strong>Network: </strong>Using a peer-to-peer network helps make blockchain fault-tolerant, transparent and distributed.</li><li><strong>Consensus mechanism: </strong>It lets all the members know that an update is valid and that the update was made by a member of the blockchain. It also sets the standard for how members prove to the rest of the chain that an update is valid. A consensus mechanism makes blockchain, distributed and immutable.</li><li><strong>Smart contract: </strong>A smart contract is a contract that executes without any additional action required by a third party. With a smart contract, you establish the terms and conditions of the contract. Once the terms and conditions of the contract are met on the blockchain, the contract automatically executes — without you needing to take any action.</li></ol><p>Wait, can a contract constitute multiple transactions? Absolutely. A “smart contract” is simply a program — a collection of code (its functions) and data (its state) that resides at a specific address on the blockchain. And what currency do we trade in? It’s cryptocurrency— your digital asset. Well, the reason blockchain is so important is that it prevents cryptocurrency to get duplicated.</p><blockquote>Pro tip: Blockchain and bitcoin aren’t synonymous.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_PTPBc1DkyvuH3PD" /><figcaption>Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=medium&amp;utm_medium=referral">Thought Catalog</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>A blockchain framework is the set of standards on which a blockchain operates. Some frameworks are built specifically for cryptocurrency creation and tracking. Other frameworks are focused on collaboration and sharing of knowledge. One of the commonly used frameworks is Ethereum.</p><p>Ethereum is a permission-less, or public, cryptocurrency blockchain that provides a broad set of capabilities for using smart contracts, running applications, and executing code. Ethereum also has its programming language (Solidity) that allows you to create applications within the Ethereum Virtual Machine (EVM). Within the EVM, you can write, build, and run applications. You can even establish fees or charges, in Ether (Ethereum’s cryptocurrency) for running an application. (Miners do charge that 😉)</p><p>For our code here, we’ll connect to the Ethereum API to access an Ethereum network via <a href="https://web3py.readthedocs.io/en/stable/contracts.html">web3</a>, an Ethereum library in Python. To interact with the Ethereum blockchain, we’ll use <a href="https://infura.io/">infura</a>. We’ll have to sign up and check our dashboard for an API key to access the endpoint “https://mainnet.infura.io/v3/&lt;your-key&gt;”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee05980c25ac2386b92c6f0d580200af/href">https://medium.com/media/ee05980c25ac2386b92c6f0d580200af/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ccea482e2cd8de02200617a5cc8d02e/href">https://medium.com/media/9ccea482e2cd8de02200617a5cc8d02e/href</a></iframe><p>This will return with a True value if the connection is established.</p><p>Now, to get the basic idea of a block of the blockchain, use the following code.</p><pre>print(web3.eth.get_block(‘latest’))</pre><p>This will give you lots of information and we’ll talk about it in the next part. Let’s now go to e<a href="https://etherscan.io/">therscan</a>. Etherscan is the leading blockchain platform for Ethereum that provides APIs, analytics and more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pQdty8re5_KSZjT4CUuVvg.png" /></figure><p>After navigating to the website, choose any token and you can spot a contract address, copy it. There, you can see all the transactions, holders, and many other fruitful pieces of information like specific to contract- total supply, name, symbol, etc. One can use this information to publish on their website or for analysis through the code ahead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*QBlXkxY6_1PcHcuHrdbVlA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1JhAzsg8DzKSxaZ3-SbH6g.png" /></figure><p>Now with that copied contract address and an Application Binary Interface(ABI) which is the description of the contract, we have our contract information with us.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6d6b970482e5fcbb8216a8c9960fefc/href">https://medium.com/media/f6d6b970482e5fcbb8216a8c9960fefc/href</a></iframe><p>However, to get the ABI there are two ways, one using the API and the other through my favorite etherscan.io UI. In the above snippet, the commented ABI was extracted in the latter way wherein you’ll have to <strong><em>click on the contract address</em></strong>, click on the <strong><em>Contract tab</em></strong> and in the code below, you’ll see the <strong><em>Contract ABI</em></strong>.</p><p>For the <strong><em>ABI-API</em></strong> way, one can refer to the following code.</p><p>It simply uses the <em>requests</em> package and gets the required ABI based on the address passed. Finally, ABI is loaded as a JSON to the contract method along with the address.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cba57750b515f50724594756662cd3b6/href">https://medium.com/media/cba57750b515f50724594756662cd3b6/href</a></iframe><p>I know your great eye has noticed a call() in the previous code, yes, that’s how we interact with the functions of the contract when reading from them. In the next part, we’ll see how to create our own contract in solidity and even use parameters to play with like, transact(), an alternative of call().</p><p>Moreover, there is an alien term fromWei that returns the value in wei converted to the given currency. <strong>Wei</strong> refers to the smallest denomination of ether (ETH). The value is returned as a decimal to ensure precision down to the wei.</p><p><em>For details check out-</em><a href="https://web3py.readthedocs.io/en/stable/web3.eth.html"><em>https://web3py.readthedocs.io/en/stable/web3.eth.html</em></a></p><p>Woohoo! You now know how to access the blocks of a blockchain, how to analyze complex numbers via Etherscan. I just feel it in my bones that you want to create a contract, a transaction, and then call more methods. Well, then stay tuned for the next part!</p><p>Note- Since it’s been a long gap and I don’t have anything saved in my drafts, part 2 is not coming. Sorry guys, I couldn’t keep me in touch with Blockchain.</p><p>If you liked the content, please clap. It’s a really good exercise :)</p><p>Thanks for reading! ❤ #CodeEveryday</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=98ebd0865c1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JWT authentication with Node.js : Solving a trust issue between Client and server sides.]]></title>
            <link>https://smritibajaj22.medium.com/jwt-authentication-with-node-js-solving-a-trust-issue-between-client-and-server-sides-6e4197bacb90?source=rss-6ca40cf7da19------2</link>
            <guid isPermaLink="false">https://medium.com/p/6e4197bacb90</guid>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[cookies]]></category>
            <dc:creator><![CDATA[Smriti Bajaj]]></dc:creator>
            <pubDate>Wed, 02 Jun 2021 23:19:06 GMT</pubDate>
            <atom:updated>2021-06-02T23:19:53.922Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>JWT authentication with Node.js: Solving a trust issue between client and server sides.</strong></h3><p>We all have had our trust issues, haven’t we? Well here, I’m trying to get your server relieved of one such case. JSON Web Token(JWT) is a token to allow entry from the client-side to the server-side through authentication. The client’s login session is preserved by storing the token in a <strong>cookie and locally</strong> (both ways) and passing it to the server. Because the client is authenticated, your server can now trust the client.</p><h4>Prerequisites-</h4><ol><li>You should know how to create Restful APIs in Node.js and how to use <a href="https://expressjs.com/">Express</a>.</li><li>Before that, <a href="https://nodejs.org/en/download/">Node.js</a> must be installed in your system.</li></ol><h4>The course of action-</h4><p><strong>Local Storage</strong></p><p>Local storage simply refers to Browser’s memory.</p><ul><li>We will start in the backend first. So, keep your MongoDB (or whichever DB you are using) ready if you want to intertwine JWT in your application. We’ll utilize the “jsonwebtoken” package which can be installed using the “npm i jsonwebtoken” command. In your <strong>js</strong> file, write the following code to import the package.</li></ul><pre>const jwt = require(“jsonwebtoken”);</pre><ul><li>Next, we’ll verify the password and the username with what is in the database(in the real scenario). If they are correct, we’ll generate a token using a secret key. This step is to be done in an API, like, login.</li></ul><p><em>‘password-hash’ is another library that you can use as-</em></p><pre>var passwordHash = require(‘password-hash’);</pre><p><em>A sample DB call would look like-</em></p><pre>result = await User.findOne({ email: req.body.email }).exec();</pre><p><em>and the API would be-</em></p><pre>router.post(‘/login’, async function (req, res) {<br>if (passwordHash.verify(req.body.password, result.password)) {</pre><pre>// generate a signed token with user id and secret key<br>const token = jwt.sign({ _id: result._id }, <br>                       CONFIG.jwtSecret, <br>                       { expiresIn: &#39;1800s&#39; }); //token expiry<br>}</pre><pre>res.status(200).send({token})<br>}</pre><p><em>Config would require the config.js which will have the following code snippet. Alternatively, if you want to generate the secret key, you can use a built-in “crypto” library.</em></p><blockquote>To use process.env, you require, require(‘dotenv’).config(); in your config.js. <strong>dotenv</strong> allows you to separate secrets from your source code. It’s a good practice in collaborative environments.</blockquote><pre>CONFIG.jwtSecret = process.env.jwtSecret</pre><ul><li>Authenticating a token is the crucial step of this entire process. We can do it by two means- 1. Using a middleware 2. Without a middleware :P</li></ul><ol><li><em>Using a middleware, authenticateToken</em></li></ol><pre>function authenticateToken(req, res, next) {<br>  const authHeader = req.headers[&#39;authorization&#39;]<br>  const token = authHeader.replace(/^Bearer\s+/, &quot;&quot;);</pre><pre>  if (token == null) return res.sendStatus(401)<br><br>  jwt.verify(token, process.env.TOKEN_SECRET as string, (err: any, user: any) =&gt; {<br>    console.log(err)</pre><pre>    if (err) return res.sendStatus(403)<br><br>    req.user = user<br>    next()<br>  })<br>}</pre><pre>router.get(&#39;/api/userOrders&#39;, authenticateToken, (req, res) =&gt; {<br>  // executes after authenticateToken<br>  // ...<br>})</pre><p>2. <em>without using a middleware</em></p><pre>router.get(&#39;/api/userOrders&#39;, async function (req, res){<br>  const authHeader = req.headers[&#39;authorization&#39;]<br>  const token = authHeader.replace(/^Bearer\s+/, &quot;&quot;);</pre><pre>  if (token == null) return res.sendStatus(401)<br>  <br>  jwt.verify(token, CONFIG.jwtSecret, function (err, decoded) {<br>      if (err) return res.sendStatus(403);<br>      <br>      // else utilize the decoded _id<br>  }<br>})</pre><p>This code will authenticate the token provided by the client. If it is valid, it can proceed with the request otherwise it can be handled as an error. For both ways, a sample request would look like this-</p><pre>GET https://example.com:4000/api/userOrders<br>Authorization: Bearer JWT_ACCESS_TOKEN</pre><ul><li>To get the token on the client-side, you will simply use, res.json() and to send back set in your request headers.</li><li>Now stop. Think for a while, what will happen to your token if you refresh the page or close and re-open the page? Your token will be lost. And what about security? If a hacker, send &lt;script&gt;Boom! You are hacked!&lt;/script&gt; It will hamper your application pertaining to the XSS attack.</li></ul><p>So, we have cookies to the rescue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_BDrdycslWX5_TkD" /><figcaption>Photo by <a href="https://unsplash.com/@lindseysavagecreative?utm_source=medium&amp;utm_medium=referral">Lindsey Savage</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Cookies</p><p>Well, not really. Using cookies isn’t the best solution because they too have a risk of XSS and CSRF attack where <a href="https://hasura.io/blog/best-practices-of-using-jwt-with-graphql/">refresh and revocation</a> come into the picture. For a simple request ← →response type application, we can grab some cookies.</p><p>We’ll refactor our above code.</p><ul><li>Install “cookie-parser”, you know why.</li></ul><pre>npm i cookie-parser</pre><ul><li>Next, we’ll modify the route send a JWT token in a cookie.</li></ul><pre>router.post(‘/login’, async function (req, res) {<br>if (passwordHash.verify(req.body.password, result.password)) {</pre><pre>// generate a signed token with user id and secret key<br>const token = jwt.sign({ _id: result._id }, <br>                       CONFIG.jwtSecret, <br>                       { expiresIn: &#39;1800s&#39; }); //token expiry<br>}</pre><pre>//res.status(200).send({token})</pre><pre>res.cookie(&quot;token&quot;, token, { httpOnly: true, secure: true } ).status(200).send({token});</pre><pre>}</pre><p>If the HttpOnly flag (optional) is included in the HTTP response header, the cookie cannot be accessed through the client-side script (if the browser supports this flag). This mitigates the XSS attack risk. The Secure flag (optional), however, is for HTTPS support only.</p><blockquote>Now the token is available only on the same port as your APIs.</blockquote><ul><li>Finally, how to get the cookies from the client-side? Now, this is a piece of cake. Simply, fetch the API response. Furthermore, if you call the other APIs, /api/userOrders , the token will be in the req.cookies.token which can be used for verification with or without the middleware.</li></ul><p>To protect your application from CSRF attack, you can use npm i csurf and you can set the middleware as-</p><pre>const csrfProtection = csrf({<br>  cookie: true<br>});app.use(csrfProtection);app.get(&#39;/csrf-token&#39;, (req, res) =&gt; {<br>  res.json({ csrfToken: req.csrfToken() });<br>});</pre><h4>Conclusion</h4><p>One must know that using JWT isn’t a one-size-fits-all solution. JWT takes more space, individual stateless JWT tokens cannot be invalidated making it a <em>single-use authorization token</em>. So, one might need both sessions and JWT for a complete and robust architecture.</p><p>If you liked the content, please clap. It’s a really good exercise :)</p><p>Thanks for reading! ❤ #CodeEveryday</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6e4197bacb90" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Tesserocr or Tesseract?]]></title>
            <link>https://smritibajaj22.medium.com/tesserocr-or-tesseract-f886b74b3432?source=rss-6ca40cf7da19------2</link>
            <guid isPermaLink="false">https://medium.com/p/f886b74b3432</guid>
            <dc:creator><![CDATA[Smriti Bajaj]]></dc:creator>
            <pubDate>Sun, 07 Feb 2021 12:48:29 GMT</pubDate>
            <atom:updated>2026-01-20T04:25:29.003Z</atom:updated>
            <content:encoded><![CDATA[<p>Did I mistype it? Isn’t it tesseract-ocr? Well, nope.</p><p>Tesserocr is known in the world of Python for its advanced support with Tesseract’s C++ API. It is primarily a wrapper around the API. Then, what’s tesseract-ocr or pytesseract? pytesseract is another module/library that interfaces with tesseract-ocr CLI by being a wrapper. In this story, we’ll learn how to install them and a working example of each.</p><blockquote>tesserocr</blockquote><p>To install tesserocr in a <strong>Windows</strong> system, I’d advise using anaconda or miniconda navigators.</p><ol><li>Create a conda env with python 3.6 - <strong>conda create -n myenv python=3.6</strong></li><li>Activate myenv- <strong>conda activate myenv</strong></li><li>In the environment, fire this command- <strong>conda install -c conda-forge tesserocr==2.5.1</strong></li><li>Execute the following code-</li></ol><pre>from tesserocr import PyTessBaseAPI, RIL<br>with PyTessBaseAPI(lang = ‘eng’, path=’\\Library\\bin\\tessdata’) as api:<br>    for img in [‘sample1.jpg’,’sample2.jpg’]:<br>        api.SetImageFile(img)<br>        print(api.GetUTF8Text())<br>        boxes = api.GetComponentImages(RIL.TEXTLINE, False)<br>        print(len(boxes))</pre><p>**<strong>lang </strong>can be changed to a combination of multiple languages like ‘eng+san’, <strong>path </strong>to be set to a tessdata folder containing eng.traineddata etc.</p><p>While in <strong>Ubuntu</strong>, you can straight away fire the command in your terminal- <strong>sudo apt-get install tesseract-ocr libtesseract-dev libleptonica-dev pkg-config</strong></p><figure><img alt="Hurraaayy!!! We are all set to OCR our images!" src="https://cdn-images-1.medium.com/max/1024/0*co-MuxDCxAA3LBhw" /><figcaption>Photo by <a href="https://unsplash.com/@dre0316?utm_source=medium&amp;utm_medium=referral">Andre Hunter</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Hurraaayy!!! We are all set to OCR our images!</p><blockquote>pytesseract</blockquote><p>Suppose, you don’t want to use the APIs but simple functions, we have pytesseract to the rescue. To install, we have straightforward commands-</p><p>For <strong>Ubuntu</strong>, there’s a prerequisite to install tesseract-ocr -</p><pre><strong>sudo apt install tesseract-ocr</strong><br>sudo apt install libtesseract-dev<br><strong>pip install pytesseract</strong></pre><p>In a <strong>Windows </strong>system,</p><ol><li>you’ll have to download tesseract via <a href="https://sourceforge.net/projects/tesseract-ocr/">https://sourceforge.net/projects/tesseract-ocr/</a></li><li>Set tessdata path in a TESSDATA_PREFIX environment variable or mention in the code as done above for tesserocr</li><li>In your tessdata folder, you are required to have the language needed for OCR. In case of English, eng.traineddata must be present in the tessdata folder- <a href="https://github.com/tesseract-ocr/tessdata">https://github.com/tesseract-ocr/tessdata</a></li><li>Now, fire <strong>pip install pytesseract </strong>in your command shell.</li></ol><p>If using Anaconda/miniconda, use <strong>conda install -c conda-forge pytesseract</strong></p><p>For code usage, refer to <a href="https://github.com/BajajSmriti/Opencv-OCR/blob/master/SanskritTextDetection_OCR.ipynb">https://github.com/BajajSmriti/Opencv-OCR/blob/master/SanskritTextDetection_OCR.ipynb</a></p><p>If you face any errors, you can refer to — <a href="https://tesseract-ocr.github.io/tessdoc/Compiling.html">https://tesseract-ocr.github.io/tessdoc/Compiling.html</a> and I’m open to discussing.</p><p>For <strong>.NET </strong>developers facing similar wrapper decisions,<a href="https://ironsoftware.com/csharp/ocr/"> IronOCR</a> sidesteps this complexity entirely. No conda environments, no TESSDATA_PREFIX configuration, no separate traineddata downloads. The library bundles everything into a single NuGet package.</p><pre>using IronOcr;<br><br>var ocr = new IronTesseract();<br>ocr.Language = OcrLanguage.English; // or OcrLanguage.EnglishSanskrit for multi-language<br><br>foreach (var img in new[] { &quot;sample1.jpg&quot;, &quot;sample2.jpg&quot; })<br>{<br>    using var input = new OcrInput();<br>    input.LoadImage(img);<br>    var result = ocr.Read(input);<br>    Console.WriteLine(result.Text);<br>    Console.WriteLine(result.Lines.Length);<br>}</pre><p>Like tesserocr, IronOCR provides access to component-level data including text lines with bounding boxes. The difference is you skip the installation headaches on Windows and the environment variable setup. Multi-language support works the same way, just combining languages without hunting down traineddata files.</p><p>To further improve the OCR accuracy, preprocessing steps like cleaning and normalizing the image before text recognition can be adopted.</p><pre>...<br>    input.LoadImage(img);<br><br>    // Pre-processing (must be BEFORE Read)<br>    input.DeNoise();<br>    input.Deskew();<br>    input.EnhanceResolution();<br><br>    var result = ocr.Read(input);<br>...</pre><p>Here, DeNoise() removes background noise and artifacts, Deskew() corrects any image rotation or tilt, and EnhanceResolution() increases effective image clarity for better character detection. All preprocessing is applied after loading the image and before executing the OCR read operation.</p><p>If you liked the content, please clap. It’s a really good exercise :)</p><p>Thanks for reading! ❤ #CodeEveryday</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f886b74b3432" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to configure live agent functionality using Zendesk?]]></title>
            <link>https://smritibajaj22.medium.com/how-to-configure-live-agent-functionality-using-zendesk-568761d09010?source=rss-6ca40cf7da19------2</link>
            <guid isPermaLink="false">https://medium.com/p/568761d09010</guid>
            <category><![CDATA[zendesk]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[live-agent]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[chatbots]]></category>
            <dc:creator><![CDATA[Smriti Bajaj]]></dc:creator>
            <pubDate>Sat, 07 Nov 2020 22:47:20 GMT</pubDate>
            <atom:updated>2020-11-08T21:59:33.354Z</atom:updated>
            <content:encoded><![CDATA[<p>If you haven’t read my previous article on <a href="https://smritibajaj22.medium.com/how-to-create-a-chatbot-with-zendesk-chat-conversations-api-ea6d2640ae59">Zendesk chatbot</a>, please do for a better understanding of this one.</p><p>To enable live agents, it’s advised to create a <strong>department</strong> such that for payment related stuff, we can have a payments department, likewise for customer support, orders etc. <a href="https://smritibajaj22.medium.com/how-to-create-a-chatbot-with-zendesk-chat-conversations-api-ea6d2640ae59"><strong>How to create a department?</strong></a></p><p>Once department(s) is(are) created, we can move ahead with the technicalities. So, whenever a visitor says, “Connect me to a live agent” or if the chatbot is unable to map the intents(NLP) for visitor queries, then we can transfer the visitor to a live agent belonging to a particular department.</p><p>The transfer depends on -</p><ul><li>Get department query which tells us the status(Online, Away, Offline) of the agents present in the department. Suppose, if any agent is online, the department becomes online, we fetch it’s Id and then we can initiate a transfer through the <a href="https://develop.zendesk.com/hc/en-us/articles/360001331787-Getting-started-with-the-Chat-Conversations-API">transfer mutation</a>.</li></ul><pre>const transferToDepartmentQuery = {<br>payload: {<br>query: `mutation {<br>transferToDepartment(<br>channel_id: &quot;${channelToBeTransferred}&quot;,<br>department_id: &quot;${onlineDepartment.id}&quot;) {<br>success<br>}<br>}`<br>},<br>type: &quot;request&quot;,<br>id: REQUEST_ID.TRANSFER_TO_DEPARTMENT<br>};<br>webSocket.send(JSON.stringify(transferToDepartmentQuery));</pre><ul><li>Channel Id of the communication channel between the visitor and the agent available in the transferred department.</li></ul><p>Depending on the requirement, we can either allow a bot-to-agent handoff by making the bot leave the conversation or stop the bot from backend to halt answering when an agent has joined the chat. In this article, we’ll discuss the former approach.</p><p>To allow the bot to leave the conversation, we should first use the <a href="https://zendesk.github.io/conversations-api/leavechannelpayload.doc.html">leaveChannel</a> mutation. This mutation requires the channel Id of the channel where a visitor is communicating with an API client/agent who is thrown out of the conversation.</p><pre>const leaveChannel = {<br>                  payload: {<br>                    query: `mutation {<br>                                    leaveChannel(<br>                                        channel_id: &quot;${channelToBeTransferred}&quot;<br>                                    ) {<br>                                        success<br>                                      }<br>                                  }`<br>                  },<br>                  type: &quot;request&quot;,<br>                  id: REQUEST_ID.LEAVE_CHANNEL<br>                };</pre><pre>webSocket.send(JSON.stringify(leaveChannel));</pre><p>Next, we should start listening to the activity after the transfer with the help of <a href="https://zendesk.github.io/conversations-api/listenvisitorchannelpayload.doc.html">listenVisitorChannel</a>. The activities include, member join log and member leave log. With this approach, once a live agent leaves, we can allow the bot to continue the conversation with the visitor.</p><pre>const listenVisitorChannel = {<br>                  payload: {<br>                    query: `mutation {<br>                      listenVisitorChannel(<br>                                          channel_id: &quot;${channelToBeTransferred}&quot;<br>                                      ) {<br>                                          success<br>                                        }<br>                                    }`<br>                  },<br>                  type: &quot;request&quot;,<br>                  id: REQUEST_ID.LISTEN_VISITOR_CHANNEL<br>                };</pre><pre>webSocket.send(JSON.stringify(listenVisitorChannel));</pre><p>Now we can see that when Bank Bot leaves the chat, a live agent, Sarah, joins in while Bank Bot doesn’t interrupt.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/332/1*Cbwrb9yGz6yTS6eSJ4sE5w.png" /><figcaption>Source: <a href="https://web-assets.zendesk.com/images/p-chatbot/chatbot-real-2X.png">https://web-assets.zendesk.com/images/p-chatbot/chatbot-real-2X.png</a></figcaption></figure><p>However, the visitors might have to wait for a long time to chat with a live agent. As a real time status of their waiting queue, Zendesk displays a queue position reflecting the visitor’s position with respect to other visitors waiting to chat with a live agent in the requested department.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/315/0*oEU0RqZZaFPsuigL.png" /><figcaption>Source: <a href="https://zen-marketing-documentation.s3.amazonaws.com/docs/en/chat_standalone_offline_form.png">https://zen-marketing-documentation.s3.amazonaws.com/docs/en/chat_standalone_offline_form.png</a></figcaption></figure><p>I hope I have explained the important bits of the implementation. For any relevant queries, you can comment below.</p><p><strong>Tips-</strong></p><ul><li>You can record channel activity by subscribing to the <strong>channel activity subscription</strong>. — <a href="https://zendesk.github.io/conversations-api/">https://zendesk.github.io/conversations-api/</a></li><li>Initiate a transfer only to a particular department.</li><li>Messages from visitors are broadcasted to all the available(online) agents in the department.</li></ul><p><strong>References-</strong></p><p><a href="https://develop.zendesk.com/hc/en-us/articles/360001331787-Getting-started-with-the-Chat-Conversations-AP">https://develop.zendesk.com/hc/en-us/articles/360001331787-Getting-started-with-the-Chat-Conversations-AP</a>I</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodesandbox.io%2Fembed%2F51rorvmwx&amp;display_name=CodeSandbox&amp;url=https%3A%2F%2Fcodesandbox.io%2Fs%2F51rorvmwx&amp;image=https%3A%2F%2Fcodesandbox.io%2Fapi%2Fv1%2Fsandboxes%2F51rorvmwx%2Fscreenshot.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codesandbox" width="1000" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/3407c3948b40e6d18f1b4d59edeaf320/href">https://medium.com/media/3407c3948b40e6d18f1b4d59edeaf320/href</a></iframe><p>If you liked the content, please clap. It’s a really good exercise :)</p><p>Thanks for reading! ❤ #CodeEveryday</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=568761d09010" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a chatbot with Zendesk Chat Conversations API?]]></title>
            <link>https://smritibajaj22.medium.com/how-to-create-a-chatbot-with-zendesk-chat-conversations-api-ea6d2640ae59?source=rss-6ca40cf7da19------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea6d2640ae59</guid>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[chatbots]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[dialogflow]]></category>
            <category><![CDATA[zendesk]]></category>
            <dc:creator><![CDATA[Smriti Bajaj]]></dc:creator>
            <pubDate>Sat, 07 Nov 2020 13:26:03 GMT</pubDate>
            <atom:updated>2020-11-07T22:49:47.870Z</atom:updated>
            <content:encoded><![CDATA[<p>A <strong>chatbot</strong> is aimed to reduce human intervention by responding to the FAQs- general or specific to any domain(payment, Easter eggs, Hotel reservation, Marvel, DC etc.) 24/7, through channels like Slack, Hangouts, SMS, a website and others. Here, we will embed Zendesk’s UI(widget) which provides us an easy way to embed chatbots in our websites.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*tIo7EKG3trYmxDq6z0AJ3g.png" /><figcaption>A simple conversation between a user and a chatbot in Dialogflow</figcaption></figure><p><strong>Zendesk </strong>brings in customer engagement, has quickly configurable chat services, is easy to use, and it scales well to fit to our needs. It also allows you to leverage their existing UI for the chat widget and even provides an option to modify their UI via Web <a href="https://api.zopim.com/web-sdk/">SDK</a>.</p><p><strong><em>**Although, this post is suitable for mobile browsers, Zendesk supports mobile </em></strong><a href="https://developer.zendesk.com/embeddables/docs/android-ios-sdks/introduction"><strong><em>SDK</em></strong></a><strong><em> too.**</em></strong></p><p><strong>Prerequisites:</strong><br>1. Natural language understanding platform like Amazon Lex, Google’s Dialogflow, RASA. (To be discussed later)<br>2. Zendesk enterprise account acquisition (or trial)<br>3. Node.js</p><p>Now, we have the needful technology support but how to integrate them? For starters, in this post, we will discuss all about Zendesk. So, let’s begin by configuring the Zendesk account through the following steps-</p><ul><li>Create an account on <a href="https://www.zendesk.com/chat/">https://www.zendesk.com/chat/</a> and buy the enterprise plan. Beginners can use a 14-day trial pack.</li><li>After successful account creation, login to create an API client. The redirect URLs could be as simple as <a href="https://localhost:9000/">https://localhost:9000/</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*6ahY9ArqXiGifTh-glp_9g.png" /><figcaption>Zendesk dashboard view</figcaption></figure><ul><li>Once an API client is created, you will get a client Id and a secret key. Save it!</li><li>Do the authentication using CURL or by typing out the following URL in your browser.</li></ul><p><em>https://www.zopim.com/oauth2/authorizations/new?response_type=token&amp;client_id=&lt;client_id&gt;&amp;scope=read%20write%20chat&amp;subdomain=&lt;subDomain&gt;</em></p><p>You’ll get redirected to this URL. Now, save the access_token. <strong>This is very important token for us.</strong></p><p><em>https://&lt;redirect_url&gt;/#access_token=&lt;access_token&gt;&amp;token_type=Bearer&amp;scope=read+write+chat</em></p><ul><li>Create a department and add appropriate agents.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*G0Pl9B9BaGxMk4IihaPDoQ.png" /><figcaption>You can add the relevant agents (custom agents can be created through <strong>Agents</strong> menu option)</figcaption></figure><ul><li>Copy the Widget script to embed in an index.html or you website’s main page.</li></ul><p><em>&lt;! — Start of Zendesk Widget script → <br>&lt;script id=”ze-snippet” src=”https://static.zdassets.com/ekr/snippet.js?key=&lt;key&gt;&quot;&gt; &lt;/script&gt;<br>&lt;! — End of Zendesk Widget script →</em></p><ul><li>Hurray!!! We are good to launch the widget via that index.html.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/198/1*i6_RBo0zss1v5sHgZk0aMw.png" /><figcaption>Zendesk widget is customizable.</figcaption></figure><p>❤❤❤❤❤❤❤ Congratulations if you have come this far! ❤❤❤❤❤❤❤Now, if you’ll type a “hi” in the text box, it wouldn’t give you any response(after some time, you might get a Trigger message which you can configure through <strong><em>Triggers</em></strong> menu option). Hence the need of backend — backbone of this structure.</p><p>In the backend, we need to use Zendesk’s Chat Conversations API. To use this API, your account must be authenticated via the access token which we had generated in the part 1 of this post.</p><pre>`mutation($access_token: String!) {<br>startAgentSession(access_token: $access_token) {<br>websocket_url<br>session_id<br>client_id<br>}<br>}`;</pre><p>This token will then be sent to the <strong>CHAT_API_URL= </strong><a href="https://chat-api.zopim.com/graphql/request"><strong>https://chat-api.zopim.com/graphql/request</strong></a> (Makes an HTTP request). If the access_token is correct and the account is active, the endpoint will send a response payload as below with a websocket_url, a sessiond_id and a client_id.</p><pre>{<br>  &quot;data&quot;: {<br>    &quot;startAgentSession&quot;: {<br>      &quot;websocket_url&quot;:&quot;wss://chat-api.zopim.com/stream/0.1/graphql/8b40lm:9012841289&quot;,<br>      &quot;session_id&quot;:&quot;8b40lm&quot;,<br>      &quot;client_id&quot;:&quot;9012841289&quot;<br>    }<br>  }<br>}</pre><p>These values can now be utilized in a web socket request such as— wss://chat-api.zopim.com/stream/0.1/graphql/{session_id}:{client_id} A success will establish a connection with the Zendesk’s web socket.</p><p><strong><em>** A complete working code can be found </em></strong><a href="https://codesandbox.io/s/51rorvmwx"><strong><em>here</em></strong></a><strong><em>. *</em>*</strong></p><p>Too much to consume? Well, let’s look at the flow.</p><ul><li>First off, send a message to the chatbot. This activity of sending the message establishes a channel between the user/visitor and the Zendesk bot(API client created in part1). Every channel is assigned a unique channel id.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/175/1*NI9PEdG5VVN24D1boLI3ew.png" /></figure><ul><li>During this process, a listener will listen to the activities on the widget such as “open” and “message”. As the chat opens and the message is sent, Zendesk’s web socket connection will call handleOpen(). There, it will send a request in a <a href="https://zendesk.github.io/conversations-api/">graphql schema</a>- mutation/query/subscription.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/210/1*4wK4Uk0Fh7qQ0cBRyQ1-9A.png" /></figure><ul><li>Subscription is meant for message send/receive for a particular request_id which you can define in your application. If the message request is successful, we can listen to that Id, in the handleMessage().</li></ul><pre>webSocket.on(&#39;message&#39;, function(message) {<br>  const data = JSON.parse(message);<br>  let messageSubscriptionId;<br><br>  // Listen to successful message subscription request<br>  if (data.id === REQUEST_ID.MESSAGE_SUBSCRIPTION) {<br>    messageSubscriptionId = data.payload.data.subscription_id;<br>  }<br>});</pre><ul><li>To receive the response, from bot to visitor, we first listen to the visitor’s message, then to the same channel id, send “Welcome visitor!” and that involves another web socket request. For the customized message you can either use a JSON or NLP.</li></ul><pre>// Listen to chat messages from the visitor<br>  if (<br>    data.sig === &#39;DATA&#39; &amp;&amp;<br>    data.subscription_id === messageSubscriptionId &amp;&amp;<br>    data.payload.data<br>  ) {<br>    const chatMessage = data.payload.data.message.node;<br>    const sender = chatMessage.from;<br><br>    if (sender.__typename === TYPE.VISITOR) {<br>      console.log(<br>        `[message] Received: &#39;${chatMessage.content}&#39; from: &#39;${<br>          sender.display_name<br>        }&#39;`<br>      );<br><br>      const sendMessageQuery = {<br>        payload: {<br>          query: `mutation {<br>            sendMessage(channel_id: &quot;${chatMessage.channel.id}&quot;,<br>msg: &quot;Welcome visitor!&quot;) {<br>              success<br>            }<br>          }`<br>        },<br>        type: &#39;request&#39;,<br>        id: REQUEST_ID.SEND_MESSAGE<br>      };<br><br>      webSocket.send(JSON.stringify(sendMessageQuery));<br>    }</pre><ul><li>Voila! You have created a chatbot successfully.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/299/1*80opefA_Tp-IBJZfh158aA.png" /><figcaption>Source: <a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fapi.zopim.com%2Fweb-sdk%2F&amp;psig=AOvVaw2y9MrjTBF7NwTSYGCZ7MZW&amp;ust=1604839133688000&amp;source=images&amp;cd=vfe&amp;ved=0CAIQjRxqFwoTCMjG5Oa58OwCFQAAAAAdAAAAABAD">https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fapi.zopim.com%2Fweb-sdk%2F&amp;psig=AOvVaw2y9MrjTBF7NwTSYGCZ7MZW&amp;ust=1604839133688000&amp;source=images&amp;cd=vfe&amp;ved=0CAIQjRxqFwoTCMjG5Oa58OwCFQAAAAAdAAAAABAD</a></figcaption></figure><p><strong>Button Templates-</strong></p><p>For different button templates, you can refer — <a href="https://support.zendesk.com/hc/en-us/articles/360022184394-Using-structured-messages-in-Zendesk-Chat">https://support.zendesk.com/hc/en-us/articles/360022184394-Using-structured-messages-in-Zendesk-Chat</a></p><p><strong>Tips-</strong></p><ul><li>Use <a href="https://smritibajaj22.medium.com/how-to-configure-live-agent-functionality-using-zendesk-568761d09010">live agent functionality</a> for a better user experience(Ux).</li><li>Keep status of the API client as Online/Away.</li><li>Make your code modular.</li></ul><p><strong>References-</strong></p><p><a href="https://develop.zendesk.com/hc/en-us/articles/360001331787-Getting-started-with-the-Chat-Conversations-API">Getting started with the Chat Conversations API</a></p><p>This is my first post on Medium, let me know your opinion in the comment section below. Thanks for Reading! ❤ #CodeEveryday</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea6d2640ae59" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>