0.1.3 • Published 5 months ago

ori-bot-react-native v0.1.3

Weekly downloads
-
License
MIT
Repository
github
Last release
5 months ago

ori-bot-react-native

Documentation to integrate and use the Ori Chatbot React Native SDK (ver. 1.0.0)

Requirements

  • React Native >= 0.67.0
  • iOS >= 12.0
  • Android >= 6.0

Installation

$ npm install ori-bot-react-native @react-native-async-storage/async-storage @react-native-community/netinfo crypto-js react-native-device-info react-native-get-location react-native-permissions react-native-swipe-gestures react-native-webview rn-fetch-blob @react-native-firebase/app @react-native-firebase/messaging react-native-push-notification @react-native-community/push-notification-ios
# --- or ---
$ yarn add ori-bot-react-native @react-native-async-storage/async-storage @react-native-community/netinfo crypto-js react-native-device-info react-native-get-location react-native-permissions react-native-swipe-gestures react-native-webview rn-fetch-blob @react-native-firebase/app @react-native-firebase/messaging react-native-push-notification @react-native-community/push-notification-ios

Go to the folder your-project/ios and run pod install, and you're done.

Android post install

For Android you need to define the permissions on AndroidManifest.xml.

  <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.INTERNET" />
   <uses-permission android:name="android.permission.VIBRATE" />
   <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
   <uses-permission android:name="android.permission.RECORD_AUDIO" />
   <uses-permission android:name="android.permission.AUDIO_CAPTURE" />
   <uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
   <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
   <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
   <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
   <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
   <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
     <queries>
       <intent>
           <action android:name="android.speech.RecognitionService" />
       </intent>
   </queries>

iOS post install

For IOS You need to define the permission on Info.plist.

<key>NSCameraUsageDescription</key>
<string>Take pictures for certain activities</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app needs to get your location...</string>
<key>NSMicrophoneUsageDescription</key>
<string>Need microphone access for recording audio</string>
<key>NSPhotoLibraryAddUsageDescription</key>
<string>Save pictures for certain activities.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>Select pictures for certain activities</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>Description of why you require the use of speech recognition</string>
<key>UILaunchStoryboardName</key>
<string>LaunchScreen</string>
<key>UIUserInterfaceStyle</key>
<string>Light</string>
<key>UIBackgroundModes</key>
<array>
  <string>fetch</string>
  <string>remote-notification</string>
</array>
<key>NSLocationAlwaysUsageDescription</key>
<string>We use this to send notifications</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We use this to send notifications</string>
<key>NSLocationTemporaryUsageDescriptionDictionary</key>
<dict>
  <key>PushNotificationUsage</key>
  <string>We use this to send notifications</string>
</dict>

Native changes

You need to define the permission on android/build.gradle.

  dependencies {
      //other dependencies
      classpath 'com.google.gms:google-services:4.4.2'
  }

You need to define the permission on AppDelegate.mm.

#import <Firebase.h>
//other import

  - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
  {
  // other code
  [FIRApp configure];
  // Define UNUserNotificationCenter
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    center.delegate = self;
  // return statement

  }


  -(void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
  {
  //THIS ONE, it allows you to call javascript even on foreground state.
  NSDictionary *userInfo = notification.request.content.userInfo;
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo];
  completionHandler(UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert | UNNotificationPresentationOptionBadge);
  }


  // Required for the register event.
  - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
  {
  [RNCPushNotificationIOS didRegisterForRemoteNotificationsWithDeviceToken:deviceToken];
  }
  // Required for the notification event. You must call the completion handler after handling the remote notification.
  - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
  fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
  {
  [RNCPushNotificationIOS didReceiveRemoteNotification:userInfo fetchCompletionHandler:completionHandler];
  }
  // Required for the registrationError event.
  - (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
  {
  [RNCPushNotificationIOS didFailToRegisterForRemoteNotificationsWithError:error];
  }
  // Required for localNotification event
  - (void)userNotificationCenter:(UNUserNotificationCenter *)center
  didReceiveNotificationResponse:(UNNotificationResponse *)response
          withCompletionHandler:(void (^)(void))completionHandler
  {
  [RNCPushNotificationIOS didReceiveNotificationResponse:response];
  }

You need to define the permission on AppDelegate.h.

  #import <UserNotifications/UNUserNotificationCenter.h>
  //other imports
  // replace @interface AppDelegate : RCTAppDelegate with @interface AppDelegate : RCTAppDelegate <UNUserNotificationCenterDelegate>

Usage

import OriBotReactNativeView from 'ori-bot-react-native';

import type {
  BotDataModelLocal,
  BotEventsDataModel,
  BotResultDataModel,
} from 'ori-bot-react-native';

// ... your project code

const chatBotRef = useRef();

//temp data, need to modify as per your need
const defaultUserData = {
  udf3: {
    identifier: 'ir on app complaints journey',
    customer_name: 'Anand',
    pincode: '110010',
    journeyQuestion: 'My Question',
    country: 'India',
    journey: 'IR COMPLAINTS',
  },
  customerId: '',
  orderId: '',
  orderLineItemId: '',
  journeyId: '',
  stateCode: 'UP',
  customerName: 'Anurag Jain',
  backToExit: 'true',
  brand: 'vodafone-uat',
  appDetails: '8.0.4',
  redirectionType: 'internal',
  circle: '0011',
  lob: 'prepaid',
};


//example to start session session, here we have also handled notification so if your don't have notification you can just skip this processing
 const startSession = ({
   botIdData,
   numberData,
   pageTitleData,
   isToolBarVisibleData,
   isMiniToolBarVisibleData,
   isNativePopUpForExitData,
   userDataRemote,
   isNotification,
 }: any) => {

   const userDataTemp = isUserDataInput
     ? {
         udf1: numberData,
         nativePopupExit: isNativePopUpForExitData,
         ...JSON.parse(userDataInput),
       }
     : {
         udf1: numberData,
         nativePopupExit: isNativePopUpForExitData,
         ...defaultUserData,
       };


   console.log('userDataTemp1234', userDataTemp);
   const remoteTemp = userDataRemote
     ? JSON.parse(userDataRemote)
     : JSON.parse('{}');
   const mergedUdf3 = {
     ...userDataTemp.udf3,
     ...remoteTemp?.udf3,
   };


   // Create a new object with `newData` properties and updated `udf3`
   const userData = { ...userDataTemp, udf3: mergedUdf3 };


   const botData: BotDataModelLocal = {
     isToolBarVisible: isToolBarVisibleData,
     isMiniToolBarVisible: isMiniToolBarVisibleData,
     userData: userData,
     botIdentifier: 'vodafone-dev',
     pageTitle: pageTitleData,
     baseUrl: botIdData,
   };
   setTimeout(
     () => {
       // @ts-ignore
       chatBotRef?.current?.setChatBotData(botData);
     },
     isNotification ? 2000 : 1000
   );
 };

// you can add this with condition on same screen or navigate to another screen
<OriBotReactNativeView
  ref={chatBotRef}
  botId="botId"
  onChatEnd={()=>{
      console.log("Chat ended")
  }}
  onError={(error) => {
    console.log('error', error);
  }}
  onBotResult={(res: BotResultDataModel) => {
    console.log('onBotResult key :---->', res.key);
    console.log('onBotResult value:---->', res.value);
  }}
  onBotEvents={(data: BotEventsDataModel) => {
    console.log('onBotEvents value:----->', data.case);
    console.log('onBotEvents type:----->', data.type);
    console.log('onBotEvents value:----->', data.value);
  }}
  botKeys={BOT_KEYS}
/>;

//example to start the session on the same screen or you can add a view on another screen and can call startSession in use effect
<TouchableOpacity
  style={styles.buttonView}
  onPress={() =>
    startSession({
      botIdData: "Your url",
      numberData: "your number",
      pageTitleData: "Test title",
      isToolBarVisibleData: true,
      isMiniToolBarVisibleData: false,
      isNativePopUpForExitData: true,
      isNotification: false,
      userDataRemote: '{}',
    })
  }
>

Props

  • ref (OriBotReactNativeView ref) - Ref to the OriBotReactNativeView
  • botId (String) - Will be provided by the ORI team
  • config (Object{bundleToken: string, userObjectToken: string}) - Object will have two keys, will provided by ORI team
  • onChatEnd (Function) - callback when the chat session ended form the SDK
  • onBotResult (Function(BotResultDataModel)) - callback to receive results data in form of BotResultDataModel object
  • onBotEvents (Function(BotEventsDataModel)) - callback to receive event data in form of BotEventsDataModel object

Methods

  • clearLocalData () - method to clear any local data stored in SDK during old session
  • setChatBotData (BotDataModelLocal) - method to set custom data in the SDK inform of BotDataModelLocal model. For more information follow official ORI SDK documentation

License

Ori Chatbot

JSONStreamabbrevabort-controlleracceptsacornacorn-jsxacorn-walkadd-streamagent-baseaggregate-errorajvanseransi-alignansi-escapesansi-fragmentsansi-regexansi-stylesanymatchappdirsjsargargparsearray-buffer-byte-lengtharray-ifyarray-includesarray-unionarray.prototype.findlastarray.prototype.flatarray.prototype.flatmaparray.prototype.maparray.prototype.toreversedarray.prototype.tosortedarraybuffer.prototype.slicearrifyasapast-typesastral-regexasync-limiterasync-retryavailable-typed-arraysbabel-corebabel-jestbabel-plugin-istanbulbabel-plugin-jest-hoistbabel-plugin-polyfill-corejs2babel-plugin-polyfill-corejs3babel-plugin-polyfill-regeneratorbabel-plugin-transform-flow-enumsbabel-preset-current-node-syntaxbabel-preset-jestbalanced-matchbase64-jsbasic-ftpbefore-after-hookbig-integerblboxenbplist-parserbrace-expansionbracesbrowserslistbserbufferbuffer-frombundle-namebytescacachecacheable-lookupcacheable-requestcall-bindcaller-callsitecaller-pathcallsitescamelcasecamelcase-keyscaniuse-litechalkchar-regexchardetchownrchrome-launcherci-infocjs-module-lexerclean-stackcli-boxescli-cursorcli-spinnerscli-widthcliuicloneclone-deepcocollect-v8-coveragecolor-convertcolor-namecolorettecommand-existscommandercommondircompare-funccompressiblecompressionconcat-mapconcat-streamconfig-chainconfigstoreconnectconventional-changelogconventional-changelog-angularconventional-changelog-atomconventional-changelog-codemirrorconventional-changelog-conventionalcommitsconventional-changelog-coreconventional-changelog-emberconventional-changelog-eslintconventional-changelog-expressconventional-changelog-jqueryconventional-changelog-jshintconventional-changelog-preset-loaderconventional-changelog-writerconventional-commits-filterconventional-commits-parserconventional-recommended-bumpconvert-source-mapcore-js-compatcore-util-iscosmiconfigcosmiconfig-typescript-loadercreate-jestcreate-requirecross-spawncrypto-random-stringcsstypedargsdata-uri-to-bufferdata-view-bufferdata-view-byte-lengthdata-view-byte-offsetdateformatdayjsdebugdecamelizedecamelize-keysdecompress-responsededentdeep-extenddeep-isdeepmergedefault-browserdefault-browser-iddefaultsdefer-to-connectdefine-data-propertydefine-lazy-propdefine-propertiesdegeneratordeldenodeifydepddeprecationdestroydetect-newlinediffdiff-sequencesdir-globdoctrinedot-propeastasianwidthee-firstelectron-to-chromiumemitteryemoji-regexencodeurlencodingend-of-streamenv-pathsenvinfoerr-codeerror-exerror-stack-parsererrorhandleres-abstractes-array-method-boxes-properlyes-define-propertyes-errorses-get-iteratores-iterator-helperses-object-atomses-set-tostringtages-shim-unscopableses-to-primitiveescaladeescape-goatescape-htmlescape-string-regexpescodegeneslint-plugin-eslint-commentseslint-plugin-ft-floweslint-plugin-jesteslint-plugin-reacteslint-plugin-react-hookseslint-plugin-react-nativeeslint-plugin-react-native-globalseslint-scopeeslint-visitor-keysespreeesprimaesqueryesrecurseestraverseesutilsetagevent-target-shimexecaexitexpectexponential-backoffexternal-editorfast-deep-equalfast-difffast-globfast-json-stable-stringifyfast-levenshteinfast-xml-parserfastqfb-watchmanfetch-blobfiguresfile-entry-cachefill-rangefinalhandlerfind-cache-dirfind-upflat-cacheflattedflow-enums-runtimeflow-parserfor-eachforeground-childform-data-encoderformdata-polyfillfreshfs-extrafs-minipassfs.realpathfseventsfunction-bindfunction.prototype.namefunctions-have-namesgensyncget-caller-fileget-intrinsicget-package-typeget-pkg-repoget-streamget-symbol-descriptionget-urigit-raw-commitsgit-remote-origin-urlgit-semver-tagsgit-upgit-url-parsegitconfiglocalglobglob-parentglobal-dirsglobalsglobalthisglobbygopdgotgraceful-fsgraphemerhandlebarshard-rejectionhas-bigintshas-flaghas-property-descriptorshas-protohas-symbolshas-tostringtaghas-yarnhasownhermes-estreehermes-parserhermes-profile-transformerhosted-git-infohtml-escaperhttp-cache-semanticshttp-errorshttp-proxy-agenthttp2-wrapperhttps-proxy-agenthuman-signalsiconv-liteieee754ignoreimage-sizeimport-freshimport-lazyimport-localimurmurhashindent-stringinflightinheritsiniinquirerinternal-slotinterpretinvariantipip-addressis-absoluteis-argumentsis-array-bufferis-arrayishis-async-functionis-bigintis-boolean-objectis-callableis-ciis-core-moduleis-data-viewis-date-objectis-directoryis-dockeris-extglobis-finalizationregistryis-fullwidth-code-pointis-generator-fnis-generator-functionis-git-dirtyis-git-repositoryis-globis-inside-containeris-installed-globallyis-interactiveis-lambdais-mapis-negative-zerois-npmis-numberis-number-objectis-objis-path-cwdis-path-insideis-plain-objis-plain-objectis-regexis-relativeis-setis-shared-array-bufferis-sshis-streamis-stringis-symbolis-text-pathis-typed-arrayis-typedarrayis-unc-pathis-unicode-supportedis-weakmapis-weakrefis-weaksetis-windowsis-wslis-yarn-globalisarrayisexeisobjectissue-parseristanbul-lib-coverageistanbul-lib-instrumentistanbul-lib-reportistanbul-lib-source-mapsistanbul-reportsiterate-iteratoriterate-valueiterator.prototypejackspeakjest-changed-filesjest-circusjest-clijest-configjest-diffjest-docblockjest-eachjest-environment-nodejest-get-typejest-haste-mapjest-leak-detectorjest-matcher-utilsjest-message-utiljest-mockjest-pnp-resolverjest-regex-utiljest-resolvejest-resolve-dependenciesjest-runnerjest-runtimejest-snapshotjest-utiljest-validatejest-watcherjest-workerjetifierjoijs-tokensjs-yamljsbnjsc-androidjsc-safe-urljscodeshiftjsescjson-bufferjson-parse-better-errorsjson-parse-even-better-errorsjson-schema-traversejson-stable-stringify-without-jsonifyjson-stringify-safejson5jsonfilejsonparsejsx-ast-utilskeyvkind-ofkleurlatest-versionlevenlevnlighthouse-loggerlines-and-columnsload-json-filelocate-pathlodashlodash.camelcaselodash.capitalizelodash.debouncelodash.escaperegexplodash.isfunctionlodash.ismatchlodash.isplainobjectlodash.isstringlodash.kebabcaselodash.mergelodash.mergewithlodash.snakecaselodash.startcaselodash.throttlelodash.uniqlodash.uniqbylodash.upperfirstlog-symbolslogkittyloose-envifylowercase-keyslru-cachemacos-releasemake-dirmake-errormake-fetch-happenmakeerrormap-objmarkymemoize-onemeowmerge-optionsmerge-streammerge2metrometro-babel-transformermetro-cachemetro-cache-keymetro-configmetro-coremetro-file-mapmetro-minify-tersermetro-resolvermetro-runtimemetro-source-mapmetro-symbolicatemetro-transform-pluginsmetro-transform-workermicromatchmimemime-dbmime-typesmimic-fnmimic-responsemin-indentminimatchminimistminimist-optionsminipassminipass-collectminipass-fetchminipass-flushminipass-pipelineminipass-sizedminizlibmkdirpmodify-valuesmsmute-streamnatural-comparenatural-compare-litenegotiatorneo-asyncnetmasknew-github-release-urlnocachenode-abort-controllernode-dirnode-domexceptionnode-fetchnode-forgenode-gypnode-int64node-releasesnode-stream-zipnoptnormalize-package-datanormalize-pathnormalize-urlnpm-run-pathnullthrowsob1object-assignobject-inspectobject-keysobject.assignobject.entriesobject.fromentriesobject.hasownobject.valueson-finishedon-headersonceonetimeopenoptionatororaos-nameos-tmpdirp-cancelablep-limitp-locatep-mapp-trypac-proxy-agentpac-resolverpackage-jsonparent-moduleparse-jsonparse-pathparse-urlparseurlpath-existspath-is-absolutepath-keypath-parsepath-scurrypath-typepicocolorspicomatchpifypiratespkg-dirpossible-typed-array-namesprelude-lsprettier-linter-helperspretty-formatproc-logprocess-nextick-argspromisepromise-retrypromise.allsettledpromptsprop-typesproto-listprotocolsproxy-agentproxy-from-envpumppunycodepupapure-randqquerystringqueuequeue-microtaskquick-lrurange-parserrcreact-devtools-corereact-isreact-refreshreact-shallow-rendererread-pkgread-pkg-upreadable-streamreadlinerecastrechoirredentreflect.getprototypeofregenerateregenerate-unicode-propertiesregenerator-runtimeregenerator-transformregexp.prototype.flagsregexpu-coreregistry-auth-tokenregistry-urlregjsparserrequire-directoryrequire-from-stringrequire-main-filenameresolveresolve-alpnresolve-cwdresolve-fromresolve-globalresolve.exportsresponselikerestore-cursorretryreusifyrimrafrun-applescriptrun-asyncrun-parallelrxjssafe-array-concatsafe-buffersafe-regex-testsafer-bufferschedulerselfsignedsemversemver-diffsendserialize-errorserve-staticset-blockingset-function-lengthset-function-namesetprototypeofshallow-cloneshebang-commandshebang-regexshell-quoteshelljsside-channelsignal-exitsisteransislashslice-ansismart-buffersockssocks-proxy-agentsource-mapsource-map-supportspdx-correctspdx-exceptionsspdx-expression-parsespdx-license-idssplitsplit2sprintf-jsssristack-utilsstackframestacktrace-parserstatusesstdin-discarderstop-iteration-iteratorstring-lengthstring-natural-comparestring-widthstring-width-cjsstring.prototype.matchallstring.prototype.trimstring.prototype.trimendstring.prototype.trimstartstring_decoderstrip-ansistrip-ansi-cjsstrip-bomstrip-final-newlinestrip-indentstrip-json-commentsstrnumsudo-promptsupports-colorsupports-preserve-symlinks-flagsynckittartemptemp-dirtersertest-excludetext-extensionstext-tablethroatthroughthrough2titleizetmptmplto-fast-propertiesto-regex-rangetoidentifiertr46trim-newlinests-nodetslibtsutilsturbo-darwin-arm64type-checktype-detecttype-festtyped-array-buffertyped-array-byte-lengthtyped-array-byte-offsettyped-array-lengthtypedarraytypedarray-to-bufferuglify-jsunbox-primitiveunc-path-regexundici-typesunicode-canonical-property-names-ecmascriptunicode-match-property-ecmascriptunicode-match-property-value-ecmascriptunicode-property-aliases-ecmascriptunique-filenameunique-slugunique-stringuniversal-user-agentuniversalifyunpipeuntildifyupdate-browserslist-dbupdate-notifieruri-jsurl-joinutil-deprecateutils-mergev8-compile-cache-libv8-to-istanbulvalidate-npm-package-licensevaryvlqvm2walkerwcwidthweb-streams-polyfillwebidl-conversionswhatwg-fetchwhatwg-urlwhichwhich-boxed-primitivewhich-builtin-typewhich-collectionwhich-modulewhich-typed-arraywidest-linewildcard-matchwindows-releaseword-wrapwordwrapwrap-ansiwrap-ansi-cjswrappywrite-file-atomicwsxdg-basedirxtendy18nyallistyamlyargsyargs-parserynyocto-queue
0.1.2

5 months ago

0.1.1

5 months ago

0.1.3

5 months ago

0.1.0

12 months ago