@open-wa/wa-automate 4.24.2 → 4.26.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- [{"env":"WA_SESSION_DATA","p":"session-data","description":"The base64 encoded sessionData used to restore a session.","type":"string","key":"sessionData"},{"env":"WA_BROWSER_WS_ENDPOINT","p":"browser-ws-endpoint","type":"string","description":"ALPHA EXPERIMENTAL FEATURE! DO NOT USE IN PRODUCTION, REQUIRES TESTING.\n\nLearn more:\n\nhttps://pptr.dev/#?product=Puppeteer&version=v3.1.0&show=api-puppeteerconnectoptions\n\nhttps://medium.com/@jaredpotter1/connecting-puppeteer-to-existing-chrome-window-8a10828149e0","key":"browserWSEndpoint"},{"env":"WA_SESSION_DATA_PATH","p":"session-data-path","type":"string","description":"The path relative to the current working directory (i.e where you run the command to start your process). This will be used to store and read your `.data.json` files. defualt to ''","key":"sessionDataPath"},{"env":"WA_SKIP_UPDATE_CHECK","p":"skip-update-check","type":"boolean","description":"If set to true, `skipUpdateCheck` will bypass the latest version check. This saves some time on boot (around 150 ms).","key":"skipUpdateCheck"},{"env":"WA_SESSION_ID","p":"session-id","type":"string","description":"This is the name of the session. You have to make sure that this is unique for every session.","key":"sessionId"},{"env":"WA_LICENSE_KEY","p":"license-key","description":"The license key to use with the session.","type":"string","key":"licenseKey"},{"env":"WA_CUSTOM_USER_AGENT","p":"custom-user-agent","type":"string","description":"You may set a custom user agent. However, due to recent developments, this is not really neccessary any more.","key":"customUserAgent"},{"env":"WA_BLOCK_CRASH_LOGS","p":"block-crash-logs","type":"boolean","description":"Setting this to true will block any network calls to crash log servers. This should keep anything you do under the radar.","key":"blockCrashLogs"},{"env":"WA_CACHE_ENABLED","p":"cache-enabled","type":"boolean","description":"Setting this to false turn off the cache. This may improve memory usage.","key":"cacheEnabled"},{"env":"WA_BROWSER_REVISION","p":"browser-revision","type":"string","description":"This is the specific browser revision to be downlaoded and used. You can find browser revision strings here: http://omahaproxy.appspot.com/ Learn more about it here: https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-browserfetcher If you're having trouble with sending images, try '737027'. If you go too far back things will start breaking !!!!!! NOTE: THIS WILL OVERRIDE useChrome and executablePath. ONLY USE THIS IF YOU KNOW WHAT YOU ARE DOING.","key":"browserRevision"},{"env":"WA_HEADLESS","p":"headless","type":"boolean","description":"By default, all instances of @open-wa/wa-automate are headless (i.e you don't see a chrome window open), you can set this to false to show the chrome/chromium window.","key":"headless"},{"env":"WA_QR_TIMEOUT","p":"qr-timeout","type":"number","description":"This determines how long the process should wait for a QR code to be scanned before killing the process entirely. To have the system wait continuously, set this to `0`.","default":60,"key":"qrTimeout"},{"env":"WA_USE_CHROME","p":"use-chrome","type":"boolean","description":"If true, the program will automatically try to detect the instance of chorme on the machine. Please note this DOES NOT override executablePath.","key":"useChrome"},{"env":"WA_QR_LOG_SKIP","p":"qr-log-skip","type":"boolean","description":"If true, skips logging the QR Code to the console.","key":"qrLogSkip"},{"env":"WA_DISABLE_SPINS","p":"disable-spins","type":"boolean","description":"Setting this to true will simplify logs for use within docker containers by disabling spins (will still print raw messages).","key":"disableSpins"},{"env":"WA_LOG_CONSOLE","p":"log-console","type":"boolean","description":"If true, this will log any console messages from the browser.","key":"logConsole"},{"env":"WA_LOG_CONSOLE_ERRORS","p":"log-console-errors","type":"boolean","description":"If true, this will log any error messages from the browser instance","key":"logConsoleErrors"},{"env":"WA_AUTH_TIMEOUT","p":"auth-timeout","type":"number","description":"This determines how long the process should wait for the session authentication. If exceeded, checks if phone is out of reach (turned of or without internet connection) and throws an error. It does not relate to the amount of time spent waiting for a qr code scan (see [[qrTimeout]]). To have the system wait continuously, set this to `0`.","key":"authTimeout"},{"env":"WA_SAFE_MODE","p":"safe-mode","type":"boolean","description":"If true, client will check if the page is valid before each command. If page is not valid, it will throw an error.","key":"safeMode"},{"env":"WA_SKIP_SESSION_SAVE","p":"skip-session-save","type":"boolean","description":"If true, the process will not save a data.json file. This means that sessions will not be saved and you will need to pass sessionData as a config param or create the session data.json file yourself","key":"skipSessionSave"},{"env":"WA_POPUP","p":"popup","type":["boolean","number"],"description":"If true, the process will open a browser window where you will see basic event logs and QR codes to authenticate the session. Usually it will open on port 3000. It can also be set to a preferred port.\n\nYou can also get the QR code png at (if localhost and port 3000):\n\n`http://localhost:3000/qr`\n\nor if you have multiple session:\n\n `http://localhost:3000/qr?sessionId=[sessionId]`","key":"popup"},{"env":"WA_QR_POP_UP_ONLY","p":"qr-pop-up-only","type":"boolean","description":"This needs to be used in conjuction with `popup`, if `popup` is not true or a number (representing a desired port) then this will not work.\n\nSetting this to true will make sure that only the qr code png is served via the web server. This is useful if you do not need the whole status page.\n\nAs mentioned in [popup](#popup), the url for the qr code is `http://localhost:3000/qr` if the port is 3000.","key":"qrPopUpOnly"},{"env":"WA_BLOCK_ASSETS","p":"block-assets","type":"boolean","description":"Setting this to true will block all assets from loading onto the page. This may result in some load time improvements but also increases instability.","key":"blockAssets"},{"env":"WA_KEEP_UPDATED","p":"keep-updated","type":"boolean","description":"[ALPHA FEATURE - ONLY IMPLEMENTED FOR TESTING - DO NOT USE IN PRODUCTION YET] Setting this to true will result in the library making sure it is always starting with the latest version of itself. This overrides `skipUpdateCheck`.","key":"keepUpdated"},{"env":"WA_RESIZABLE","p":"resizable","type":"boolean","description":"Syncs the viewport size with the window size which is how normal browsers act. Only relevant when `headless: false` and this overrides `viewport` config.","key":"resizable"},{"env":"WA_VIEWPORT","p":"viewport","type":"object","properties":{"width":{"type":"number","description":"Page width in pixels"},"height":{"type":"number","description":"Page height in pixels"}},"additionalProperties":false,"description":"Set the desired viewport height and width. For CLI, use [width]x[height] format. E.g `--viewport 1920x1080`.","key":"viewport"},{"env":"WA_LEGACY","p":"legacy","type":"boolean","description":"As the library is constantly evolving, some parts will be replaced with more efficient and improved code. In some of the infinite edge cases these new changes may not work for you. Set this to true to roll back on 'late beta' features. The reason why legacy is false by default is that in order for features to be tested they have to be released and used by everyone to find the edge cases and fix them.","key":"legacy"},{"env":"WA_DELETE_SESSION_DATA_ON_LOGOUT","p":"delete-session-data-on-logout","type":"boolean","description":"Deletes the session data file (if found) on logout event. This results in a quicker login when you restart the process.","key":"deleteSessionDataOnLogout"},{"env":"WA_KILL_PROCESS_ON_TIMEOUT","p":"kill-process-on-timeout","type":"boolean","description":"If set to true, the system will kill the whole node process when either an [[authTimeout]] or a [[qrTimeout]] has been reached. This is useful to prevent hanging processes.","key":"killProcessOnTimeout"},{"env":"WA_CORS_FIX","p":"cors-fix","type":"boolean","description":"Setting this to true will bypass web security. DO NOT DO THIS IF YOU DO NOT HAVE TO. CORS issue may arise when using a proxy.","key":"corsFix"},{"env":"WA_CALL_TIMEOUT","p":"call-timeout","type":"number","description":"Amount of time (in ms) to wait for a client method (specifically methods that interact with the WA web session) to resolve. If a client method results takes longer than the timout value then it will result in a [[PageEvaluationTimeout]] error.\n\nIf you get this error, it does not automatically mean that the method failed - it just stops your program from waiting for a client method to resolve.\n\nThis is useful if you do not rely on the results of a client method (e.g the message ID).\n\nIf set to `0`, the process will wait indefinitely for a client method to resolve.","default":0,"key":"callTimeout"},{"env":"WA_SCREENSHOT_ON_INITIALIZATION_BROWSER_ERROR","p":"screenshot-on-initialization-browser-error","type":"boolean","description":"When true, this option will take a screenshot of the browser when an unexpected error occurs within the browser during `create` initialization. The path will be `[working directory]/logs/[session ID]/[start timestamp]/[timestamp].jpg`","key":"screenshotOnInitializationBrowserError"},{"env":"WA_EVENT_MODE","p":"event-mode","type":"boolean","description":"Setting listeners may not be your cup of tea. With eventMode, all [[SimpleListener]] events will be registered automatically and be filed via the built in Events Listener.\n\nThis is useful because you can register/deregister the event listener as needed whereas the legacy method of setting callbacks are only be set once","key":"eventMode"},{"env":"WA_LOG_FILE","p":"log-file","type":"boolean","description":"If true, the system will automatically create a log of all processes relating to actions sent to the web session.\n\nThe location of the file will be relative to the process directory (pd)\n\n`[pd]/[sessionId]/[start timestamp].log`","default":false,"key":"logFile"},{"env":"WA_ID_CORRECTION","p":"id-correction","type":"boolean","description":"When true, the system will attempt to correct chatIds and groupChatIds. This means you can ignore `@c.us` and `@g.us` distinctions in some parameters.","default":false,"key":"idCorrection"},{"env":"WA_STICKER_SERVER_ENDPOINT","p":"sticker-server-endpoint","type":["string","boolean"],"description":"Redundant until self-hostable sticker server is available.","key":"stickerServerEndpoint"},{"env":"WA_CACHED_PATCH","p":"cached-patch","type":"boolean","description":"This will force the library to use the default cached raw github link for patches to shave a few hundred milliseconds from your launch time. If you use this option, you will need to wait about 5 minutes before trying out new patches.","key":"cachedPatch"},{"env":"WA_LOG_DEBUG_INFO_AS_OBJECT","p":"log-debug-info-as-object","type":"boolean","description":"Setting `this` to true will replace the `console.table` with a stringified logging of the debug info object instead. This would be useful to set for smaller terminal windows. If `disableSpins` is `true` then this will also be `true`.","key":"logDebugInfoAsObject"},{"env":"WA_KILL_CLIENT_ON_LOGOUT","p":"kill-client-on-logout","type":"boolean","description":"Kill the client when a logout is detected","key":"killClientOnLogout"},{"env":"WA_THROW_ON_EXPIRED_SESSION_DATA","p":"throw-on-expired-session-data","type":"boolean","description":"This will make the `create` command return `false` if the detected session data is expired.\n\nThis will mean, the process will not attempt to automatically get a new QR code.","key":"throwOnExpiredSessionData"},{"env":"WA_USE_NATIVE_PROXY","p":"use-native-proxy","type":"boolean","description":"Some sessions may experience issues with sending media when using proxies. Using the native proxy system instead of the recommended 3rd party library may fix these issues.","key":"useNativeProxy"},{"env":"WA_RASPI","p":"raspi","type":"boolean","description":"Set this to `true` to make the library work on Raspberry Pi OS.\n\nMake sure to run the following command before running the library the first time:\n\n``` > sudo apt update -y && sudo apt install chromium-browser chromium-codecs-ffmpeg -y && sudo apt upgrade ```\n\nIf you're using the CLI, you can set this value to `true` by adding the following flag to the CLI command\n\n``` > npx @open-wa/wa-automate ... --raspi ```","key":"raspi"},{"env":"WA_MULTI_DEVICE","p":"multi-device","type":"boolean","description":"Please note that multi-device is still in beta so a lot of things may not work. It is HIGHLY suggested to NOT use this in production!!!!\n\nSet this to true if you're using the multidevice beta.","key":"multiDevice"},{"env":"WA_SESSION_DATA_BUCKET_AUTH","p":"session-data-bucket-auth","type":"string","description":"Base64 encoded S3 Bucket & Authentication object for session data files. The object should be in the same format as cloudUploadOptions.","key":"sessionDataBucketAuth"},{"env":"WA_AUTO_EMOJI","p":"auto-emoji","type":"string","description":"Set the automatic emoji detection character. Set this to false to disable auto emoji. Default is `:`.","key":"autoEmoji"},{"env":"WA_MAX_CHATS","p":"max-chats","type":"number","description":"Set the maximum amount of chats to be present in a session.","key":"maxChats"},{"env":"WA_MAX_MESSAGES","p":"max-messages","type":"number","description":"Set the maximum amount of messages to be present in a session.","key":"maxMessages"},{"env":"WA_DISCORD","p":"discord","type":"string","description":"Your Discord ID to get onto the sticker leaderboard!","key":"discord"},{"env":"WA_IGNORE_NUKE","p":"ignore-nuke","type":"boolean","description":"Don't implicitly determine if the host logged out.","key":"ignoreNuke"},{"env":"WA_ENSURE_HEADFUL_INTEGRITY","p":"ensure-headful-integrity","type":"boolean","description":"Makes sure the headless session is usable even on first login. Headful sessions are ususally only usable on reauthentication.","key":"ensureHeadfulIntegrity"},{"env":"WA_WAIT_FOR_RIPE_SESSION","p":"wait-for-ripe-session","type":"boolean","description":"wait for a valid headful session. Not required in recent versions.","key":"waitForRipeSession"}]
1
+ [{"env":"WA_SESSION_DATA","p":"session-data","description":"The base64 encoded sessionData used to restore a session.","type":"string","key":"sessionData"},{"env":"WA_BROWSER_WS_ENDPOINT","p":"browser-ws-endpoint","type":"string","description":"ALPHA EXPERIMENTAL FEATURE! DO NOT USE IN PRODUCTION, REQUIRES TESTING.\n\nLearn more:\n\nhttps://pptr.dev/#?product=Puppeteer&version=v3.1.0&show=api-puppeteerconnectoptions\n\nhttps://medium.com/@jaredpotter1/connecting-puppeteer-to-existing-chrome-window-8a10828149e0","key":"browserWSEndpoint"},{"env":"WA_SESSION_DATA_PATH","p":"session-data-path","type":"string","description":"The path relative to the current working directory (i.e where you run the command to start your process). This will be used to store and read your `.data.json` files. defualt to ''","key":"sessionDataPath"},{"env":"WA_SKIP_UPDATE_CHECK","p":"skip-update-check","type":"boolean","description":"If set to true, `skipUpdateCheck` will bypass the latest version check. This saves some time on boot (around 150 ms).","key":"skipUpdateCheck"},{"env":"WA_SESSION_ID","p":"session-id","type":"string","description":"This is the name of the session. You have to make sure that this is unique for every session.","key":"sessionId"},{"env":"WA_LICENSE_KEY","p":"license-key","description":"The license key to use with the session.","type":"string","key":"licenseKey"},{"env":"WA_CUSTOM_USER_AGENT","p":"custom-user-agent","type":"string","description":"You may set a custom user agent. However, due to recent developments, this is not really neccessary any more.","key":"customUserAgent"},{"env":"WA_BLOCK_CRASH_LOGS","p":"block-crash-logs","type":"boolean","description":"Setting this to true will block any network calls to crash log servers. This should keep anything you do under the radar.","key":"blockCrashLogs"},{"env":"WA_CACHE_ENABLED","p":"cache-enabled","type":"boolean","description":"Setting this to false turn off the cache. This may improve memory usage.","key":"cacheEnabled"},{"env":"WA_BROWSER_REVISION","p":"browser-revision","type":"string","description":"This is the specific browser revision to be downlaoded and used. You can find browser revision strings here: http://omahaproxy.appspot.com/ Learn more about it here: https://github.com/puppeteer/puppeteer/blob/master/docs/api.md#class-browserfetcher If you're having trouble with sending images, try '737027'. If you go too far back things will start breaking !!!!!! NOTE: THIS WILL OVERRIDE useChrome and executablePath. ONLY USE THIS IF YOU KNOW WHAT YOU ARE DOING.","key":"browserRevision"},{"env":"WA_HEADLESS","p":"headless","type":"boolean","description":"By default, all instances of @open-wa/wa-automate are headless (i.e you don't see a chrome window open), you can set this to false to show the chrome/chromium window.","key":"headless"},{"env":"WA_QR_TIMEOUT","p":"qr-timeout","type":"number","description":"This determines how long the process should wait for a QR code to be scanned before killing the process entirely. To have the system wait continuously, set this to `0`.","default":60,"key":"qrTimeout"},{"env":"WA_USE_CHROME","p":"use-chrome","type":"boolean","description":"If true, the program will automatically try to detect the instance of chorme on the machine. Please note this DOES NOT override executablePath.","key":"useChrome"},{"env":"WA_QR_LOG_SKIP","p":"qr-log-skip","type":"boolean","description":"If true, skips logging the QR Code to the console.","key":"qrLogSkip"},{"env":"WA_DISABLE_SPINS","p":"disable-spins","type":"boolean","description":"Setting this to true will simplify logs for use within docker containers by disabling spins (will still print raw messages).","key":"disableSpins"},{"env":"WA_LOG_CONSOLE","p":"log-console","type":"boolean","description":"If true, this will log any console messages from the browser.","key":"logConsole"},{"env":"WA_LOG_CONSOLE_ERRORS","p":"log-console-errors","type":"boolean","description":"If true, this will log any error messages from the browser instance","key":"logConsoleErrors"},{"env":"WA_AUTH_TIMEOUT","p":"auth-timeout","type":"number","description":"This determines how long the process should wait for the session authentication. If exceeded, checks if phone is out of reach (turned of or without internet connection) and throws an error. It does not relate to the amount of time spent waiting for a qr code scan (see [[qrTimeout]]). To have the system wait continuously, set this to `0`.","key":"authTimeout"},{"env":"WA_SAFE_MODE","p":"safe-mode","type":"boolean","description":"If true, client will check if the page is valid before each command. If page is not valid, it will throw an error.","key":"safeMode"},{"env":"WA_SKIP_SESSION_SAVE","p":"skip-session-save","type":"boolean","description":"If true, the process will not save a data.json file. This means that sessions will not be saved and you will need to pass sessionData as a config param or create the session data.json file yourself","key":"skipSessionSave"},{"env":"WA_POPUP","p":"popup","type":["boolean","number"],"description":"If true, the process will open a browser window where you will see basic event logs and QR codes to authenticate the session. Usually it will open on port 3000. It can also be set to a preferred port.\n\nYou can also get the QR code png at (if localhost and port 3000):\n\n`http://localhost:3000/qr`\n\nor if you have multiple session:\n\n `http://localhost:3000/qr?sessionId=[sessionId]`","key":"popup"},{"env":"WA_QR_POP_UP_ONLY","p":"qr-pop-up-only","type":"boolean","description":"This needs to be used in conjuction with `popup`, if `popup` is not true or a number (representing a desired port) then this will not work.\n\nSetting this to true will make sure that only the qr code png is served via the web server. This is useful if you do not need the whole status page.\n\nAs mentioned in [popup](#popup), the url for the qr code is `http://localhost:3000/qr` if the port is 3000.","key":"qrPopUpOnly"},{"env":"WA_BLOCK_ASSETS","p":"block-assets","type":"boolean","description":"Setting this to true will block all assets from loading onto the page. This may result in some load time improvements but also increases instability.","key":"blockAssets"},{"env":"WA_KEEP_UPDATED","p":"keep-updated","type":"boolean","description":"[ALPHA FEATURE - ONLY IMPLEMENTED FOR TESTING - DO NOT USE IN PRODUCTION YET] Setting this to true will result in the library making sure it is always starting with the latest version of itself. This overrides `skipUpdateCheck`.","key":"keepUpdated"},{"env":"WA_RESIZABLE","p":"resizable","type":"boolean","description":"Syncs the viewport size with the window size which is how normal browsers act. Only relevant when `headless: false` and this overrides `viewport` config.","key":"resizable"},{"env":"WA_VIEWPORT","p":"viewport","type":"object","properties":{"width":{"type":"number","description":"Page width in pixels"},"height":{"type":"number","description":"Page height in pixels"}},"additionalProperties":false,"description":"Set the desired viewport height and width. For CLI, use [width]x[height] format. E.g `--viewport 1920x1080`.","key":"viewport"},{"env":"WA_LEGACY","p":"legacy","type":"boolean","description":"As the library is constantly evolving, some parts will be replaced with more efficient and improved code. In some of the infinite edge cases these new changes may not work for you. Set this to true to roll back on 'late beta' features. The reason why legacy is false by default is that in order for features to be tested they have to be released and used by everyone to find the edge cases and fix them.","key":"legacy"},{"env":"WA_DELETE_SESSION_DATA_ON_LOGOUT","p":"delete-session-data-on-logout","type":"boolean","description":"Deletes the session data file (if found) on logout event. This results in a quicker login when you restart the process.","key":"deleteSessionDataOnLogout"},{"env":"WA_KILL_PROCESS_ON_TIMEOUT","p":"kill-process-on-timeout","type":"boolean","description":"If set to true, the system will kill the whole node process when either an [[authTimeout]] or a [[qrTimeout]] has been reached. This is useful to prevent hanging processes.","key":"killProcessOnTimeout"},{"env":"WA_CORS_FIX","p":"cors-fix","type":"boolean","description":"Setting this to true will bypass web security. DO NOT DO THIS IF YOU DO NOT HAVE TO. CORS issue may arise when using a proxy.","key":"corsFix"},{"env":"WA_CALL_TIMEOUT","p":"call-timeout","type":"number","description":"Amount of time (in ms) to wait for a client method (specifically methods that interact with the WA web session) to resolve. If a client method results takes longer than the timout value then it will result in a [[PageEvaluationTimeout]] error.\n\nIf you get this error, it does not automatically mean that the method failed - it just stops your program from waiting for a client method to resolve.\n\nThis is useful if you do not rely on the results of a client method (e.g the message ID).\n\nIf set to `0`, the process will wait indefinitely for a client method to resolve.","default":0,"key":"callTimeout"},{"env":"WA_SCREENSHOT_ON_INITIALIZATION_BROWSER_ERROR","p":"screenshot-on-initialization-browser-error","type":"boolean","description":"When true, this option will take a screenshot of the browser when an unexpected error occurs within the browser during `create` initialization. The path will be `[working directory]/logs/[session ID]/[start timestamp]/[timestamp].jpg`","key":"screenshotOnInitializationBrowserError"},{"env":"WA_EVENT_MODE","p":"event-mode","type":"boolean","description":"Setting listeners may not be your cup of tea. With eventMode, all [[SimpleListener]] events will be registered automatically and be filed via the built in Events Listener.\n\nThis is useful because you can register/deregister the event listener as needed whereas the legacy method of setting callbacks are only be set once","key":"eventMode"},{"env":"WA_LOG_FILE","p":"log-file","type":"boolean","description":"If true, the system will automatically create a log of all processes relating to actions sent to the web session.\n\nThe location of the file will be relative to the process directory (pd)\n\n`[pd]/[sessionId]/[start timestamp].log`","default":false,"key":"logFile"},{"env":"WA_ID_CORRECTION","p":"id-correction","type":"boolean","description":"When true, the system will attempt to correct chatIds and groupChatIds. This means you can ignore `@c.us` and `@g.us` distinctions in some parameters.","default":false,"key":"idCorrection"},{"env":"WA_STICKER_SERVER_ENDPOINT","p":"sticker-server-endpoint","type":["string","boolean"],"description":"Redundant until self-hostable sticker server is available.","key":"stickerServerEndpoint"},{"env":"WA_GH_PATCH","p":"gh-patch","type":"boolean","description":"This will force the library to use the default cached raw github link for patches to shave a few hundred milliseconds from your launch time. If you use this option, you will need to wait about 5 minutes before trying out new patches.","key":"ghPatch"},{"env":"WA_CACHED_PATCH","p":"cached-patch","type":"boolean","description":"Setting this to `true` will save a local copy of the patches.json file (as patches.ignore.data.json) which will be used in subsequent instantiations of the session. While the rest of the launch procedure is running, the library will fetch and save a recent version of the patches to ensure your patches don't go stale. This will be ignored if the cached patches are more than a day old.","key":"cachedPatch"},{"env":"WA_LOG_DEBUG_INFO_AS_OBJECT","p":"log-debug-info-as-object","type":"boolean","description":"Setting `this` to true will replace the `console.table` with a stringified logging of the debug info object instead. This would be useful to set for smaller terminal windows. If `disableSpins` is `true` then this will also be `true`.","key":"logDebugInfoAsObject"},{"env":"WA_KILL_CLIENT_ON_LOGOUT","p":"kill-client-on-logout","type":"boolean","description":"Kill the client when a logout is detected","key":"killClientOnLogout"},{"env":"WA_THROW_ON_EXPIRED_SESSION_DATA","p":"throw-on-expired-session-data","type":"boolean","description":"This will make the `create` command return `false` if the detected session data is expired.\n\nThis will mean, the process will not attempt to automatically get a new QR code.","key":"throwOnExpiredSessionData"},{"env":"WA_USE_NATIVE_PROXY","p":"use-native-proxy","type":"boolean","description":"Some sessions may experience issues with sending media when using proxies. Using the native proxy system instead of the recommended 3rd party library may fix these issues.","key":"useNativeProxy"},{"env":"WA_RASPI","p":"raspi","type":"boolean","description":"Set this to `true` to make the library work on Raspberry Pi OS.\n\nMake sure to run the following command before running the library the first time:\n\n``` > sudo apt update -y && sudo apt install chromium-browser chromium-codecs-ffmpeg -y && sudo apt upgrade ```\n\nIf you're using the CLI, you can set this value to `true` by adding the following flag to the CLI command\n\n``` > npx @open-wa/wa-automate ... --raspi ```","key":"raspi"},{"env":"WA_MULTI_DEVICE","p":"multi-device","type":"boolean","description":"Please note that multi-device is still in beta so a lot of things may not work. It is HIGHLY suggested to NOT use this in production!!!!\n\nSet this to true if you're using the multidevice beta.","key":"multiDevice"},{"env":"WA_SESSION_DATA_BUCKET_AUTH","p":"session-data-bucket-auth","type":"string","description":"Base64 encoded S3 Bucket & Authentication object for session data files. The object should be in the same format as cloudUploadOptions.","key":"sessionDataBucketAuth"},{"env":"WA_AUTO_EMOJI","p":"auto-emoji","type":"string","description":"Set the automatic emoji detection character. Set this to false to disable auto emoji. Default is `:`.","key":"autoEmoji"},{"env":"WA_MAX_CHATS","p":"max-chats","type":"number","description":"Set the maximum amount of chats to be present in a session.","key":"maxChats"},{"env":"WA_MAX_MESSAGES","p":"max-messages","type":"number","description":"Set the maximum amount of messages to be present in a session.","key":"maxMessages"},{"env":"WA_DISCORD","p":"discord","type":"string","description":"Your Discord ID to get onto the sticker leaderboard!","key":"discord"},{"env":"WA_IGNORE_NUKE","p":"ignore-nuke","type":"boolean","description":"Don't implicitly determine if the host logged out.","key":"ignoreNuke"},{"env":"WA_ENSURE_HEADFUL_INTEGRITY","p":"ensure-headful-integrity","type":"boolean","description":"Makes sure the headless session is usable even on first login. Headful sessions are ususally only usable on reauthentication.","key":"ensureHeadfulIntegrity"},{"env":"WA_WAIT_FOR_RIPE_SESSION","p":"wait-for-ripe-session","type":"boolean","description":"wait for a valid headful session. Not required in recent versions.","key":"waitForRipeSession"}]
@@ -39,6 +39,8 @@ export declare class Client {
39
39
  private _refreshing;
40
40
  private _l;
41
41
  private _prio;
42
+ private _pageListeners;
43
+ private _registeredPageListeners;
42
44
  private _queues;
43
45
  /**
44
46
  * This is used to track if a listener is already used via webhook. Before, webhooks used to be set once per listener. Now a listener can be set via multiple webhooks, or revoked from a specific webhook.
@@ -104,6 +106,7 @@ export declare class Client {
104
106
  *
105
107
  */
106
108
  private registerListener;
109
+ private registerPageEventListener;
107
110
  /**
108
111
  * Listens to a log out event
109
112
  *
@@ -111,7 +114,11 @@ export declare class Client {
111
114
  * @param fn callback
112
115
  * @fires `true`
113
116
  */
114
- onLogout(fn: (loggedOut?: boolean) => any): Promise<boolean>;
117
+ onLogout(fn: (loggedOut?: boolean) => any, priority?: number): Promise<boolean>;
118
+ /**
119
+ * Wait for the webhook queue to become idle. This is useful for ensuring webhooks are cleared before ending a process.
120
+ */
121
+ waitWhQIdle(): Promise<any>;
115
122
  /**
116
123
  * If you have set `onAnyMessage` or `onMessage` with the second parameter (PQueue options) then you may want to inspect their respective PQueue's.
117
124
  */
@@ -63,7 +63,7 @@ const auth_1 = require("../controllers/auth");
63
63
  const wa_decrypt_1 = require("@open-wa/wa-decrypt");
64
64
  const path = __importStar(require("path"));
65
65
  const media_1 = require("./model/media");
66
- const initializer_1 = require("../controllers/initializer");
66
+ const patch_manager_1 = require("../controllers/patch_manager");
67
67
  const events_2 = require("./model/events");
68
68
  const MessageCollector_1 = require("../structures/MessageCollector");
69
69
  const init_patch_1 = require("../controllers/init_patch");
@@ -104,6 +104,8 @@ class Client {
104
104
  this._currentlyBeingKilled = false;
105
105
  this._refreshing = false;
106
106
  this._prio = Number.MAX_SAFE_INTEGER;
107
+ this._pageListeners = [];
108
+ this._registeredPageListeners = [];
107
109
  this._queues = {};
108
110
  /**
109
111
  * This is used to track if a listener is already used via webhook. Before, webhooks used to be set once per listener. Now a listener can be set via multiple webhooks, or revoked from a specific webhook.
@@ -350,7 +352,7 @@ class Client {
350
352
  /**
351
353
  * preload license
352
354
  */
353
- const preloadlicense = ((_c = this._createConfig) === null || _c === void 0 ? void 0 : _c.licenseKey) ? yield initializer_1.getLicense(this._createConfig, me, this._sessionInfo, spinner) : false;
355
+ const preloadlicense = ((_c = this._createConfig) === null || _c === void 0 ? void 0 : _c.licenseKey) ? yield patch_manager_1.getLicense(this._createConfig, me, this._sessionInfo, spinner) : false;
354
356
  spinner.info('Refreshing session');
355
357
  const START_TIME = Date.now();
356
358
  spinner.info("Opening session in new tab");
@@ -373,7 +375,7 @@ class Client {
373
375
  /**
374
376
  * Wait for the new page to be loaded up before closing existing page
375
377
  */
376
- yield initializer_1.earlyInjectionCheck(newTab);
378
+ yield patch_manager_1.earlyInjectionCheck(newTab);
377
379
  spinner.info("Checking if fresh session is authenticated...");
378
380
  if (yield auth_1.isAuthenticated(newTab)) {
379
381
  /**
@@ -394,9 +396,9 @@ class Client {
394
396
  /**
395
397
  * patch
396
398
  */
397
- yield initializer_1.getAndInjectLivePatch(newTab, spinner, null, this._createConfig, this._sessionInfo);
399
+ yield patch_manager_1.getAndInjectLivePatch(newTab, spinner, null, this._createConfig, this._sessionInfo);
398
400
  if ((_f = this._createConfig) === null || _f === void 0 ? void 0 : _f.licenseKey)
399
- yield initializer_1.getAndInjectLicense(newTab, this._createConfig, me, this._sessionInfo, spinner, preloadlicense);
401
+ yield patch_manager_1.getAndInjectLicense(newTab, this._createConfig, me, this._sessionInfo, spinner, preloadlicense);
400
402
  /**
401
403
  * init patch
402
404
  */
@@ -552,7 +554,21 @@ class Client {
552
554
  return res;
553
555
  });
554
556
  }
555
- // NON-STAMDARD LISTENERS
557
+ // NON-STANDARD LISTENERS
558
+ registerPageEventListener(_event, callback, priority) {
559
+ const event = _event;
560
+ this._pageListeners.push({
561
+ event,
562
+ callback,
563
+ priority
564
+ });
565
+ if (this._registeredPageListeners.includes(event))
566
+ return true;
567
+ this._page.on(event, (...args) => __awaiter(this, void 0, void 0, function* () {
568
+ return yield Promise.all(this._pageListeners.filter(l => l.event === event).sort((a, b) => (b.priority || 0) - (a.priority || 0)).map(l => l.callback(...args)));
569
+ }));
570
+ this._registeredPageListeners.push(event);
571
+ }
556
572
  /**
557
573
  * Listens to a log out event
558
574
  *
@@ -560,17 +576,25 @@ class Client {
560
576
  * @param fn callback
561
577
  * @fires `true`
562
578
  */
563
- onLogout(fn) {
579
+ onLogout(fn, priority) {
564
580
  return __awaiter(this, void 0, void 0, function* () {
565
- yield this._page.on('request', request => {
566
- if (request.url() === "https://web.whatsapp.com/" && !this._refreshing)
567
- fn();
568
- });
569
- this.onStateChanged(state => {
570
- if (state === model_1.STATE.UNPAIRED) {
571
- fn();
581
+ this.registerPageEventListener('framenavigated', (frame) => __awaiter(this, void 0, void 0, function* () {
582
+ if (frame.url().includes('post_logout=1')) {
583
+ console.log("LOGGED OUT");
584
+ yield fn(true);
572
585
  }
573
- });
586
+ }), priority);
587
+ return true;
588
+ });
589
+ }
590
+ /**
591
+ * Wait for the webhook queue to become idle. This is useful for ensuring webhooks are cleared before ending a process.
592
+ */
593
+ waitWhQIdle() {
594
+ return __awaiter(this, void 0, void 0, function* () {
595
+ if (this._webhookQueue) {
596
+ return yield this._webhookQueue.onIdle();
597
+ }
574
598
  return true;
575
599
  });
576
600
  }
@@ -3309,7 +3333,7 @@ class Client {
3309
3333
  ...Object.keys(this._registeredWebhooks).map(webhookId => this._registeredWebhooks[webhookId]).filter(webhookEntry => webhookEntry.events.includes(event))
3310
3334
  ].map(({ id, url, requestConfig }) => axios_1.default(Object.assign({ method: 'post', url, data: this.prepEventData(_data, event, { webhook_id: id }) }, requestConfig)).catch(err => console.error(`WEBHOOK ERROR: `, url, err.message))));
3311
3335
  }));
3312
- }));
3336
+ }), 10000);
3313
3337
  }
3314
3338
  }
3315
3339
  });
@@ -552,6 +552,11 @@ export interface ConfigObject {
552
552
  * This will force the library to use the default cached raw github link for patches to shave a few hundred milliseconds from your launch time. If you use this option, you will need to wait about 5 minutes before trying out new patches.
553
553
  * @default `false`
554
554
  */
555
+ ghPatch?: boolean;
556
+ /**
557
+ * Setting this to `true` will save a local copy of the patches.json file (as patches.ignore.data.json) which will be used in subsequent instantiations of the session. While the rest of the launch procedure is running, the library will fetch and save a recent version of the patches to ensure your patches don't go stale. This will be ignored if the cached patches are more than a day old.
558
+ * @default `false`
559
+ */
555
560
  cachedPatch?: boolean;
556
561
  /**
557
562
  * Setting `this` to true will replace the `console.table` with a stringified logging of the debug info object instead. This would be useful to set for smaller terminal windows. If `disableSpins` is `true` then this will also be `true`.
package/dist/cli/index.js CHANGED
@@ -23,11 +23,7 @@ const server_1 = require("./server");
23
23
  const localtunnel_1 = __importDefault(require("localtunnel"));
24
24
  let checkUrl = (s) => (typeof s === "string") && is_url_superb_1.default(s);
25
25
  const ready = (config) => __awaiter(void 0, void 0, void 0, function* () {
26
- if (process.send) {
27
- process.send('ready');
28
- process.send('ready');
29
- process.send('ready');
30
- }
26
+ index_1.processSend('ready');
31
27
  if (config.readyWebhook)
32
28
  yield axios_1.default({
33
29
  method: 'post',
@@ -112,10 +108,17 @@ function start() {
112
108
  client.onLogout(() => __awaiter(this, void 0, void 0, function* () {
113
109
  console.error('!!!! CLIENT LOGGED OUT !!!!');
114
110
  if (cliConfig && !cliConfig.noKillOnLogout) {
111
+ yield client.waitWhQIdle();
115
112
  console.error("Shutting down.");
116
113
  process.exit();
117
114
  }
118
115
  }));
116
+ if (cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.chatwootUrl) {
117
+ spinner.info('Setting Up Chatwoot handler');
118
+ spinner.info('Make sure to set up the Chatwoot inbox webhook to the following path on this process: /chatwoot');
119
+ yield server_1.setupChatwoot(cliConfig, client);
120
+ spinner.succeed('Chatwoot handler set up successfully');
121
+ }
119
122
  if (cliConfig === null || cliConfig === void 0 ? void 0 : cliConfig.botPressUrl) {
120
123
  spinner.info('Setting Up Botpress handler');
121
124
  server_1.setupBotPressHandler(cliConfig, client);
@@ -0,0 +1,6 @@
1
+ import { Client } from '../..';
2
+ import { cliFlags } from '../server';
3
+ import { Request, Response } from "express";
4
+ export declare type expressMiddleware = (req: Request, res: Response) => Promise<Response<any, Record<string, any>>>;
5
+ export declare const chatwootMiddleware: (cliConfig: cliFlags, client: Client) => expressMiddleware;
6
+ export declare const setupChatwootOutgoingMessageHandler: (cliConfig: cliFlags, client: Client) => Promise<void>;
@@ -0,0 +1,234 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ var __importDefault = (this && this.__importDefault) || function (mod) {
12
+ return (mod && mod.__esModule) ? mod : { "default": mod };
13
+ };
14
+ Object.defineProperty(exports, "__esModule", { value: true });
15
+ exports.setupChatwootOutgoingMessageHandler = exports.chatwootMiddleware = void 0;
16
+ const axios_1 = __importDefault(require("axios"));
17
+ const chatwootMiddleware = (cliConfig, client) => {
18
+ return (req, res) => __awaiter(void 0, void 0, void 0, function* () {
19
+ const processMesssage = () => __awaiter(void 0, void 0, void 0, function* () {
20
+ const promises = [];
21
+ const { body } = req;
22
+ const m = body.conversation.messages[0];
23
+ const contact = (body.conversation.meta.sender.phone_number || "").replace('+', '');
24
+ if (body.message_type === "incoming" ||
25
+ body.private ||
26
+ body.event !== "message_created" ||
27
+ !m ||
28
+ !contact)
29
+ return;
30
+ const { attachments, content } = m;
31
+ const to = `${contact}@c.us`;
32
+ if ((attachments === null || attachments === void 0 ? void 0 : attachments.length) > 0) {
33
+ //has attachments
34
+ const [firstAttachment, ...restAttachments] = attachments;
35
+ const sendAttachment = (attachment, c) => __awaiter(void 0, void 0, void 0, function* () { return client.sendImage(to, attachment.data_url, attachment.data_url.substring(attachment.data_url.lastIndexOf('/') + 1), c || '', null, true); });
36
+ //send the text as the caption with the first message only
37
+ promises.push(sendAttachment(firstAttachment, content));
38
+ restAttachments.map(sendAttachment).map(promises.push);
39
+ }
40
+ else {
41
+ //no attachments
42
+ if (!content)
43
+ return;
44
+ /**
45
+ * Check if this is a location message
46
+ */
47
+ const locationMatcher = /@(\-*\d*\.*\d*\,\-*\d*\.*\d*)/g;
48
+ const [possLoc, ...restMessage] = content.split(' ');
49
+ const locArr = possLoc.match(locationMatcher);
50
+ if (locArr) {
51
+ const [lat, lng] = locArr[0].split(',');
52
+ //grab the location message
53
+ const loc = restMessage.join(' ') || '';
54
+ promises.push(client.sendLocation(to, lat, lng, loc));
55
+ }
56
+ else {
57
+ //not a location message
58
+ promises.push(client.sendText(to, content));
59
+ }
60
+ }
61
+ return yield Promise.all(promises);
62
+ });
63
+ try {
64
+ const processAndSendResult = yield processMesssage();
65
+ res.status(200).send(processAndSendResult);
66
+ }
67
+ catch (error) {
68
+ console.log("🚀 ~ file: chatwoot.ts ~ line 62 ~ return ~ error", error);
69
+ res.status(400).send(error);
70
+ }
71
+ return;
72
+ });
73
+ };
74
+ exports.chatwootMiddleware = chatwootMiddleware;
75
+ const setupChatwootOutgoingMessageHandler = (cliConfig, client) => __awaiter(void 0, void 0, void 0, function* () {
76
+ const u = cliConfig.chatwootUrl; //e.g `"localhost:3000/api/v1/accounts/3"
77
+ const api_access_token = cliConfig.chatwootApiAccessToken;
78
+ const _u = new URL(u);
79
+ const origin = _u.origin;
80
+ const port = _u.port || 80;
81
+ const [accountId, inboxId] = u.match(/\/(app|(api\/v1))\/accounts\/\d*\/inbox\/\d*/g)[0].split('/').filter(Number);
82
+ // const accountId = u.match(/accounts\/\d*/g) && u.match(/accounts\/\d*/g)[0].replace('accounts/', '')
83
+ const resolvedInbox = inboxId || u.match(/inboxes\/\d*/g) && u.match(/inboxes\/\d*/g)[0].replace('inboxes/', '');
84
+ const cwReq = (path, method, data) => {
85
+ const url = `${origin}/api/v1/accounts/${accountId}/${path}`.replace('app.bentonow.com', 'chat.bentonow.com');
86
+ console.log(url, method, data);
87
+ return axios_1.default({
88
+ method,
89
+ data,
90
+ url,
91
+ headers: {
92
+ api_access_token
93
+ }
94
+ });
95
+ };
96
+ const contactReg = {
97
+ //WID : chatwoot contact ID
98
+ "example@c.us": "1"
99
+ };
100
+ const convoReg = {
101
+ //WID : chatwoot conversation ID
102
+ "example@c.us": "1"
103
+ };
104
+ const { data: get_inbox } = yield cwReq(`inboxes/${resolvedInbox}`, 'get');
105
+ // const inboxId = `openwa_${sessionId}`
106
+ /**
107
+ * Get the inbox and test it.
108
+ */
109
+ if (!((get_inbox === null || get_inbox === void 0 ? void 0 : get_inbox.webhook_url) || "").includes("/chatwoot"))
110
+ console.log("Please set the chatwoot inbox webhook to this sessions URL with path /chatwoot");
111
+ /**
112
+ * Get Contacts and conversations
113
+ */
114
+ const searchContact = (number) => __awaiter(void 0, void 0, void 0, function* () {
115
+ try {
116
+ const n = number.replace('@c.us', '');
117
+ const { data } = yield cwReq(`contacts/search?q=${n}&sort=phone_number`, 'get');
118
+ if (data.payload.length) {
119
+ return data.payload.find(x => (x.phone_number || "").includes(n)) || false;
120
+ }
121
+ else
122
+ false;
123
+ }
124
+ catch (error) {
125
+ return;
126
+ }
127
+ });
128
+ const getContactConversation = (number) => __awaiter(void 0, void 0, void 0, function* () {
129
+ try {
130
+ const { data } = yield cwReq(`contacts/${contactReg[number]}/conversations`, 'get');
131
+ return data.payload[0];
132
+ }
133
+ catch (error) {
134
+ return;
135
+ }
136
+ });
137
+ const createConversation = (contact_id) => __awaiter(void 0, void 0, void 0, function* () {
138
+ try {
139
+ const { data } = yield cwReq(`conversations`, 'post', {
140
+ contact_id,
141
+ "inbox_id": resolvedInbox
142
+ });
143
+ return data.payload;
144
+ }
145
+ catch (error) {
146
+ return;
147
+ }
148
+ });
149
+ const createContact = (contact) => __awaiter(void 0, void 0, void 0, function* () {
150
+ try {
151
+ const { data } = yield cwReq(`contacts`, 'post', {
152
+ "identifier": contact.id,
153
+ "name": contact.formattedName || contact.id,
154
+ "phone_number": `+${contact.id.replace('@c.us', '')}`,
155
+ "avatar_url": contact.profilePicThumbObj.eurl
156
+ });
157
+ return data.payload.contact;
158
+ }
159
+ catch (error) {
160
+ return;
161
+ }
162
+ });
163
+ const sendConversationMessage = (content, contactId, message) => __awaiter(void 0, void 0, void 0, function* () {
164
+ try {
165
+ const { data } = yield cwReq(`conversations/${convoReg[contactId]}/messages`, 'post', {
166
+ content,
167
+ "message_type": 0,
168
+ "private": false
169
+ });
170
+ return data;
171
+ }
172
+ catch (error) {
173
+ return;
174
+ }
175
+ });
176
+ // const inboxId = s.match(/conversations\/\d*/g) && s.match(/conversations\/\d*/g)[0].replace('conversations/','')
177
+ /**
178
+ * Update the chatwoot contact and conversation registries
179
+ */
180
+ client.onMessage((message) => __awaiter(void 0, void 0, void 0, function* () {
181
+ if (message.from.includes('g')) {
182
+ //chatwoot integration does not support group chats
183
+ return;
184
+ }
185
+ /**
186
+ * Does the contact exist in chatwoot?
187
+ */
188
+ if (!contactReg[message.from]) {
189
+ const contact = yield searchContact(message.from);
190
+ if (contact) {
191
+ contactReg[message.from] = contact.id;
192
+ }
193
+ else {
194
+ //create the contact
195
+ contactReg[message.from] = (yield createContact(message.sender)).id;
196
+ }
197
+ }
198
+ if (!convoReg[message.from]) {
199
+ const conversation = yield getContactConversation(message.from);
200
+ if (conversation) {
201
+ convoReg[message.from] = conversation.id;
202
+ }
203
+ else {
204
+ //create the conversation
205
+ convoReg[message.from] = (yield createConversation(contactReg[message.from])).id;
206
+ }
207
+ }
208
+ /**
209
+ * Does the conversation exist in
210
+ */
211
+ let text = message.body;
212
+ switch (message.type) {
213
+ case 'location':
214
+ text = `${message.lat},${message.lng}`;
215
+ break;
216
+ case 'buttons_response':
217
+ text = message.selectedButtonId;
218
+ break;
219
+ case 'document':
220
+ case 'image':
221
+ case 'audio':
222
+ case 'ptt':
223
+ case 'video':
224
+ if (message.cloudUrl)
225
+ text = `FILE:\t${message.cloudUrl}\n\nMESSAGE:\t${message.text}`;
226
+ break;
227
+ default:
228
+ text = message.body || "__UNHANDLED__";
229
+ break;
230
+ }
231
+ yield sendConversationMessage(text, message.from, message);
232
+ }));
233
+ });
234
+ exports.setupChatwootOutgoingMessageHandler = setupChatwootOutgoingMessageHandler;
@@ -16,5 +16,6 @@ export declare const getCommands: () => any;
16
16
  export declare const listListeners: () => string[];
17
17
  export declare const setupMediaMiddleware: () => void;
18
18
  export declare const setupTwilioCompatibleWebhook: (cliConfig: cliFlags, client: Client) => void;
19
+ export declare const setupChatwoot: (cliConfig: cliFlags, client: Client) => void;
19
20
  export declare const setupBotPressHandler: (cliConfig: cliFlags, client: Client) => void;
20
21
  export declare const setupSocketServer: (cliConfig: any, client: Client) => Promise<void>;
@@ -31,7 +31,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
31
31
  return (mod && mod.__esModule) ? mod : { "default": mod };
32
32
  };
33
33
  Object.defineProperty(exports, "__esModule", { value: true });
34
- exports.setupSocketServer = exports.setupBotPressHandler = exports.setupTwilioCompatibleWebhook = exports.setupMediaMiddleware = exports.listListeners = exports.getCommands = exports.setupRefocusDisengageMiddleware = exports.setupSwaggerStatsMiddleware = exports.setupApiDocs = exports.setupAuthenticationLayer = exports.enableCORSRequests = exports.setUpExpressApp = exports.server = exports.app = void 0;
34
+ exports.setupSocketServer = exports.setupBotPressHandler = exports.setupChatwoot = exports.setupTwilioCompatibleWebhook = exports.setupMediaMiddleware = exports.listListeners = exports.getCommands = exports.setupRefocusDisengageMiddleware = exports.setupSwaggerStatsMiddleware = exports.setupApiDocs = exports.setupAuthenticationLayer = exports.enableCORSRequests = exports.setUpExpressApp = exports.server = exports.app = void 0;
35
35
  //@ts-ignore
36
36
  const express_1 = __importDefault(require("express"));
37
37
  const http_1 = __importDefault(require("http"));
@@ -43,6 +43,7 @@ const parse_function_1 = __importDefault(require("parse-function"));
43
43
  const __1 = require("..");
44
44
  const qs_1 = __importDefault(require("qs"));
45
45
  const xmlbuilder2_1 = require("xmlbuilder2");
46
+ const chatwoot_1 = require("./integrations/chatwoot");
46
47
  exports.app = express_1.default();
47
48
  exports.server = http_1.default.createServer(exports.app);
48
49
  const trimChatId = (chatId) => chatId.replace("@c.us", "").replace("@g.us", "");
@@ -233,6 +234,11 @@ const setupTwilioCompatibleWebhook = (cliConfig, client) => {
233
234
  }));
234
235
  };
235
236
  exports.setupTwilioCompatibleWebhook = setupTwilioCompatibleWebhook;
237
+ const setupChatwoot = (cliConfig, client) => __awaiter(void 0, void 0, void 0, function* () {
238
+ exports.app.post('/chatwoot', chatwoot_1.chatwootMiddleware(cliConfig, client));
239
+ yield chatwoot_1.setupChatwootOutgoingMessageHandler(cliConfig, client);
240
+ });
241
+ exports.setupChatwoot = setupChatwoot;
236
242
  const setupBotPressHandler = (cliConfig, client) => {
237
243
  const u = cliConfig.botPressUrl;
238
244
  const sendBotPressMessage = (text, chatId, message) => __awaiter(void 0, void 0, void 0, function* () {
package/dist/cli/setup.js CHANGED
@@ -63,6 +63,16 @@ const optionList = [{
63
63
  type: String,
64
64
  typeLabel: '{blue {underline http://localhost:5555/incoming}}',
65
65
  description: "Send twillio payloads to this URL. EASY API will also parse and processes twillio response message payloads."
66
+ }, {
67
+ name: 'chatwoot-url',
68
+ type: String,
69
+ typeLabel: '{blue {underline http://localhost:3000/api/v1/accounts/3/inboxes/1}}',
70
+ description: "The URL of the specific Chatwoot inbox you set up for this session"
71
+ }, {
72
+ name: 'chatwoot-api-access-token',
73
+ type: String,
74
+ typeLabel: '{blue {underline mEEwUGEEML2ZThMm252rLg1M}}',
75
+ description: "The access token of the specific Chatwoot inbox you set up for this session"
66
76
  },
67
77
  {
68
78
  name: 'port',
@@ -48,7 +48,11 @@ const puppeteerConfig = {
48
48
  // '--no-zygote',
49
49
  // '--renderer-process-limit=1',
50
50
  // '--no-first-run'
51
- '--disable-gl-drawing-for-tests'
51
+ '--disable-gl-drawing-for-tests',
52
+ //keep awake in all situations
53
+ '--disable-background-timer-throttling',
54
+ '--disable-backgrounding-occluded-windows',
55
+ '--disable-renderer-backgrounding'
52
56
  ]
53
57
  };
54
58
  exports.puppeteerConfig = puppeteerConfig;
@@ -33,6 +33,7 @@ const qrcode = __importStar(require("qrcode-terminal"));
33
33
  const rxjs_1 = require("rxjs");
34
34
  const events_1 = require("./events");
35
35
  const initializer_1 = require("./initializer");
36
+ const tools_1 = require("../utils/tools");
36
37
  const timeout = ms => new Promise(resolve => setTimeout(resolve, ms, 'timeout'));
37
38
  /**
38
39
  * Validates if client is authenticated
@@ -102,18 +103,21 @@ function smartQr(waPage, config, spinner) {
102
103
  if (isAuthed)
103
104
  return true;
104
105
  const grabAndEmit = (qrData) => __awaiter(this, void 0, void 0, function* () {
106
+ if (qrData) {
107
+ if (!config.qrLogSkip)
108
+ qrcode.generate(qrData, { small: true });
109
+ else
110
+ console.log(`New QR Code generated. Not printing in console because qrLogSkip is set to true`);
111
+ }
105
112
  try {
106
- const qrCode = yield waPage.evaluate(`window.getQrPng()`);
107
- if (qrCode) {
108
- qrEv.emit(qrCode);
109
- if (!config.qrLogSkip)
110
- qrcode.generate(qrData, { small: true });
111
- else
112
- console.log(`New QR Code generated. Not printing in console because qrLogSkip is set to true`);
113
+ const qrPng = yield waPage.evaluate(`window.getQrPng()`);
114
+ if (qrPng) {
115
+ qrEv.emit(qrPng);
113
116
  }
114
117
  else {
115
118
  spinner.info("Something went wrong while retreiving new the QR code but it should not affect the session launch procedure.");
116
119
  }
120
+ tools_1.processSend('QR');
117
121
  }
118
122
  catch (error) {
119
123
  //@ts-ignore
@@ -122,7 +126,7 @@ function smartQr(waPage, config, spinner) {
122
126
  }
123
127
  });
124
128
  const qrEv = new events_1.EvEmitter(config.sessionId || 'session', 'qr');
125
- const _hasDefaultStateYet = yield waPage.evaluate("window.Store && window.Store.State && window.Store.State.default");
129
+ const _hasDefaultStateYet = yield waPage.evaluate("!!(window.Store && window.Store.State && window.Store.State.Socket)");
126
130
  if (!_hasDefaultStateYet) {
127
131
  //expecting issue, take a screenshot then wait a few seconds before continuing
128
132
  yield timeout(2000);