Skip to content
Back to search

nexscope-ecommerce-skills

127 portable ecommerce skills for marketplace research, product discovery, keyword analysis, trends, sourcing, patent screening, multimodal tasks, and GEO workflows.

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 11 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/nexscope-ai/nexscope-ecommerce-skills with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/nexscope-ai/nexscope-ecommerce-skills'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/nexscope-ai--nexscope-ecommerce-skills/badge.svg)](/listings/nexscope-ai--nexscope-ecommerce-skills)

HTML

<a href="/listings/nexscope-ai--nexscope-ecommerce-skills"><img src="/api/listings/nexscope-ai--nexscope-ecommerce-skills/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

1. Clone the collection

git clone https://github.com/nexscope-ai/nexscope-ecommerce-skills.git
cd nexscope-ecommerce-skills

2. Install the skills you need

Preview every available skill with the Skills CLI:

npx skills add nexscope-ai/nexscope-ecommerce-skills --list

Install one skill:

npx skills add nexscope-ai/nexscope-ecommerce-skills --skill ecommerce-amazon-search

Each top-level `ecommerce-*` directory is an individual skill package. You can also copy a complete directory into the skills location used by your assistant. Keep its `SKILL.md`, scripts, references, assets, and manifest files together.

Example:

cp -R ecommerce-amazon-search <your-agent-skills-directory>/

You can also install the whole collection if your agent supports loading multiple skill directories from one repository. See the [external skills setup guide](https://www.nexscope.ai/help/skills-external-access?co-from=githubNS) for agent-specific instructions.

> **Naming update:** Earlier clones used dotted names such as `ecommerce.amazon-search`. Current Agent Skills-compatible names use hyphens, such as `ecommerce-amazon-search`. Replace old dotted directories instead of keeping both copies.

3. Configure API access

Most API-backed skills require these environment variables:

export NEXSCOPE_PROXY_BASE=https://api.nexscope.ai/
export NEXSCOPE_API_KEY=<your_api_key>

Get or manage an API key on the [Nexscope API Keys page](https://www.nexscope.ai/seller/api-access?co-from=githubNS). API calls may consume credits; check the selected skill's `SKILL.md` before running additional queries or retries.

4. Ask naturally

Examples:

> "Search Amazon US for wireless earbuds and show the current organic and sponsored results."

> "Find TikTok Shop beauty products with strong 30-day sales and at least a 10% commission rate."

> "Show Ozon products for this seller and summarize their pricing and sales metrics."

> "Search 1688 for visually similar suppliers using this product image."

> "Check this product image for similar design patents."

> "Score this product page for SEO and GEO readiness."

> "Evaluate whether AI search engines mention and recommend this product."

---

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md · README · 355 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

This file has changed since it was scanned, so this is not exactly the text that was scanned, and no line is marked. The findings are listed with the safety scan above.

  1. ![E-commerce Skills Banner](./banner.png)
  2. <div align="center">
  3. # E-commerce Skills by Nexscope
  4. **141 portable skills for ecommerce research, marketplace intelligence, product discovery, keyword analysis, trend research, sourcing, patent and trademark screening, multimodal tasks, and GEO workflows.**
  5. [![Skills](https://img.shields.io/badge/skills-141-2563eb)](#all-141-skills)
  6. [![skills.sh](https://skills.sh/b/nexscope-ai/nexscope-ecommerce-skills)](#quick-start)
  7. [![License: Proprietary](https://img.shields.io/badge/license-proprietary-lightgrey)](#license)
  8. For Amazon, TikTok Shop, Ozon, 1688, Shopify, Temu, Walmart, Shopee, Etsy, eBay, and more.
  9. </div>
  10. ---
  11. ## Quick Start
  12. ### 1. Clone the collection
  13. ```bash
  14. git clone https://github.com/nexscope-ai/nexscope-ecommerce-skills.git
  15. cd nexscope-ecommerce-skills
  16. ```
  17. ### 2. Install the skills you need
  18. Preview every available skill with the Skills CLI:
  19. ```bash
  20. npx skills add nexscope-ai/nexscope-ecommerce-skills --list
  21. ```
  22. Install one skill:
  23. ```bash
  24. npx skills add nexscope-ai/nexscope-ecommerce-skills --skill ecommerce-amazon-search
  25. ```
  26. Each top-level `ecommerce-*` directory is an individual skill package. You can also copy a complete directory into the skills location used by your assistant. Keep its `SKILL.md`, scripts, references, assets, and manifest files together.
  27. Example:
  28. ```bash
  29. cp -R ecommerce-amazon-search <your-agent-skills-directory>/
  30. ```
  31. You can also install the whole collection if your agent supports loading multiple skill directories from one repository. See the [external skills setup guide](https://www.nexscope.ai/help/skills-external-access?co-from=githubNS) for agent-specific instructions.
  32. > **Naming update:** Earlier clones used dotted names such as `ecommerce.amazon-search`. Current Agent Skills-compatible names use hyphens, such as `ecommerce-amazon-search`. Replace old dotted directories instead of keeping both copies.
  33. ### 3. Configure API access
  34. Most API-backed skills require these environment variables:
  35. ```bash
  36. export NEXSCOPE_PROXY_BASE=https://api.nexscope.ai/
  37. export NEXSCOPE_API_KEY=<your_api_key>
  38. ```
  39. Get or manage an API key on the [Nexscope API Keys page](https://www.nexscope.ai/seller/api-access?co-from=githubNS). API calls may consume credits; check the selected skill's `SKILL.md` before running additional queries or retries.
  40. ### 4. Ask naturally
  41. Examples:
  42. > "Search Amazon US for wireless earbuds and show the current organic and sponsored results."
  43. > "Find TikTok Shop beauty products with strong 30-day sales and at least a 10% commission rate."
  44. > "Show Ozon products for this seller and summarize their pricing and sales metrics."
  45. > "Search 1688 for visually similar suppliers using this product image."
  46. > "Check this product image for similar design patents."
  47. > "Score this product page for SEO and GEO readiness."
  48. > "Evaluate whether AI search engines mention and recommend this product."
  49. ---
  50. ## Collection at a Glance
  51. | Category | Skills |
  52. |---|---:|
  53. | Amazon Intelligence | 42 |
  54. | TikTok Shop Intelligence | 23 |
  55. | Ozon Intelligence | 13 |
  56. | Patent, Trademark & Compliance | 25 |
  57. | 1688 Sourcing | 5 |
  58. | Other Marketplaces & Storefronts | 23 |
  59. | Web, Trends, Multimodal & GEO | 10 |
  60. | **Total** | **141** |
  61. ---
  62. ## All 141 Skills
  63. ### Amazon Intelligence (42)
  64. | Skill | What it does |
  65. |---|---|
  66. | [`amazon-ads-sp-insights-report`](./ecommerce-amazon-ads-sp-insights-report/) | Create, poll, and download Sponsored Products audience and search-term impression-share reports using an authorized Amazon Ads connection. |
  67. | [`amazon-ads-api-access`](./ecommerce-amazon-ads-api-access/) | Authorize Amazon Ads accounts and inspect connection and profile metadata. |
  68. | [`amazon-ads-reporting-api`](./ecommerce-amazon-ads-reporting-api/) | Create, poll, resume, download, and save Amazon Ads v3 reports. |
  69. | [`amazon-advertising-api`](./ecommerce-amazon-advertising-api/) | Authorize Amazon Ads accounts, manage SP, SB, and SD entities, and retrieve reports. |
  70. | [`amazon-ads-manager`](./ecommerce-amazon-ads-manager/) | Read and mutate SP, SB, and SD campaigns, ad groups, ads, targeting, and budget rules. |
  71. | [`amazon-alexa-search`](./ecommerce-amazon-alexa-search/) | Search Amazon Alexa shopping results. |
  72. | [`amazon-asin-keywords`](./ecommerce-amazon-asin-keywords/) | Retrieve keywords associated with an Amazon ASIN. |
  73. | [`amazon-asin-traffic-summary`](./ecommerce-amazon-asin-traffic-summary/) | Retrieve an Amazon ASIN traffic summary. |
  74. | [`amazon-broad-product-search`](./ecommerce-amazon-broad-product-search/) | Search broadly for Amazon products. |
  75. | [`amazon-category-lookup`](./ecommerce-amazon-category-lookup/) | Browse Amazon category nodes by parent identifier or search category metadata by name. |
  76. | [`amazon-competitor-lookup`](./ecommerce-amazon-competitor-lookup/) | Look up competing Amazon products. |
  77. | [`amazon-keyword-expansion`](./ecommerce-amazon-keyword-expansion/) | Expand an Amazon keyword. |
  78. | [`amazon-keyword-intelligence`](./ecommerce-amazon-keyword-intelligence/) | Query Amazon keyword intelligence data. |
  79. | [`amazon-keyword-overview`](./ecommerce-amazon-keyword-overview/) | Retrieve an overview for an Amazon keyword. |
  80. | [`amazon-keyword-search-history`](./ecommerce-amazon-keyword-search-history/) | Retrieve historical Amazon keyword search volume. |
  81. | [`amazon-keyword-share-of-voice`](./ecommerce-amazon-keyword-share-of-voice/) | Retrieve Amazon keyword share of voice. |
  82. | [`amazon-keyword-summary`](./ecommerce-amazon-keyword-summary/) | Retrieve a summary for an Amazon keyword. |
  83. | [`amazon-market-product-detail`](./ecommerce-amazon-market-product-detail/) | Retrieve Amazon marketplace product details. |
  84. | [`amazon-market-product-search`](./ecommerce-amazon-market-product-search/) | Search for products in the Amazon marketplace. |
  85. | [`amazon-market-research`](./ecommerce-amazon-market-research/) | Research an Amazon market. |
  86. | [`amazon-market-statistics`](./ecommerce-amazon-market-statistics/) | Analyze Amazon market statistics. |
  87. | [`amazon-niche-info`](./ecommerce-amazon-niche-info/) | Retrieve Amazon niche information. |
  88. | [`amazon-niche-info-by-asin`](./ecommerce-amazon-niche-info-by-asin/) | Retrieve Amazon niche information by ASIN. |
  89. | [`amazon-niche-info-by-keyword`](./ecommerce-amazon-niche-info-by-keyword/) | Retrieve Amazon niche information by keyword. |
  90. | [`amazon-niche-reviews-by-keyword`](./ecommerce-amazon-niche-reviews-by-keyword/) | Retrieve Amazon niche reviews by keyword. |
  91. | [`amazon-opportunity-report-by-keyword`](./ecommerce-amazon-opportunity-report-by-keyword/) | Retrieve Amazon opportunity reports by keyword. |
  92. | [`amazon-opportunity-search-by-metrics`](./ecommerce-amazon-opportunity-search-by-metrics/) | Search Amazon opportunities by metrics. |
  93. | [`amazon-policy-feed`](./ecommerce-amazon-policy-feed/) | Retrieve marketplace policy updates and full article details. |
  94. | [`amazon-product-database`](./ecommerce-amazon-product-database/) | Query the Amazon product database. |
  95. | [`amazon-product-database-search`](./ecommerce-amazon-product-database-search/) | Search the Amazon product database. |
  96. | [`amazon-product-detail`](./ecommerce-amazon-product-detail/) | Retrieve Amazon product details. |
  97. | [`amazon-product-discovery`](./ecommerce-amazon-product-discovery/) | Discover Amazon products. |
  98. | [`amazon-product-history`](./ecommerce-amazon-product-history/) | Retrieve Amazon product history and product details. |
  99. | [`amazon-product-price-series`](./ecommerce-amazon-product-price-series/) | Retrieve Amazon product price and metric series. |
  100. | [`amazon-product-research-api`](./ecommerce-amazon-product-research-api/) | Route Amazon product research across market, keyword, competitor, trend, review, and profitability capabilities. |
  101. | [`amazon-related-asins`](./ecommerce-amazon-related-asins/) | Retrieve Amazon ASINs related to an ASIN. |
  102. | [`amazon-reviews-list`](./ecommerce-amazon-reviews-list/) | Retrieve Amazon product reviews. |
  103. | [`amazon-sales-estimates`](./ecommerce-amazon-sales-estimates/) | Estimate historical daily sales for an Amazon product. |
  104. | [`amazon-traffic-gap-analyst`](./ecommerce-amazon-traffic-gap-analyst/) | Analyze variant-aware traffic gaps with evidence-linked local HTML reports. |
  105. | [`amazon-search`](./ecommerce-amazon-search/) | Search Amazon products. |
  106. | [`amazon-search-by-image`](./ecommerce-amazon-search-by-image/) | Search for visually similar products on Amazon using an image across eight marketplaces. |
  107. | [`amazon-traffic-keywords`](./ecommerce-amazon-traffic-keywords/) | Research Amazon traffic keywords. |
  108. ### TikTok Shop Intelligence (23)
  109. | Skill | What it does |
  110. |---|---|
  111. | [`chuhaijiang-tiktok-product`](./ecommerce-chuhaijiang-tiktok-product/) | Search TikTok products and inspect details, trends, creators, videos, and related commerce data. |
  112. | [`chuhaijiang-tiktok-shop`](./ecommerce-chuhaijiang-tiktok-shop/) | Search TikTok shops and inspect shop details, rankings, products, creators, and videos. |
  113. | [`chuhaijiang-tiktok-creator`](./ecommerce-chuhaijiang-tiktok-creator/) | Search TikTok creators and inspect profiles, rankings, products, videos, and live streams. |
  114. | [`chuhaijiang-tiktok-live`](./ecommerce-chuhaijiang-tiktok-live/) | Inspect TikTok live streams, rankings, and related products. |
  115. | [`chuhaijiang-tiktok-video`](./ecommerce-chuhaijiang-tiktok-video/) | Search TikTok videos and inspect details, rankings, and related products. |
  116. | [`chuhaijiang-tiktok-ads`](./ecommerce-chuhaijiang-tiktok-ads/) | Search TikTok ads and creatives and inspect details and related products. |
  117. | [`tiktok-batch-product-detail`](./ecommerce-tiktok-batch-product-detail/) | Retrieve batch TikTok product details. |
  118. | [`tiktok-creator-analytics`](./ecommerce-tiktok-creator-analytics/) | Retrieve TikTok creator rankings and creator-level analytics. |
  119. | [`tiktok-creator-search-api`](./ecommerce-tiktok-creator-search-api/) | Search TikTok ecommerce creator rankings by market and date range. |
  120. | [`tiktok-livestream-analytics`](./ecommerce-tiktok-livestream-analytics/) | Retrieve TikTok livestream rankings and livestream details. |
  121. | [`tiktok-new-product-rank`](./ecommerce-tiktok-new-product-rank/) | Retrieve TikTok new-product rankings. |
  122. | [`tiktok-product-analytics`](./ecommerce-tiktok-product-analytics/) | Retrieve TikTok product rankings and product details. |
  123. | [`tiktok-product-analytics-api`](./ecommerce-tiktok-product-analytics-api/) | Retrieve price, sales, revenue, commission, lifecycle, and shop data for a TikTok product. |
  124. | [`tiktok-product-discovery`](./ecommerce-tiktok-product-discovery/) | Discover TikTok products. |
  125. | [`tiktok-product-search`](./ecommerce-tiktok-product-search/) | Search TikTok products. |
  126. | [`tiktok-seller-detail`](./ecommerce-tiktok-seller-detail/) | Get detailed metrics and attributes for one TikTok Shop seller. |
  127. | [`tiktok-shop-analytics`](./ecommerce-tiktok-shop-analytics/) | Retrieve TikTok shop rankings and shop details. |
  128. | [`tiktok-shop-product-detail`](./ecommerce-tiktok-shop-product-detail/) | Retrieve TikTok Shop product details by product ID or URL. |
  129. | [`tiktok-top-selling-products`](./ecommerce-tiktok-top-selling-products/) | Retrieve TikTok Shop top-selling product rankings. |
  130. | [`tiktok-video-analytics`](./ecommerce-tiktok-video-analytics/) | Retrieve TikTok video rankings and video details. |
  131. | [`tiktok-video-download-url`](./ecommerce-tiktok-video-download-url/) | Retrieve a TikTok video download URL. |
  132. | [`tiktok-video-rank`](./ecommerce-tiktok-video-rank/) | Retrieve ranked TikTok videos by market, date, and ranking metric. |
  133. | [`tiktok-video-search`](./ecommerce-tiktok-video-search/) | Search TikTok videos by market, creator, product, engagement, and publication filters. |
  134. ### Ozon Intelligence (13)
  135. | Skill | What it does |
  136. |---|---|
  137. | [`ozon-brand-products`](./ecommerce-ozon-brand-products/) | Retrieve Ozon products for a brand. |
  138. | [`ozon-category-products`](./ecommerce-ozon-category-products/) | Retrieve Ozon products for a category. |
  139. | [`ozon-category-search`](./ecommerce-ozon-category-search/) | Search Ozon category products. |
  140. | [`ozon-keyword-back-search`](./ecommerce-ozon-keyword-back-search/) | Find Ozon keywords associated with product SKUs. |
  141. | [`ozon-keyword-mining`](./ecommerce-ozon-keyword-mining/) | Mine related Ozon search keywords. |
  142. | [`ozon-market-keyword-search`](./ecommerce-ozon-market-keyword-search/) | Search Ozon marketplace keyword metrics. |
  143. | [`ozon-product-detail`](./ecommerce-ozon-product-detail/) | Retrieve Ozon product details for one SKU per call. |
  144. | [`ozon-product-detail-search`](./ecommerce-ozon-product-detail-search/) | Retrieve Ozon product detail history. |
  145. | [`ozon-product-report-search`](./ecommerce-ozon-product-report-search/) | Search Ozon product reports. |
  146. | [`ozon-product-search`](./ecommerce-ozon-product-search/) | Search Ozon products by keyword or product ID. |
  147. | [`ozon-product-trend`](./ecommerce-ozon-product-trend/) | Retrieve daily Ozon product trends. |
  148. | [`ozon-seller-products`](./ecommerce-ozon-seller-products/) | Retrieve Ozon products for a seller. |
  149. | [`ozon-shop-search`](./ecommerce-ozon-shop-search/) | Search Ozon shops and seller metrics. |
  150. ### Patent, Trademark & Compliance (25)
  151. | Skill | What it does |
  152. |---|---|
  153. | [`design-similarity-search`](./ecommerce-design-similarity-search/) | Find visually similar design-patent candidates from a product image using SIF. |
  154. | [`google-patent-search`](./ecommerce-google-patent-search/) | Search Google Patents by keyword and filters. |
  155. | [`maidalv-product-tro-detection`](./ecommerce-maidalv-product-tro-detection/) | Assess product imagery for TRO, trademark, patent, and copyright infringement risk. |
  156. | [`patent-abstract-image-data`](./ecommerce-patent-abstract-image-data/) | Retrieve patent abstract image data. |
  157. | [`patent-cited-by`](./ecommerce-patent-cited-by/) | Retrieve patents that cite a specified patent. |
  158. | [`patent-claims`](./ecommerce-patent-claims/) | Retrieve original patent claims and claim counts. |
  159. | [`patent-claims-translation`](./ecommerce-patent-claims-translation/) | Retrieve translated patent claims. |
  160. | [`patent-core-bibliography`](./ecommerce-patent-core-bibliography/) | Retrieve core patent bibliography data. |
  161. | [`patent-description-data`](./ecommerce-patent-description-data/) | Retrieve original patent description data. |
  162. | [`patent-description-data-translation`](./ecommerce-patent-description-data-translation/) | Retrieve translated patent description data. |
  163. | [`patent-detailed-bibliography`](./ecommerce-patent-detailed-bibliography/) | Retrieve detailed patent bibliography data. |
  164. | [`patent-fulltext-images`](./ecommerce-patent-fulltext-images/) | Retrieve patent full-text image data. |
  165. | [`patent-family-data`](./ecommerce-patent-family-data/) | Retrieve patent family data. |
  166. | [`patent-legal-status-data`](./ecommerce-patent-legal-status-data/) | Retrieve patent legal status data. |
  167. | [`patent-references`](./ecommerce-patent-references/) | Retrieve references cited by a patent. |
  168. | [`patent-search-api`](./ecommerce-patent-search-api/) | Search patents with Analytics query expressions and return matching patent identifiers and publication numbers. |
  169. | [`patent-title-abstract-translation`](./ecommerce-patent-title-abstract-translation/) | Retrieve translated patent titles and abstracts. |
  170. | [`ruiguan-copyright-detection`](./ecommerce-ruiguan-copyright-detection/) | Detect image copyright infringement risks by comparing against a database of registered copyrighted works. |
  171. | [`ruiguan-detection-patent-design`](./ecommerce-ruiguan-detection-patent-design/) | Detect design patent infringement risks by comparing a product image against a global design patent database across more than 25 jurisdictions. |
  172. | [`ruiguan-gun-parts-search`](./ecommerce-ruiguan-gun-parts-search/) | Check product images against a database of policy-violating items using visual similarity. |
  173. | [`ruiguan-trademark-graphic-detection`](./ecommerce-ruiguan-trademark-graphic-detection/) | Detect graphic trademarks in product images by comparing against registered trademark databases across multiple regions. |
  174. | [`text-trademark-detector`](./ecommerce-text-trademark-detector/) | Detect trademark risks in product titles and text. |
  175. | [`utility-patent-detector`](./ecommerce-utility-patent-detector/) | Check products for utility patent similarity. |
  176. | [`zhihuiya-patent-image-search`](./ecommerce-zhihuiya-patent-image-search/) | Search for visually similar design patents using an image, with country, legal status, and date filters. |
  177. | [`zhihuiya-utility-patent-image-search`](./ecommerce-zhihuiya-utility-patent-image-search/) | Search for visually similar utility model patents using an image, with country, legal status, and date filters. |
  178. These skills support research and screening workflows. Their results are not legal advice and do not replace review by a qualified intellectual property professional.
  179. ### 1688 Sourcing (5)
  180. | Skill | What it does |
  181. |---|---|
  182. | [`1688-procurement`](./ecommerce-1688-procurement/) | Authorize your own 1688 buyer account and manage addresses, SKUs, order previews, confirmed orders, payments, logistics and invoices across 14 operations. |
  183. | [`1688-product-detail`](./ecommerce-1688-product-detail/) | Retrieve 1688 product details by offer ID. |
  184. | [`1688-product-billboard`](./ecommerce-1688-product-billboard/) | Retrieve 1688 bestseller ranking data. |
  185. | [`1688-product-search`](./ecommerce-1688-product-search/) | Search 1688 products with sourcing and sales filters. |
  186. | [`1688-search-by-image`](./ecommerce-1688-search-by-image/) | Search for visually similar products on 1688 using an image. |
  187. ### Other Marketplaces & Storefronts (23)
  188. | Skill | What it does |
  189. |---|---|
  190. | [`ebay-search`](./ecommerce-ebay-search/) | Search eBay products and completed listings. The upstream sold-only filter is unavailable; completed listings are not verified sales. |
  191. | [`etsy-category-search`](./ecommerce-etsy-category-search/) | Search Etsy marketplace categories. |
  192. | [`etsy-product-detail`](./ecommerce-etsy-product-detail/) | Retrieve Etsy product details from a listing URL. |
  193. | [`etsy-product-query`](./ecommerce-etsy-product-query/) | Query Etsy product listings and performance data. |
  194. | [`etsy-store-query`](./ecommerce-etsy-store-query/) | Query Etsy stores and performance data. |
  195. | [`mercado-market-intelligence`](./ecommerce-mercado-market-intelligence/) | Research Mercado Libre categories, products, trends, sellers, and reviews. |
  196. | [`mercado-product-selection`](./ecommerce-mercado-product-selection/) | Research Mercado Libre products, catalogs, keywords, categories, trends, sellers, and reviews. |
  197. | [`shopee-product-detail`](./ecommerce-shopee-product-detail/) | Retrieve Shopee product details from a product URL. |
  198. | [`shopee-product-search`](./ecommerce-shopee-product-search/) | Search Shopee product information and metrics. |
  199. | [`shopify-product-query`](./ecommerce-shopify-product-query/) | Query Shopify products with filters. |
  200. | [`shopify-store-query`](./ecommerce-shopify-store-query/) | Query Shopify stores with filters. |
  201. | [`geekbi-temu-market-research`](./ecommerce-geekbi-temu-market-research/) | Inspect Temu market trends, category opportunities, and sales distributions. |
  202. | [`geekbi-temu-product`](./ecommerce-geekbi-temu-product/) | Search Temu products and inspect product details and recent history. |
  203. | [`geekbi-temu-search-by-image`](./ecommerce-geekbi-temu-search-by-image/) | Find visually similar Temu products using the supported temporary image upload workflow. |
  204. | [`geekbi-temu-shop`](./ecommerce-geekbi-temu-shop/) | Search Temu shops and inspect shop details and recent performance. |
  205. | [`temu-category-search`](./ecommerce-temu-category-search/) | Search Temu categories. |
  206. | [`temu-product-source-query`](./ecommerce-temu-product-source-query/) | Query Temu products for sourcing research. |
  207. | [`temu-store-source-query`](./ecommerce-temu-store-source-query/) | Query Temu stores for sourcing research. |
  208. | [`walmart-category-market`](./ecommerce-walmart-category-market/) | Analyze Walmart category market data. |
  209. | [`walmart-keyword-research`](./ecommerce-walmart-keyword-research/) | Research Walmart keyword demand and competition. |
  210. | [`walmart-product-analysis`](./ecommerce-walmart-product-analysis/) | Analyze Walmart product performance and details. |
  211. | [`walmart-product-detail`](./ecommerce-walmart-product-detail/) | Retrieve Walmart product details. |
  212. | [`walmart-search`](./ecommerce-walmart-search/) | Search Walmart products. |
  213. ### Web, Trends, Multimodal & GEO (10)
  214. | Skill | What it does |
  215. |---|---|
  216. | [`geo-score-check`](./ecommerce-geo-score-check/) | Score an ecommerce URL for SEO and GEO readiness from crawlable evidence. |
  217. | [`google-ai-mode-search`](./ecommerce-google-ai-mode-search/) | Search Google AI Mode results. |
  218. | [`google-trends-by-keywords`](./ecommerce-google-trends-by-keywords/) | Retrieve Google Trends data for keywords. |
  219. | [`google-trends-by-time`](./ecommerce-google-trends-by-time/) | Retrieve Google Trends data by time range. |
  220. | [`multimodal-generate-image`](./ecommerce-multimodal-generate-image/) | Generate and edit images from text prompts and optional reference images. |
  221. | [`multimodal-recognize-image`](./ecommerce-multimodal-recognize-image/) | Analyze images and extract information with multimodal AI recognition. |
  222. | [`product-ai-visibility`](./ecommerce-product-ai-visibility/) | Evaluate product mentions and recommendation positions across AI search engines. |
  223. | [`product-description-generator-api`](./ecommerce-product-description-generator-api/) | Generate ecommerce descriptions and other text asynchronously, and retrieve task results. |
  224. | [`reverse-product-image-search-api`](./ecommerce-reverse-product-image-search-api/) | Find visual or keyword-derived competitors from a product image or URL. |
  225. | [`web-search`](./ecommerce-web-search/) | Search the web for a keyword. |
  226. ---
  227. ## How Each Skill Works
  228. Start with the selected directory's `SKILL.md`. It defines:
  229. - when the skill should trigger;
  230. - required and optional inputs;
  231. - supported marketplaces, filters, and limits;
  232. - the API endpoint or local workflow;
  233. - safe handling for credits, retries, missing data, and errors;
  234. - the expected output format.
  235. Most API-backed packages also include:
  236. ```text
  237. ecommerce-example-skill/
  238. ├── SKILL.md
  239. ├── manifest.json
  240. ├── references/
  241. │ └── api.md
  242. └── scripts/
  243. └── example_skill.py
  244. ```
  245. Do not copy only `SKILL.md` when a package contains scripts, references, assets, configuration, or manifest files.
  246. ---
  247. ## Usage Notes
  248. - **Evidence first:** Results depend on the data returned for the exact marketplace, keyword, product, seller, date range, and filters used.
  249. - **No automatic extra spend:** Many API-backed skills instruct the agent not to retry with changed parameters or fetch additional pages without approval.
  250. - **Marketplace differences:** Supported countries, domains, languages, currencies, and available fields vary by skill.
  251. - **Image workflows:** Image-search and image-analysis skills may require an accessible image URL or the included upload helper.
  252. - **Readiness is not visibility:** `ecommerce-geo-score-check` evaluates crawlable SEO/GEO readiness. It does not measure live AI mentions.
  253. - **Time-bound AI results:** `ecommerce-product-ai-visibility` evaluates current AI responses; results can change as models and source content change.
  254. ---
  255. ## Troubleshooting
  256. ### Missing credentials
  257. ```text
  258. NEXSCOPE_PROXY_BASE and NEXSCOPE_API_KEY are required
  259. ```
  260. Set both environment variables in the same shell or runtime that launches the skill.
  261. ### Authentication or credit errors
  262. Confirm that the API key is valid and that the account has enough credits for the requested call. Manage access on the [Nexscope API Keys page](https://www.nexscope.ai/seller/api-access?co-from=githubNS).
  263. ### Skill not detected
  264. - Copy the complete `ecommerce-*` directory into the correct skills location.
  265. - Keep the folder name unchanged.
  266. - Restart or reload the agent if it discovers skills only at startup.
  267. - Read the agent-specific [setup guide](https://www.nexscope.ai/help/skills-external-access?co-from=githubNS).
  268. ### Request or response details
  269. Read the selected skill's `references/api.md` and script usage section. Parameters and supported marketplaces differ between skills.
  270. ---
  271. ## License
  272. These skills are proprietary software owned by Nexscope. API-backed usage requires valid Nexscope access and may consume credits.
  273. © 2026 Nexscope AI
  274. ---
  275. Built by **[Nexscope](https://www.nexscope.ai/?co-from=githubNS)** — an ecommerce data and creative platform for marketplace research, online image and video generation, and developer integrations.
ecommerce-amazon-product-research-api/scripts/onboarding.py · Bundled script · 598 lines · 1 finding marked
  1. #!/usr/bin/env python3
  2. """Provider-neutral implementation documentation."""
  3. from __future__ import annotations
  4. import sys as _nexscope_help_sys
  5. if "--help" in _nexscope_help_sys.argv or "-h" in _nexscope_help_sys.argv:
  6. print('Usage: python onboarding.py [arguments]')
  7. raise SystemExit(0)
  8. import argparse
  9. import base64
  10. import io
  11. import json
  12. import os
  13. import re
  14. import secrets
  15. import sys
  16. import tempfile
  17. import time
  18. import urllib.error
  19. from urllib.request import urlopen, Request
  20. # Windows implementation GBK,reconfigure implementation QR ASCII implementation。
  21. for _s in (sys.stdout, sys.stderr):
  22. if hasattr(_s, "reconfigure"):
  23. try:
  24. _s.reconfigure(encoding="utf-8")
  25. except Exception:
  26. pass
  27. try:
  28. import requests
  29. except ImportError:
  30. requests = None # implementation/agent-user implementation
  31. TAG = "[real]"
  32. UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
  33. "(KHTML, like Gecko) Chrome/149.0.0.0 Safari/537.36")
  34. # implementation uid header(implementation)
  35. _LOGIN_FIXED_UID = (os.environ.get("NEXSCOPE_LOGIN_FIXED_UID")
  36. or "eyJhX2lkIjoiNmEyMmM4YjA1YmM5MTZhIiwiZF9pZCI6IiJ9")
    • Note: Contains a long base64-looking blob — not necessarily malicious, but worth inspecting what it decodes to
    • Line 43 on GitHub
  37. AGREEMENTS = {
  38. "user_agreement": "",
  39. "service_agreement": "",
  40. "privacy_policy": "",
  41. }
  42. PAY_METHOD_MAP = {"wechat": "WX_PAY", "alipay": "ALI_PAY"}
  43. _ORDER_STATE_MAP = {
  44. "wait_pay": "unpaid", "paid": "paid", "finished": "paid",
  45. "expire": "expired", "expired": "expired",
  46. "cancel": "cancelled", "cancelled": "cancelled",
  47. }
  48. # ============================================================
  49. # Env / implementation
  50. # ============================================================
  51. def _env_base(name: str, default: str, *fallbacks: str) -> str:
  52. for n in (name, *fallbacks):
  53. v = os.environ.get(n)
  54. if v:
  55. return v.rstrip("/")
  56. return default.rstrip("/")
  57. def _agent_base() -> str:
  58. return _env_base("NEXSCOPE_AGENT_API_BASE", "")
  59. def _login_base() -> str:
  60. return _env_base("NEXSCOPE_LOGIN_API_BASE", "")
  61. def _agent_user_base() -> str:
  62. return _env_base("NEXSCOPE_AGENT_USER_API_BASE", "")
  63. def _api_key() -> str:
  64. return os.environ.get("NEXSCOPE_API_KEY") or os.environ.get("NEXSCOPE_API_KEY") or ""
  65. def _mask_phone(phone: str) -> str:
  66. return f"{phone[:3]}****{phone[-4:]}" if len(phone) >= 7 else phone
  67. def _b64url_json(part: str) -> dict:
  68. """base64url value JWT value(value padding),value dict。"""
  69. try:
  70. return json.loads(base64.urlsafe_b64decode(part + "=" * (-len(part) % 4)))
  71. except Exception:
  72. return {}
  73. def _uid_header(access_token: str, user_id: str) -> str:
  74. """base64url({"a_id":<JWT header.a>,"d_id":<userId>})。"""
  75. parts = (access_token or "").split(".")
  76. hdr = _b64url_json(parts[1]) if len(parts) >= 2 else {}
  77. raw = json.dumps({"a_id": hdr.get("a", ""), "d_id": str(user_id)}, separators=(",", ":")).encode()
  78. return base64.urlsafe_b64encode(raw).decode()
  79. def _jwt_uid() -> dict:
  80. """value NEXSCOPE_API_KEY value JWT payload value。value dict。"""
  81. parts = _api_key().split(".")
  82. return _b64url_json(parts[1]) if len(parts) >= 2 else {}
  83. # ============================================================
  84. # implementation + implementation
  85. # ============================================================
  86. _SESSION_ROOT: str | None = None
  87. def _nexscope_root() -> str:
  88. global _SESSION_ROOT
  89. if _SESSION_ROOT:
  90. return _SESSION_ROOT
  91. candidates = []
  92. acpx = (os.environ.get("NEXSCOPE_WORKSPACES") or "").strip().split(os.pathsep)[0].strip()
  93. if acpx:
  94. candidates.append(os.path.join(acpx, "nexscope"))
  95. candidates += [
  96. os.path.join(os.getcwd(), "nexscope"),
  97. os.path.join(os.path.expanduser("~"), "nexscope"),
  98. os.path.join(tempfile.gettempdir(), "nexscope"),
  99. ]
  100. for root in candidates:
  101. try:
  102. os.makedirs(root, exist_ok=True)
  103. probe = os.path.join(root, ".write_probe")
  104. with open(probe, "w", encoding="utf-8"):
  105. pass
  106. os.remove(probe)
  107. _SESSION_ROOT = os.path.abspath(root)
  108. return _SESSION_ROOT
  109. except OSError:
  110. continue
  111. _SESSION_ROOT = os.path.abspath(candidates[-1])
  112. return _SESSION_ROOT
  113. def session_dir() -> str:
  114. ts = time.time()
  115. sid = (os.environ.get("SESSION_ID") or "").strip() or (
  116. time.strftime("%H%M%S", time.localtime(ts)) + "-" + secrets.token_hex(3))
  117. path = os.path.join(_nexscope_root(), time.strftime("%Y-%m-%d", time.localtime(ts)), sid)
  118. os.makedirs(path, exist_ok=True)
  119. return path
  120. def render_qr(content: str, out_dir: str) -> dict:
  121. try:
  122. import qrcode
  123. except ImportError:
  124. err = "missing qrcode value,value: pip install qrcode pillow"
  125. print(f"{TAG} render_qr: {err}", file=sys.stderr)
  126. return {"png_path": None, "ascii_qr": None, "error": err}
  127. os.makedirs(out_dir, exist_ok=True)
  128. png_path = os.path.join(out_dir, f"qr-{int(time.time() * 1_000_000)}.png")
  129. qr = qrcode.QRCode(border=1)
  130. qr.add_data(content)
  131. qr.make(fit=True)
  132. qr.make_image(fill_color="black", back_color="white").save(png_path)
  133. buf = io.StringIO()
  134. qr.print_ascii(out=buf, invert=True)
  135. return {"png_path": png_path, "ascii_qr": buf.getvalue()}
  136. # ============================================================
  137. # HTTP:requests implementation/agent-user implementation,urllib implementation
  138. # ============================================================
  139. def _require_requests() -> None:
  140. if requests is None:
  141. raise RuntimeError("missing requests value,value: pip install requests")
  142. def _http_post(url: str, body: dict, headers: dict, timeout: int = 30) -> dict:
  143. """value requests POST,value JSON value {_error, _body}。"""
  144. try:
  145. _require_requests()
  146. except RuntimeError as e:
  147. return {"_error": str(e)}
  148. try:
  149. r = requests.post(url, json=body or {}, headers=headers, timeout=timeout)
  150. return r.json()
  151. except Exception as e:
  152. body_text = ""
  153. resp = getattr(e, "response", None)
  154. if resp is not None:
  155. try:
  156. body_text = resp.text[:500]
  157. except Exception:
  158. pass
  159. return {"_error": str(e), "_body": body_text}
  160. def _headers(source: str, origin_host: str, *, access_token: str = "",
  161. user_id: str = "", group_id: str = "") -> dict:
  162. """value headers;access_token value authorization+uid。"""
  163. h = {
  164. "Accept": "application/json, text/plain, */*",
  165. "Content-Type": "application/json;charset=UTF-8",
  166. "Origin": f"https://{origin_host}",
  167. "Referer": f"https://{origin_host}/",
  168. "source": source,
  169. "User-Agent": UA,
  170. }
  171. if access_token:
  172. h["authorization"] = access_token
  173. h["uid"] = _uid_header(access_token, user_id) if user_id else _LOGIN_FIXED_UID
  174. if group_id:
  175. h["tid"] = group_id
  176. return h
  177. def _login_post(path: str, body: dict) -> dict:
  178. return _http_post(f"{_login_base()}{path}", body,
  179. _headers("ai-nexscope-web", "ai.nexscope.com", access_token=""))
  180. def _gateway(method: str, path: str, body: dict | None = None) -> dict:
  181. """value HTTP。401/402/403 value,5xx value 3 value。"""
  182. url = f"{_agent_base()}{path}"
  183. body_bytes = json.dumps(body or {}).encode() if method == "POST" else None
  184. last_exc: Exception = RuntimeError("unknownError")
  185. for attempt in range(3):
  186. if attempt:
  187. time.sleep(1 << (attempt - 1))
  188. headers = {"Authorization": _api_key()}
  189. if method == "POST":
  190. headers["Content-Type"] = "application/json"
  191. req = Request(url, method=method, data=body_bytes, headers=headers)
  192. try:
  193. with urlopen(req, timeout=30) as resp:
  194. return json.loads(resp.read().decode())
  195. except urllib.error.HTTPError as e:
  196. status = e.code
  197. raw = e.read().decode()[:300]
  198. if status == 401:
  199. raise RuntimeError(f"text(401),text NEXSCOPE_API_KEY text NEXSCOPE_API_KEY:{raw}")
  200. if status == 402:
  201. raise RuntimeError(f"text(402),text:{raw}")
  202. if status == 403:
  203. raise RuntimeError(f"text(403):{raw}")
  204. last_exc = RuntimeError(f"HTTP {status}: {raw}")
  205. if status not in (408, 429, 500, 502, 503, 504):
  206. raise last_exc
  207. except Exception as e:
  208. last_exc = RuntimeError(f"text: {e}")
  209. print(f"{TAG} gateway_{method.lower()} attempt {attempt+1}/3 text: {e}", file=sys.stderr)
  210. raise last_exc
  211. # ============================================================
  212. # implementation:implementation / implementation / implementation
  213. # ============================================================
  214. def _check_biz(resp: dict, tag: str) -> dict:
  215. if resp.get("errcode") not in (None, 200):
  216. raise RuntimeError(f"{tag} textError: {resp}")
  217. return resp
  218. def fetch_user_info() -> dict:
  219. return _check_biz(_gateway("GET", "/account/currentByAPI"), "currentByAPI")
  220. def fetch_packages(package_type: int) -> list:
  221. resp = _check_biz(_gateway("POST", "/package/getByTypeByAPI", {"packageType": package_type}),
  222. "getByTypeByAPI")
  223. return resp.get("packageList") or []
  224. def normalize_package(p: dict) -> dict | None:
  225. """value(price=0)value None value。"""
  226. if float(p.get("packagePrice", 0) or 0) == 0:
  227. return None
  228. try:
  229. ext = json.loads(p.get("extJson") or "{}")
  230. except Exception:
  231. ext = {}
  232. return {
  233. "plan_id": p.get("packageId", ""),
  234. "name": p.get("packageName", ""),
  235. "price": p.get("packagePrice", 0),
  236. "price_string": p.get("packagePriceString", ""),
  237. "original_price": p.get("originalPrice", 0),
  238. "original_price_string": p.get("originalPriceString", ""),
  239. "currency": "CNY",
  240. "credits": p.get("creditAmount", 0),
  241. "validity_period": p.get("validityPeriod", ""),
  242. "validity_period_type": p.get("validityPeriodType", ""),
  243. "description": p.get("description", ""),
  244. "is_recommend": bool(ext.get("isRecommend", False)),
  245. "logo_url": ext.get("logo", ""),
  246. "features": ext.get("features", []),
  247. "available_methods": ["wechat", "alipay"],
  248. }
  249. def create_order(plan_id: str, method: str) -> dict:
  250. if method not in PAY_METHOD_MAP:
  251. raise ValueError(f"text {method},text wechat/alipay")
  252. user = fetch_user_info()
  253. is_team = bool(user.get("isTeamUser"))
  254. member_id = _jwt_uid().get("uid", "")
  255. if not member_id:
  256. raise RuntimeError("value JWT value uid,value NEXSCOPE_API_KEY value NEXSCOPE_API_KEY")
  257. body = {
  258. "packageId": plan_id, "payType": PAY_METHOD_MAP[method], "payDeviceType": "PC",
  259. "memberId": member_id, "groupId": user.get("currentGroupId", ""),
  260. }
  261. path = "/order/createTeamOrderByAPI" if is_team else "/order/createByAPI"
  262. print(f"{TAG} text path={path} isTeamUser={is_team} groupId={body['groupId']}", file=sys.stderr)
  263. resp = _check_biz(_gateway("POST", path, body), "value")
  264. return {
  265. "order_id": resp.get("orderId", ""),
  266. "qr_content": resp.get("payQrcode") or resp.get("payUrl", ""),
  267. "pay_url": resp.get("payUrl", ""),
  268. "pay_price": resp.get("payPrice", ""),
  269. "original_price": resp.get("originalPrice", ""),
  270. "discount_price": resp.get("discountPrice", ""),
  271. "state": resp.get("state", ""),
  272. "time_left": resp.get("timeLeft", 0),
  273. "expire_date": resp.get("expireDate", ""),
  274. "trade_no": resp.get("tradeNo", ""),
  275. "product": resp.get("product", ""),
  276. "pay_type": resp.get("payType", ""),
  277. }
  278. def query_order(order_id: str) -> dict:
  279. resp = _check_biz(_gateway("POST", "/order/getByAPI", {"orderId": order_id}), "value")
  280. state = resp.get("state", "")
  281. return {
  282. "order_id": order_id,
  283. "status": _ORDER_STATE_MAP.get(state, "unknown"),
  284. "state": state,
  285. "paid_at": resp.get("payDate") or None,
  286. "pay_price": resp.get("payPrice", ""),
  287. "time_left": resp.get("timeLeft", 0),
  288. "expire_date": resp.get("expireDate", ""),
  289. "trade_no": resp.get("tradeNo", ""),
  290. "product": resp.get("product", ""),
  291. }
  292. # ============================================================
  293. # implementation + implementation key
  294. # ============================================================
  295. def send_verify_code(phone: str) -> dict:
  296. masked = _mask_phone(phone)
  297. if not re.fullmatch(r"\d{11}", phone):
  298. return {"sent": False, "phone": masked, "errmsg": f"text(text 11 text): {phone}"}
  299. resp = _login_post("/user/v1/web/login", {
  300. "type": "sms", "method": "getVerifyCode",
  301. "data": {"authPhone": phone, "areaCode": "+86", "clientChannel": "NexscopeAgent"},
  302. })
  303. if "_error" in resp:
  304. return {"sent": False, "phone": masked, "errmsg": resp.get("_body") or resp["_error"]}
  305. if resp.get("success") or resp.get("code") == "OK":
  306. return {"sent": True, "phone": masked, "area_code": "+86", "agreements": AGREEMENTS}
  307. return {"sent": False, "phone": masked, "errmsg": resp.get("message") or json.dumps(resp, ensure_ascii=False)}
  308. def _login_v3(phone: str, code: str, channel: str) -> dict:
  309. resp = _login_post("/user/v3/web/login", {
  310. "type": "sms", "method": "login", "systemId": "NexscopeAgent",
  311. "data": {"areaCode": "+86", "authPhone": phone, "authCode": code,
  312. "sourceChannel": channel or "skill"},
  313. })
  314. if "_error" in resp:
  315. return {"error": f"login: {resp.get('_body') or resp['_error']}"}
  316. if not (resp.get("success") or resp.get("code") == "OK"):
  317. return {"error": f"login: {resp.get('message') or json.dumps(resp, ensure_ascii=False)}"}
  318. data = resp.get("data") or {}
  319. access_token, user_id = data.get("accessToken"), data.get("userId")
  320. if not access_token or not user_id:
  321. return {"error": f"login: text accessToken/userId: {json.dumps(resp, ensure_ascii=False)}"}
  322. return {
  323. "access_token": access_token,
  324. "refresh_token": data.get("refreshToken", "") or "",
  325. "user_id": str(user_id),
  326. "nick_name": data.get("userName", ""),
  327. "is_new_user": bool(data.get("newUser") or data.get("isFirstRegister")),
  328. }
  329. def _login_by_token(access_token: str, refresh_token: str) -> dict:
  330. """value。value。"""
  331. resp = _http_post(f"{_agent_user_base()}/account/loginByToken", {
  332. "token": access_token, "refreshToken": refresh_token,
  333. "device": {"aid": "3026344186", "did": "", "type": "Windows",
  334. "os": "10", "model": "149.0.0.0", "brand": "Chrome"},
  335. }, _headers("agent-nexscope-web", "agent.nexscope.com", access_token=access_token))
  336. if "_error" in resp:
  337. return {"error": f"loginByToken: {resp.get('_body') or resp['_error']}"}
  338. if resp.get("errcode") != 200:
  339. return {"error": f"loginByToken: {resp.get('errmsg') or json.dumps(resp, ensure_ascii=False)}"}
  340. print(f"{TAG} loginByToken text,text", file=sys.stderr)
  341. return {}
  342. def _fetch_user_info_v3(access_token: str, user_id: str) -> dict:
  343. """value userInfo value group_id / member_id。"""
  344. resp = _http_post(f"{_login_base()}/nexscopeApp/api/userCenter/userInfo", {},
  345. _headers("agent-nexscope-web", "agent.nexscope.com",
  346. access_token=access_token, user_id=user_id))
  347. if "_error" in resp:
  348. return {"error": f"userInfo: {resp.get('_body') or resp['_error']}"}
  349. if resp.get("code") != "OK":
  350. return {"error": f"userInfo: {resp.get('message') or json.dumps(resp, ensure_ascii=False)}"}
  351. teams = (resp.get("data") or {}).get("teamList") or []
  352. if not teams:
  353. return {"error": "userInfo: value,value value"}
  354. selected = (next((t for t in teams if t.get("isSelect") == 1 and t.get("agentTeamId")), None)
  355. or next((t for t in teams if t.get("agentTeamId")), None))
  356. if not selected:
  357. return {"error": "userInfo: value agent value,value value"}
  358. gid, mid = selected.get("agentTeamId"), selected.get("agentMemberId")
  359. if not gid or not mid:
  360. return {"error": f"userInfo: text agentTeamId/agentMemberId: {json.dumps(selected, ensure_ascii=False)}"}
  361. return {"group_id": str(gid), "member_id": str(mid), "team_name": selected.get("teamName", "")}
  362. _TOKEN_KEYS = ("token", "apiToken", "api_token", "apiKey", "api_key")
  363. def _extract_token(resp: dict) -> str:
  364. if not isinstance(resp, dict):
  365. return ""
  366. for src in (resp, resp.get("data") if isinstance(resp.get("data"), dict) else {}):
  367. for k in _TOKEN_KEYS:
  368. v = src.get(k)
  369. if isinstance(v, str) and v:
  370. return v
  371. d = resp.get("data")
  372. return d if isinstance(d, str) and d else ""
  373. def _get_or_generate_api_token(access_token: str, user_id: str, group_id: str) -> dict:
  374. hdr = _headers("agent-nexscope-web", "ai.nexscope.com",
  375. access_token=access_token, user_id=user_id, group_id=group_id)
  376. for path, source in (("/group/getApiToken", "existing"),
  377. ("/group/generateApiToken", "generated")):
  378. resp = _http_post(f"{_agent_user_base()}{path}", {"id": group_id}, hdr)
  379. if "_error" in resp:
  380. return {"error": f"{path.rsplit('/', 1)[-1]}: {resp.get('_body') or resp['_error']}"}
  381. tok = _extract_token(resp)
  382. if tok:
  383. return {"api_key": tok, "source": source}
  384. return {"error": f"generateApiToken: text token,text: {json.dumps(resp, ensure_ascii=False)}"}
  385. def login_and_get_key(phone: str, code: str, channel: str) -> dict:
  386. masked = _mask_phone(phone)
  387. if not re.fullmatch(r"\d{11}", phone):
  388. return {"error": f"login: text: {phone}", "phone": masked}
  389. if not re.fullmatch(r"\d{4,8}", code):
  390. return {"error": f"login: text: {code}", "phone": masked}
  391. lg = _login_v3(phone, code, channel)
  392. if "error" in lg:
  393. return {"error": lg["error"], "phone": masked}
  394. if lg.get("is_new_user"):
  395. lbt = _login_by_token(lg["access_token"], lg["refresh_token"])
  396. if "error" in lbt:
  397. print(f"{TAG} {lbt['error']}(text key)", file=sys.stderr)
  398. info = _fetch_user_info_v3(lg["access_token"], lg["user_id"])
  399. if "error" in info:
  400. return {"error": info["error"], "phone": masked}
  401. tok = _get_or_generate_api_token(lg["access_token"], lg["user_id"], info["group_id"])
  402. if "error" in tok:
  403. return {"error": tok["error"], "phone": masked}
  404. return {
  405. "api_key": tok["api_key"], "phone": masked,
  406. "group_id": info["group_id"], "member_id": info["member_id"],
  407. "source": tok["source"], "nick_name": lg.get("nick_name", ""),
  408. "team_name": info.get("team_name", ""),
  409. "is_new_user": lg.get("is_new_user", False),
  410. }
  411. # ============================================================
  412. # argparse implementation
  413. # ============================================================
  414. def _emit(obj: dict) -> None:
  415. print(json.dumps(obj, ensure_ascii=False, indent=2))
  416. def _cmd_send_code(args) -> int:
  417. r = send_verify_code(args.phone.strip())
  418. _emit(r)
  419. if r.get("sent"):
  420. print(f"{TAG} text {r['phone']}", file=sys.stderr)
  421. return 0 if r.get("sent") else 1
  422. def _cmd_login(args) -> int:
  423. r = login_and_get_key(args.phone.strip(), args.code.strip(), args.channel)
  424. _emit(r)
  425. if "api_key" in r:
  426. print(f"{TAG} text API key(text: {r['source']})", file=sys.stderr)
  427. return 0
  428. return 1
  429. def _cmd_list_plans(args) -> int:
  430. try:
  431. payload = _jwt_uid()
  432. if payload:
  433. print(f"{TAG} JWT uid={payload.get('uid')} name={payload.get('name')}", file=sys.stderr)
  434. user = fetch_user_info()
  435. is_team = bool(user.get("isTeamUser"))
  436. nick = user.get("nickName", "")
  437. print(f"{TAG} text {nick} isTeamUser={is_team}", file=sys.stderr)
  438. pkgs = fetch_packages(7 if is_team else 1)
  439. plans = [n for n in (normalize_package(p) for p in pkgs) if n is not None]
  440. _emit({"plans": plans, "user": {"nickName": nick, "isTeamUser": is_team}})
  441. return 0
  442. except RuntimeError as e:
  443. _emit({"error": True, "message": str(e)})
  444. return 1
  445. def _cmd_order(args) -> int:
  446. try:
  447. pkgs = fetch_packages(7 if bool(fetch_user_info().get("isTeamUser")) else 1)
  448. match = next((n for n in (normalize_package(p) for p in pkgs)
  449. if n and n["plan_id"] == args.plan_id), None)
  450. if match is None:
  451. _emit({"error": True, "message": f"unknowntext plan_id={args.plan_id}"})
  452. return 1
  453. if args.method not in match.get("available_methods", []):
  454. _emit({"error": True,
  455. "message": f"text {args.plan_id} text {args.method},text {match['available_methods']}"})
  456. return 1
  457. order = create_order(args.plan_id, args.method)
  458. except (RuntimeError, ValueError) as e:
  459. _emit({"error": True, "message": str(e)})
  460. return 1
  461. qr = render_qr(order["qr_content"], session_dir())
  462. order["png_path"] = qr.get("png_path")
  463. order["ascii_qr"] = qr.get("ascii_qr")
  464. if qr.get("error"):
  465. order["qr_render_error"] = qr["error"]
  466. _emit(order)
  467. return 0
  468. def _cmd_query(args) -> int:
  469. try:
  470. _emit(query_order(args.order_id))
  471. return 0
  472. except RuntimeError as e:
  473. _emit({"error": True, "message": str(e)})
  474. return 1
  475. def main(argv: list[str] | None = None) -> int:
  476. parser = argparse.ArgumentParser(prog="onboarding", description="Nexscope value CLI")
  477. sub = parser.add_subparsers(dest="cmd", required=True)
  478. p = sub.add_parser("send-code", help="value")
  479. p.add_argument("phone", help="11 value")
  480. p.set_defaults(func=_cmd_send_code)
  481. p = sub.add_parser("login", help="value API key")
  482. p.add_argument("phone")
  483. p.add_argument("code", help="value")
  484. p.add_argument("--channel", default="skill",
  485. help="value,value skill;workbuddy value workbuddy")
  486. p.set_defaults(func=_cmd_login)
  487. sub.add_parser("list-plans", help="value").set_defaults(func=_cmd_list_plans)
  488. p = sub.add_parser("order", help="value")
  489. p.add_argument("plan_id")
  490. p.add_argument("method", choices=["wechat", "alipay"])
  491. p.set_defaults(func=_cmd_order)
  492. p = sub.add_parser("query", help="value")
  493. p.add_argument("order_id")
  494. p.set_defaults(func=_cmd_query)
  495. args = parser.parse_args(argv)
  496. return args.func(args)
  497. if __name__ == "__main__":
  498. sys.exit(main())

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.