Напиши расширение для турбоварп где будет через лю...

Создано: 16 августа 2025 г.

Отвечено с использованием GPT-5 Thinking от Chat01

Вопрос

Напиши расширение для турбоварп где будет через любое апи поиска без подписок токенов и тд отдавать json по запросу (блок (json по запросу (запрос)))

Мысль

Considering API options for extension

The user wants a TurboWarp extension to fetch JSON data through any search API without subscriptions. Many services like Google or Bing need API keys, but there are free options like DuckDuckGo’s Instant Answer API (though it may be deprecated) and Wikipedia’s search API, which doesn't require a key. I'll confirm what works best!

Selecting suitable API and extension format

The user asked for any search API without tokens, so DuckDuckGo Instant Answer seems like a good option—though it doesn't return full search results, it provides related topics that might work. I’ll focus on using that API and writing the TurboWarp extension code to fit the Scratch 3 format.

Designing the extension

To implement the extension, I’ll define a SearchJSON class with a method to fetch JSON from DuckDuckGo’s API. I'll format the returned data as text in response to a block request. However, I need to check if DuckDuckGo supports CORS or if I'll need to switch to Wikipedia’s API, which works reliably.

Choosing the best approach

I think the user wants any search API, not just a knowledge base, so I’ll offer two options: DuckDuckGo and Wikipedia. To handle potential CORS issues with DuckDuckGo, I’ll code it to fall back to Wikipedia if the first fetch fails. A dropdown would let the user choose. I'll provide sample code!

Building the extension

I’m creating an extension in TurboWarp for searching JSON. It sends a request to DuckDuckGo and Wikipedia, returning the results into a normalized format. I’ll provide code for both engines, with a fallback in case one fails. The extension supports simple usage, but an advanced version is also possible. I'll ensure it's compatible with the sandboxed environment.

Thought for 35s

Ответ

круто, сделал минималистичное расширение для TurboWarp с одним блоком-репортёром:

json по запросу (запрос)

Под капотом оно сначала пробует DuckDuckGo Instant Answer API (без ключа), а если не вышло (например, CORS), то автоматически падает обратно на Wikipedia OpenSearch (тоже без ключа). На выход отдаёт строку с JSON в нормализованном формате: { engine, query, results: [{title, url, description}] }.

Сохраните код ниже как, например, search-json.js, выложите где-нибудь по HTTPS (GitHub Gist → “Raw” отлично подходит), и подключите в TurboWarp: «Расширения → Пользовательское → URL вашего файла».

js
(function (Scratch) { 'use strict'; class SearchJSON { getInfo() { return { id: 'searchjson', name: 'Поиск JSON', color1: '#4C97FF', color2: '#3373CC', blocks: [ { opcode: 'jsonByQuery', blockType: Scratch.BlockType.REPORTER, text: 'json по запросу [QUERY]', arguments: { QUERY: { type: Scratch.ArgumentType.STRING, defaultValue: 'котики' } } } ] }; } async jsonByQuery(args) { const q = String(args.QUERY || '').trim(); if (!q) { return JSON.stringify({ engine: null, query: '', results: [], error: 'Пустой запрос' }); } // timeout, чтобы не «висло» бесконечно const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 8000); // 1) Пытаемся DuckDuckGo Instant Answer (без ключа) try { const ddgURL = 'https://api.duckduckgo.com/?q=' + encodeURIComponent(q) + '&format=json&no_html=1&no_redirect=1&skip_disambig=1'; const res = await fetch(ddgURL, { signal: controller.signal, headers: { 'Accept': 'application/json' } }); if (res.ok) { const data = await res.json(); const results = this._normalizeDDG(data); if (results.length) { clearTimeout(timer); return JSON.stringify({ engine: 'duckduckgo', query: q, results }); } } } catch (e) { // игнорируем и пробуем вики } // 2) Фолбэк на Wikipedia OpenSearch (без ключа, CORS через origin=*) try { const wikiURL = 'https://ru.wikipedia.org/w/api.php?' + 'action=opensearch&format=json&origin=*' + '&limit=10&search=' + encodeURIComponent(q); const res = await fetch(wikiURL, { signal: controller.signal, headers: { 'Accept': 'application/json' } }); if (res.ok) { const data = await res.json(); const results = this._normalizeWiki(data); clearTimeout(timer); return JSON.stringify({ engine: 'wikipedia', query: q, results }); } } catch (e) { // падаем в общую ошибку } clearTimeout(timer); return JSON.stringify({ engine: null, query: q, results: [], error: 'Не удалось получить данные (возможны CORS/сеть).' }); } _normalizeDDG(data) { const out = []; const push = (title, url, description) => { if (title || url || description) { out.push({ title: title || '', url: url || '', description: description || '' }); } }; // «крупный» ответ if (data.AbstractURL || data.AbstractText || data.Heading) { push(data.Heading || data.AbstractSource || '', data.AbstractURL || '', data.AbstractText || ''); } // RelatedTopics может быть вложенным const extract = (arr) => { for (const item of arr || []) { if (item.Topics) { extract(item.Topics); } else { push(item.Text || '', item.FirstURL || '', item.Text || ''); } } }; extract(data.RelatedTopics || []); return out.slice(0, 10); } _normalizeWiki(opensearchArr) { // формат: [query, titles[], descriptions[], urls[]] const titles = opensearchArr[1] || []; const descs = opensearchArr[2] || []; const urls = opensearchArr[3] || []; const out = []; for (let i = 0; i < titles.length; i++) { out.push({ title: titles[i] || '', url: urls[i] || '', description: descs[i] || '' }); } return out; } } Scratch.extensions.register(new SearchJSON()); })(Scratch);

Как использовать в проекте

  1. Откройте редактор TurboWarp.
  2. «Расширения → Пользовательское → вставьте URL на search-json.js».
  3. В блоках появится репортёр json по запросу (текст).
  4. Подайте строку запроса, а результат используйте как текстовую строку с JSON. Например, соедините с блоком «отобразить» или парсите в своем коде (если нужно — распилите строку, т.к. Scratch-хранилище — текстовое).

Пример результата

Запрос: котики → строка вида:

json
{"engine":"duckduckgo","query":"котики","results":[{"title":"Cats - ...","url":"https://...","description":"..."}]}

Если хотите — могу добавить ещё меню выбора движка (DDG/Wikipedia/auto) или второй блок, который возвращает N-й результат (заголовок/ссылку/описание) отдельно.

Поделиться этим Q&A