ChatGPT ئەوەی-خۆکار 📣

بەرزکردنی وەڵامەکانی ChatGPT بە شێوەی خۆکار

// ==UserScript==
// @name                ChatGPT Auto-Talk 📣
// @name:af             ChatGPT Auto-Praat 📣
// @name:am             ChatGPT በራስሰር እንጋቢ 📣
// @name:ar             ChatGPT التحدث التلقائي 📣
// @name:az             ChatGPT Avtomatik-Danışıq 📣
// @name:be             ChatGPT Аўта-Размова 📣
// @name:bem            ChatGPT Kusogolo Kwati 📣
// @name:bg             ChatGPT Авто-Разговор 📣
// @name:bn             ChatGPT অটো-টক 📣
// @name:bo             ChatGPT རང་འཛུལ་སྐད་ཆེན་པོ 📣
// @name:bs             ChatGPT Auto-Razgovor 📣
// @name:ca             ChatGPT Auto-Parla 📣
// @name:ceb            ChatGPT Auto-Panulti 📣
// @name:ckb            ChatGPT ئەوەی-خۆکار 📣
// @name:cs             ChatGPT Automatický-Rozhovor 📣
// @name:cy             ChatGPT Sgwrsio-Awtomatig 📣
// @name:da             ChatGPT Auto-Tale 📣
// @name:de             ChatGPT Auto-Sprechen 📣
// @name:dv             ChatGPT އޮޓޯ-ކޮމިއުނިކޭޝަން 📣
// @name:dz             ChatGPT རང་འཛུལ་སྐད་ཆེན་པོ 📣
// @name:el             ChatGPT Αυτόματη-Ομιλία 📣
// @name:eo             ChatGPT Aŭtomata-Parolo 📣
// @name:es             ChatGPT Auto-Hablar 📣
// @name:et             ChatGPT Automaatne-Jutt 📣
// @name:eu             ChatGPT Auto-Hizketa 📣
// @name:fa             ChatGPT گفتگوی خودکار 📣
// @name:fi             ChatGPT Auto-Puhe 📣
// @name:fo             ChatGPT Sjálvvirkandi-Prát 📣
// @name:fr             ChatGPT Auto-Parler 📣
// @name:fr-CA          ChatGPT Auto-Parler 📣
// @name:gd             ChatGPT Fèin-Labhairt 📣
// @name:gl             ChatGPT Auto-Falar 📣
// @name:gu             ChatGPT ઓટો-બોલો 📣
// @name:haw            ChatGPT Kūʻokoʻa-ʻŌlelo 📣
// @name:he             ChatGPT דיבור-אוטומטי 📣
// @name:hi             ChatGPT ऑटो-टॉक 📣
// @name:hr             ChatGPT Auto-Razgovor 📣
// @name:ht             ChatGPT Auto-Pale 📣
// @name:hu             ChatGPT Auto-Beszélgetés 📣
// @name:hy             ChatGPT Ինքնաբերաբար-Խոսք 📣
// @name:id             ChatGPT Bicara-Otomatis 📣
// @name:is             ChatGPT Sjálfvirk-Tal 📣
// @name:it             ChatGPT Auto-Parlare 📣
// @name:ja             ChatGPT オートトーク 📣
// @name:jv             ChatGPT Auto-Omah 📣
// @name:ka             ChatGPT ავტო-ლაპარაკი 📣
// @name:kab            ChatGPT Awto-Talqeq 📣
// @name:kk             ChatGPT Авто-Сөйлеу 📣
// @name:km             ChatGPT ការប្រាស្រ័យអគ្គិសនី 📣
// @name:kn             ChatGPT ಸ್ವಯಂಚಾಲಿತ-ಮಾತು 📣
// @name:ko             ChatGPT 자동-토크 📣
// @name:ku             ChatGPT Axê-Raxt 📣
// @name:ky             ChatGPT Авто-Сүйлөшүү 📣
// @name:la             ChatGPT Auto-Loquens 📣
// @name:lb             ChatGPT Auto-Schwätzen 📣
// @name:lo             ChatGPT ການເວົ້າອັດຕະໂນມັດ 📣
// @name:lt             ChatGPT Auto-Kalba 📣
// @name:lv             ChatGPT Auto-Saruna 📣
// @name:mg             ChatGPT Auto-Kabary 📣
// @name:mi             ChatGPT Aunoa-Kōrero 📣
// @name:mk             ChatGPT Авто-Разговор 📣
// @name:ml             ChatGPT ഓട്ടോ-സംസാരം 📣
// @name:mn             ChatGPT Автомат-Яриа 📣
// @name:ms             ChatGPT Auto-Bercakap 📣
// @name:mt             ChatGPT Auto-Kellem 📣
// @name:my             ChatGPT အလိုအလျောက်-စကားပြော 📣
// @name:ne             ChatGPT स्वचालित-वार्ता 📣
// @name:nl             ChatGPT Auto-Praten 📣
// @name:no             ChatGPT Auto-Snakke 📣
// @name:ny             ChatGPT Auto-Kulankhula 📣
// @name:pa             ChatGPT ਆਟੋ-ਗੱਲਬਾਤ 📣
// @name:pap            ChatGPT Auto-Papia 📣
// @name:pl             ChatGPT Auto-Rozmowa 📣
// @name:ps             ChatGPT خودکاره-خبري کول 📣
// @name:pt             ChatGPT Auto-Falar 📣
// @name:pt-BR          ChatGPT Auto-Falar 📣
// @name:rn             ChatGPT Auto-Kuvuga 📣
// @name:ro             ChatGPT Auto-Vorbire 📣
// @name:ru             ChatGPT Авто-Разговор 📣
// @name:rw             ChatGPT Ibyoguhindura 📣
// @name:sg             ChatGPT Auto-Yângâ 📣
// @name:si             ChatGPT ස්වයංක්‍රීය-කතා 📣
// @name:sk             ChatGPT Automatický-Rozhovor 📣
// @name:sl             ChatGPT Avtomatski-Pogovor 📣
// @name:sm             ChatGPT Fetalai-Otometi 📣
// @name:sn             ChatGPT Auto-Taurirana 📣
// @name:so             ChatGPT Hadal-otomaatig ah 📣
// @name:sr             ChatGPT Ауто-Разговор 📣
// @name:sv             ChatGPT Auto-Prata 📣
// @name:sw             ChatGPT Maongezi-Otomatiki 📣
// @name:ta             ChatGPT தானாகவே-பேச்சு 📣
// @name:te             ChatGPT ఆటో-మాట 📣
// @name:tg             ChatGPT Авто-Гап 📣
// @name:th             ChatGPT การสนทนาอัตโนมัติ 📣
// @name:ti             ChatGPT እስካምልክቲ-ቃል ኣቐሪቡ 📣
// @name:tk             ChatGPT Auto-Dialog 📣
// @name:tn             ChatGPT Auto-Matla 📣
// @name:to             ChatGPT Fakamatala-Otometi 📣
// @name:tpi            ChatGPT Autometik-Tok 📣
// @name:tr             ChatGPT Otomatik-Konuşma 📣
// @name:uk             ChatGPT Авто-Розмова 📣
// @name:ur             ChatGPT خودکار-بات 📣
// @name:uz             ChatGPT Avto-Suhbat 📣
// @name:vi             ChatGPT Tự-Động-Nói 📣
// @name:xh             ChatGPT IyaZenzekelayo-Thetha 📣
// @name:yi             ChatGPT אַוטאָ-רעדן 📣
// @name:zh             ChatGPT 自动谈话 📣
// @name:zh-CN          ChatGPT 自动谈话 📣
// @name:zh-HK          ChatGPT 自動談話 📣
// @name:zh-SG          ChatGPT 自动谈话 📣
// @name:zh-TW          ChatGPT 自動談話 📣
// @name:zu             ChatGPT Ukuzenzakalela-Ukhuluma 📣
// @description         Automatically play ChatGPT responses
// @description:af      Speel ChatGPT-antwoorde outomaties af
// @description:am      ምርመራ ChatGPT ምላሾችን በራስ-ሰር
// @description:ar      تشغيل ردود ChatGPT تلقائيًا
// @description:az      ChatGPT cavablarını avtomatik olaraq oynat
// @description:be      Аўтаматычнае прайграванне адказаў ChatGPT
// @description:bem     Panga zolingana pa ChatGPT mwankhama
// @description:bg      Автоматично възпроизвеждане на отговори от ChatGPT
// @description:bn      ChatGPT প্রতিক্রিয়া স্বয়ংক্রিয়ভাবে প্লে করুন
// @description:bo      ChatGPT ལྟེ་བཤོལ་རང་འཛུལ་སྐད་སྒྲོན་འགྲོ
// @description:bs      Automatski reproducirajte odgovore ChatGPT-a
// @description:ca      Reproduir automàticament les respostes de ChatGPT
// @description:ceb     Awomatikong pagdula sa mga tubag sa ChatGPT
// @description:ckb     بەرزکردنی وەڵامەکانی ChatGPT بە شێوەی خۆکار
// @description:cs      Automatické přehrávání odpovědí ChatGPT
// @description:cy      Chwarae atebion ChatGPT yn awtomatig
// @description:da      Afspil ChatGPT-svar automatisk
// @description:de      ChatGPT-Antworten automatisch abspielen
// @description:dv      ChatGPT ޖެހިދާން އޮޓޯއެވެއްވިދާނެއް ކުރޭ
// @description:dz      ChatGPT བརྒྱུད་གཏོང་རང་འཛུལ་སྐད་སྒྲོན་འགྲོ
// @description:el      Αυτόματη αναπαραγωγή απαντήσεων ChatGPT
// @description:eo      Aŭtomate ludi ChatGPT-respondojn
// @description:es      Reproducir automáticamente respuestas de ChatGPT
// @description:et      ChatGPT vastuste automaatne esitamine
// @description:eu      ChatGPT erantzunak automatikoki erreproduzitu
// @description:fa      پخش خودکار پاسخهای ChatGPT
// @description:fi      Toista ChatGPT-vastaukset automaattisesti
// @description:fo      Spæl ChatGPT svar sjálvvirkandi
// @description:fr      Lire automatiquement les réponses de ChatGPT
// @description:fr-CA   Lire automatiquement les réponses de ChatGPT
// @description:gd      Cluich gu fèin-ghluasadach freagairtean ChatGPT
// @description:gl      Reproducir automaticamente as respostas de ChatGPT
// @description:gu      ChatGPT પ્રતિક્રિયાઓ આપોઆપ વગાડો
// @description:haw     Hoʻopaʻapaʻa i nā pane ChatGPT ma ka automate
// @description:he      השמע תגובות ChatGPT באופן אוטומטי
// @description:hi      ChatGPT प्रतिक्रियाओं को स्वचालित रूप से चलाएं
// @description:hr      Automatski reproducirajte odgovore ChatGPT-a
// @description:ht      Jwe repons ChatGPT otomatikman
// @description:hu      ChatGPT-válaszok automatikus lejátszása
// @description:hy      Ավտոմատ նվագարկել ChatGPT-ի պատասխանները
// @description:id      Mainkan respons ChatGPT secara otomatis
// @description:is      Spilaðu sjálfkrafa svör ChatGPT
// @description:it      Riprodurre automaticamente le risposte di ChatGPT
// @description:ja      ChatGPT の回答を自動的に再生する
// @description:jv      Puter balasan ChatGPT kanthi otomatis
// @description:ka      ავტომატურად ითამაშეთ ChatGPT პასუხები
// @description:kab     Melk ikdimen n d-yitran n ChatGPT
// @description:kk      ChatGPT жауаптарын автоматты түрде ойнату
// @description:km      លេងការឆ្លើយតបរបស់ ChatGPT ដោយស្វ័យប្រវត្តិ
// @description:kn      ChatGPT ಪ್ರತಿಕ್ರಿಯೆಗಳನ್ನು ಸ್ವಯಂಚಾಲಿತವಾಗಿ ಪ್ಲೇ ಮಾಡಿ
// @description:ko      ChatGPT 응답 자동 재생
// @description:ku      Serdana erebeyîyan bi xweka yên ChatGPT bixwe
// @description:ky      ChatGPT жоопторун автоматтык түрдө ойнотуу
// @description:la      Lude responsiones ChatGPT automatice
// @description:lb      ChatGPT-Äntwerten automatesch ofspillen
// @description:lo      ຄວາມສົມພາດ ChatGPT ໃນຕົວເອງ
// @description:lt      Automatiškai leisti ChatGPT atsakymus
// @description:lv      Automātiski atskaņot ChatGPT atbildes
// @description:mg      Alefaso ho azy ny valintenin'i ChatGPT
// @description:mi      Purei aunoa i ngā whakautu a ChatGPT
// @description:mk      Автоматски пуштај одговори на ChatGPT
// @description:ml      ChatGPT പ്രതികരണങ്ങൾ സ്വയമേവ പ്ലേ ചെയ്യുക
// @description:mn      ChatGPT хариултыг автоматаар тоглуулах
// @description:ms      Mainkan tindak balas ChatGPT secara automatik
// @description:mt      Awtomatikament iddoqq ir-risposti ta' ChatGPT
// @description:my      ChatGPT ၏တုံ့ပြန်ချက်များကို အလိုအလျောက် ဖွင့်ပါ
// @description:ne      ChatGPT प्रतिक्रियाहरू स्वचालित रूपमा प्ले गर्नुहोस्
// @description:nl      Speel ChatGPT-antwoorden automatisch af
// @description:no      Spill ChatGPT-svar automatisk
// @description:ny      Sewera mayankho a ChatGPT zokha
// @description:pa      ChatGPT ਦੇ ਜਵਾਬ ਆਟੋਮੈਟਿਕ ਚਲਾਓ
// @description:pap     Hunga respuesta di ChatGPT otomátikamente
// @description:pl      Automatyczne odtwarzanie odpowiedzi ChatGPT
// @description:ps      د ChatGPT ځوابونه په اوتومات ډول لوبې کړئ
// @description:pt      Reproduzir automaticamente respostas do ChatGPT
// @description:pt-BR   Reproduzir automaticamente respostas do ChatGPT
// @description:rn      Gukina ivyishura vya ChatGPT ku buryo bwikora
// @description:ro      Redați automat răspunsurile ChatGPT
// @description:ru      Автоматическое воспроизведение ответов ChatGPT
// @description:rw      Gukina ibisubizo bya ChatGPT ku buryo bwikora
// @description:sg      Gbangba ko ye tere ChatGPT makumba mbene
// @description:si      ChatGPT ප්‍රතිචාර ස්වයංක්‍රීයව ප්ලේ කරන්න
// @description:sk      Automatické prehrávanie odpovedí ChatGPT
// @description:sl      Samodejno predvajaj odgovore ChatGPT
// @description:sm      Taʻa otometi tali a le ChatGPT
// @description:sn      Tumira otomatiki mhinduro dzeChatGPT
// @description:so      Si toos ah u ciyaar jawaabaha ChatGPT
// @description:sr      Аутоматски пуштајте одговоре ChatGPT-а
// @description:sv      Spela upp ChatGPT-svar automatiskt
// @description:sw      Chezesha majibu ya ChatGPT kiotomatiki
// @description:ta      ChatGPT பதில்களை தானாகவே இயக்கவும்
// @description:te      ChatGPT ప్రతిస్పందనలను ఆటోమేటిక్ గా ప్లే చేయండి
// @description:tg      Ба таври худкор ҷавобҳои ChatGPT-ро навозед
// @description:th      เล่นการตอบสนอง ChatGPT โดยอัตโนมัติ
// @description:ti      እቶም ምላእ ብኣውቶማቲክ ንእሽቶ ChatGPT እቶም እዩ ክንዕዘምብ እዩ
// @description:tk      ChatGPT jogaplaryny awtomatiki oýnamak
// @description:tn      Dira karabo tsa ChatGPT ka boitsamaisi
// @description:to      Tataki ke tali ʻo e ChatGPT ‘i he ngaahi fakamatala faka‘otometiki
// @description:tpi     Pleiim ol toktok blong ChatGPT olsem otomat
// @description:tr      ChatGPT yanıtlarını otomatik olarak oynat
// @description:uk      Автоматично відтворювати відповіді ChatGPT
// @description:ur      خودکار طور پر ChatGPT جوابات چلائیں
// @description:uz      ChatGPT javoblarini avtomatik ijro etish
// @description:vi      Tự động phát các phản hồi của ChatGPT
// @description:xh      Dlala iimpendulo zeChatGPT ngokuzenzekelayo
// @description:yi      שפּיל אויטאָמאַטיש ChatGPT ענטפֿערס
// @description:zh      自动播放 ChatGPT 的回复
// @description:zh-CN   自动播放 ChatGPT 的回复
// @description:zh-HK   自動播放 ChatGPT 的回覆
// @description:zh-SG   自动播放 ChatGPT 的回复
// @description:zh-TW   自動播放 ChatGPT 的回覆
// @description:zu      Dlala izimpendulo ze-ChatGPT ngokuzenzakalela
// @author              Adam Lui
// @namespace           https://github.com/adamlui
// @version             2024.11.14.2
// @license             MIT
// @icon                https://assets.chatgptautotalk.com/images/icons/openai/black/icon48.png?v=9f1ed3c
// @icon64              https://assets.chatgptautotalk.com/images/icons/openai/black/icon64.png?v=9f1ed3c
// @match               *://chatgpt.com/*
// @match               *://chat.openai.com/*
// @require             https://cdn.jsdelivr.net/npm/@kudoai/[email protected]/dist/chatgpt.min.js#sha256-rfC4kk8q0byrafp7X0Qf9vaa3JNvkHRwNnUt6uL2hUE=
// @connect             cdn.jsdelivr.net
// @connect             update.greasyfork.org
// @grant               GM_setValue
// @grant               GM_getValue
// @grant               GM_registerMenuCommand
// @grant               GM_unregisterMenuCommand
// @grant               GM_xmlhttpRequest
// @grant               GM.xmlHttpRequest
// @noframes
// @homepageURL         https://www.chatgptautotalk.com
// @supportURL          https://support.chatgptautotalk.com
// @contributionURL     https://github.com/sponsors/adamlui
// ==/UserScript==

// NOTE: This script relies on the powerful chatgpt.js library @ https://chatgpt.js.org © 2023–2024 KudoAI & contributors under the MIT license.

(async () => {

    // Init APP info
    const app = {
        name: 'ChatGPT Auto-Talk', symbol: '📣', configKeyPrefix: 'chatGPTautoTalk',
        author: { name: 'Adam Lui', url: 'https://github.com/adamlui' },
        urls: {
            chatgptJS: 'https://chatgpt.js.org',
            donate: {
                cashApp: 'https://cash.app/$adamlui',
                gitHub: 'https://github.com/sponsors/adamlui',
                payPal: 'https://paypal.me/adamlui'
            },
            gitHub: 'https://github.com/adamlui/chatgpt-auto-talk',
            greasyFork: 'https://greasyfork.org/en/scripts/500940-chatgpt-auto-talk',
            relatedApps: 'https://github.com/adamlui/ai-web-extensions',
            review: { greasyFork: 'https://greasyfork.org/en/scripts/500940-chatgpt-auto-talk/feedback#post-discussion' },
            support: 'https://support.chatgptautotalk.com'
        },
        latestAssetCommitHash: '1104341' // for cached messages.json + navicon
    }
    app.urls.assetHost = app.urls.gitHub.replace('github.com', 'cdn.jsdelivr.net/gh') + `@${app.latestAssetCommitHash}`
    app.urls.update = app.urls.greasyFork.replace('https://', 'https://update.')
        .replace(/(\d+)-?([a-z-]*)$/i, (_, id, name) => `${id}/${ name || 'script' }.meta.js`)

    // Init ENV info
    const env = {
        browser: { isMobile: chatgpt.browser.isMobile(), isFF: chatgpt.browser.isFirefox() },
        scriptManager: (() => { try { return GM_info.scriptHandler } catch (err) { return 'unknown' }})()
    }

    // Init CONFIG
    const config = { userLanguage: chatgpt.getUserLanguage() }
    const settings = {
        load(...keys) {
            if (Array.isArray(keys[0])) keys = keys[0] // use 1st array arg, else all comma-separated ones
            keys.forEach(key => config[key] = GM_getValue(app.configKeyPrefix + '_' + key, false))
        },
        save(key, value) { GM_setValue(app.configKeyPrefix + '_' + key, value) ; config[key] = value }
    } ; settings.load('autoTalkDisabled', 'toggleHidden')

    // Init app MESSAGES
    const xhr = env.scriptManager == 'OrangeMonkey' ? GM_xmlhttpRequest : GM.xmlHttpRequest
    app.msgs = {
        appName: app.name,
        appAuthor: app.author.name,
        appDesc: 'Automatically play ChatGPT responses',
        menuLabel_toggleVis: 'Toggle Visibility',
        menuLabel_about: 'About',
        menuLabel_donate: 'Please send a donation',
        about_version: 'Version',
        about_poweredBy: 'Powered by',
        about_sourceCode: 'Source code',
        mode_autoTalk: 'Auto-Talk',
        alert_updateAvail: 'Update available',
        alert_newerVer: 'An update to',
        alert_isAvail: 'is available',
        alert_upToDate: 'Up-to-date',
        alert_showYourSupport: 'Show your support',
        alert_isOSS: 'is open-source software built & maintained for free through 100% volunteer efforts',
        alert_despiteAffliction: 'Despite being severely afflicted by',
        alert_longCOVID: 'long COVID',
        alert_since2020: 'since 2020',
        alert_byDonatingResults: 'by donating, you help me to continue improving, fixing bugs, adding new features, and making the software even better',
        alert_yourContrib: 'Your contribution',
        alert_noMatterSize: 'no matter the size',
        alert_directlySupports: 'directly supports my unpaid efforts to ensure this project remains free and open for all to use',
        alert_tyForSupport: 'Thank you for your support',
        alert_author: 'author',
        alert_isUpToDate: 'is up-to-date',
        btnLabel_moreApps: 'More ChatGPT Apps',
        btnLabel_rateUs: 'Rate Us',
        btnLabel_getSupport: 'Get Support',
        btnLabel_updateCheck: 'Check for Updates',
        btnLabel_update: 'Update',
        btnLabel_dismiss: 'Dismiss',
        link_viewChanges: 'View changes',
        state_enabled: 'enabled',
        state_disabled: 'disabled',
        state_on: 'on',
        state_off: 'off'
    }
    if (!config.userLanguage.startsWith('en')) { // localize msgs for non-English users
        const localizedMsgs = await new Promise(resolve => {
            const msgHostDir = app.urls.assetHost + '/greasemonkey/_locales/',
                  msgLocaleDir = ( config.userLanguage ? config.userLanguage.replace('-', '_') : 'en' ) + '/'
            let msgHref = msgHostDir + msgLocaleDir + 'messages.json', msgXHRtries = 0
            function fetchMsgs() { xhr({ method: 'GET', url: msgHref, onload: handleMsgs })}
            function handleMsgs(resp) {
                try { // to return localized messages.json
                    const msgs = JSON.parse(resp.responseText), flatMsgs = {}
                    for (const key in msgs)  // remove need to ref nested keys
                        if (typeof msgs[key] == 'object' && 'message' in msgs[key])
                            flatMsgs[key] = msgs[key].message
                    resolve(flatMsgs)
                } catch (err) { // if bad response
                    msgXHRtries++ ; if (msgXHRtries == 3) return resolve({}) // try up to 3X (original/region-stripped/EN) only
                    msgHref = config.userLanguage.includes('-') && msgXHRtries == 1 ? // if regional lang on 1st try...
                        msgHref.replace(/([^_]+_[^_]+)_[^/]*(\/.*)/, '$1$2') // ...strip region before retrying
                            : ( msgHostDir + 'en/messages.json' ) // else use default English messages
                    fetchMsgs()
                }
            }
            fetchMsgs()
        })
        Object.assign(app.msgs, localizedMsgs)
    }

    // Define MENU functions
    
    const menu = {
        ids: [], state: {
            symbols: ['❌', '✔️'], separator: env.scriptManager == 'Tampermonkey' ? ' — ' : ': ',
            words: [app.msgs.state_off.toUpperCase(), app.msgs.state_on.toUpperCase()]
        },

        register() {

            // Add Auto-Talk toggle
            const atLabel = menu.state.symbols[+!config.autoTalkDisabled] + ' '
                          + ( app.msgs.mode_autoTalk )
                          + menu.state.separator + menu.state.words[+!config.autoTalkDisabled]
            menu.ids.push(GM_registerMenuCommand(atLabel, () => document.getElementById('auto-talk-toggle-label').click()))

            // Add Toggle Visibility toggle
            const tvLabel = menu.state.symbols[+!config.toggleHidden] + ' '
                          + ( app.msgs.menuLabel_toggleVis )
                          + menu.state.separator + menu.state.words[+!config.toggleHidden]
            menu.ids.push(GM_registerMenuCommand(tvLabel, () => {
                settings.save('toggleHidden', !config.toggleHidden)
                navToggleDiv.style.display = config.toggleHidden ? 'none' : 'flex' // toggle visibility
                notify(`${app.msgs.menuLabel_toggleVis}: ${menu.state.words[+!config.toggleHidden]}`)
                menu.refresh()
            }))

            // Add About entry
            const aboutLabel = `💡 ${app.msgs.menuLabel_about} ${app.msgs.appName}`
            menu.ids.push(GM_registerMenuCommand(aboutLabel, modals.about.show))

            // Add Donate entry
            const donateLabel = `💖 ${app.msgs.menuLabel_donate}`
            menu.ids.push(GM_registerMenuCommand(donateLabel, modals.donate.show))
        },

        refresh() {
            if (env.scriptManager == 'OrangeMonkey') return
            for (const id of menu.ids) { GM_unregisterMenuCommand(id) } menu.register()
        }
    }

    function updateCheck() {

        // Fetch latest meta
        const currentVer = GM_info.script.version
        xhr({
            method: 'GET', url: app.urls.update + '?t=' + Date.now(),
            headers: { 'Cache-Control': 'no-cache' },
            onload: response => { const updateAlertWidth = 377

                // Compare versions
                const latestVer = /@version +(.*)/.exec(response.responseText)[1]
                for (let i = 0 ; i < 4 ; i++) { // loop thru subver's
                    const currentSubVer = parseInt(currentVer.split('.')[i], 10) || 0,
                          latestSubVer = parseInt(latestVer.split('.')[i], 10) || 0
                    if (currentSubVer > latestSubVer) break // out of comparison since not outdated
                    else if (latestSubVer > currentSubVer) { // if outdated

                        // Alert to update
                        const updateModalID = siteAlert(`🚀 ${app.msgs.alert_updateAvail}!`, // title
                            `${app.msgs.alert_newerVer} ${app.msgs.appName} `
                                + `(v${latestVer}) ${app.msgs.alert_isAvail}!  `
                                + '<a target="_blank" rel="noopener" style="font-size: 0.7rem" '
                                    + 'href="' + app.urls.gitHub + '/commits/main/greasemonkey/'
                                    + app.urls.update.replace(/[^/]*\/([^/]*?)meta\.js/, '$1user.js') + '"'
                                    + `> ${app.msgs.link_viewChanges}</a>`,
                            function update() { // button
                                modals.safeWinOpen(app.urls.update.replace('meta.js', 'user.js') + '?t=' + Date.now())
                            }, '', updateAlertWidth
                        )

                        // Localize button labels if needed
                        if (!config.userLanguage.startsWith('en')) {
                            const updateAlert = document.querySelector(`[id="${updateModalID}"]`),
                                  updateBtns = updateAlert.querySelectorAll('button')
                            updateBtns[1].textContent = app.msgs.btnLabel_update
                            updateBtns[0].textContent = app.msgs.btnLabel_dismiss
                        }

                        return
                }}

                // Alert to no update, return to About modal
                siteAlert(`${app.msgs.alert_upToDate}!`, // title
                    `${app.msgs.appName} (v${currentVer}) ${app.msgs.alert_isUpToDate}!`, // msg
                    '', '', updateAlertWidth
                )
                modals.about.show()
    }})}

    // Define FEEDBACK functions

    function notify(msg, pos = '', notifDuration = '', shadow = '') {

        // Strip state word to append colored one later
        const foundState = menu.state.words.find(word => msg.includes(word))
        if (foundState) msg = msg.replace(foundState, '')

        // Show notification
        chatgpt.notify(`${app.symbol} ${msg}`, pos, notifDuration, shadow || chatgpt.isDarkMode() ? '' : 'shadow')
        const notif = document.querySelector('.chatgpt-notif:last-child')

        // Append styled state word
        if (foundState) {
            const styledStateSpan = document.createElement('span')
            styledStateSpan.style.cssText = `color: ${
                foundState == menu.state.words[0] ? '#ef4848 ; text-shadow: rgba(255, 169, 225, 0.44) 2px 1px 5px'
                                                : '#5cef48 ; text-shadow: rgba(255, 250, 169, 0.38) 2px 1px 5px' }`
            styledStateSpan.append(foundState) ; notif.append(styledStateSpan)
        }
    }

    function siteAlert(title = '', msg = '', btns = '', checkbox = '', width = '') {
        return chatgpt.alert(title, msg, btns, checkbox, width )}

    // Define MODAL functions

    const modals = {

        about: {
            show() {

                // Show alert
                const chatgptJSver = (/chatgpt-([\d.]+)\.min/.exec(GM_info.script.header) || [null, ''])[1],
                      headingStyle = 'font-size: 1.15rem',
                      pStyle = 'position: relative ; left: 3px',
                      pBrStyle = 'position: relative ; left: 4px ',
                      aStyle = 'color: ' + ( chatgpt.isDarkMode() ? '#c67afb' : '#8325c4' ) // purple
                const aboutModalID = siteAlert(
                    app.msgs.appName, // title
                    `<span style="${headingStyle}"><b>🏷️ <i>${app.msgs.about_version}</i></b>: </span>`
                        + `<span style="${pStyle}">${GM_info.script.version}</span>\n`
                    + `<span style="${headingStyle}"><b>⚡ <i>${app.msgs.about_poweredBy}</i></b>: </span>`
                        + `<span style="${pStyle}"><a style="${aStyle}" href="${app.urls.chatgptJS}" target="_blank" rel="noopener">`
                        + 'chatgpt.js</a>' + ( chatgptJSver ? ( ' v' + chatgptJSver ) : '' ) + '</span>\n'
                    + `<span style="${headingStyle}"><b>📜 <i>${app.msgs.about_sourceCode}</i></b>:</span>\n`
                        + `<span style="${pBrStyle}"><a href="${app.urls.gitHub}" target="_blank" rel="nopener">`
                        + app.urls.gitHub + '</a></span>',
                    [ // buttons
                        function checkForUpdates() { updateCheck() },
                        function getSupport() { modals.safeWinOpen(app.urls.support) },
                        function rateUs() { modals.safeWinOpen(app.urls.review.greasyFork) },
                        function moreChatGPTapps() { modals.safeWinOpen(app.urls.relatedApps) }
                    ], '', 478 // set width
                )
        
                // Re-format buttons to include emoji + localized label + hide Dismiss button
                for (const button of document.getElementById(aboutModalID).querySelectorAll('button')) {
                    if (/updates/i.test(button.textContent)) button.textContent = (
                        '🚀 ' + ( app.msgs.btnLabel_updateCheck ))
                    else if (/support/i.test(button.textContent)) button.textContent = (
                        '🧠 ' + ( app.msgs.btnLabel_getSupport ))
                    else if (/rate/i.test(button.textContent)) button.textContent = (
                        '⭐ ' + ( app.msgs.btnLabel_rateUs ))
                    else if (/apps/i.test(button.textContent)) button.textContent = (
                        '🤖 ' + ( app.msgs.btnLabel_moreApps ))
                    else button.style.display = 'none' // hide Dismiss button
                }
            }
        },

        donate: {
            longCOVIDwikiLink: 'https://en.wikipedia.org/wiki/Long_COVID',

            show() {

                // Show alert
                const donateModalID = siteAlert(
                    `💖 ${app.msgs.alert_showYourSupport}`, // title
                        `<p>${app.msgs.appName} ${app.msgs.alert_isOSS}.</p>`
                      + `<p>${app.msgs.alert_despiteAffliction} `
                          + `<a target="_blank" rel="noopener" href="${modals.donate.longCOVIDwikiLink}">${app.msgs.alert_longCOVID}</a> `
                          + `${app.msgs.alert_since2020}, ${app.msgs.alert_byDonatingResults}.</p>`
                      + `<p>${app.msgs.alert_yourContrib}, <b>${app.msgs.alert_noMatterSize}</b>, ${app.msgs.alert_directlySupports}.</p>`
                      + `<p>${app.msgs.alert_tyForSupport}!</p>`
                      + `<img src="https://cdn.jsdelivr.net/gh/adamlui/adamlui/images/siggie/${ chatgpt.isDarkMode() ? 'white' : 'black' }.png"`
                          + ' style="height: 54px ; margin: 5px 0 -2px 5px"></img>'
                      + `<p>—<b><a target="_blank" rel="noopener" href="${app.author.url}">${app.msgs.appAuthor}</a></b>, ${app.msgs.alert_author}</p>`,
                    [ // buttons
                        function paypal() { modals.safeWinOpen(app.urls.donate.payPal) },
                        function githubSponsors() { modals.safeWinOpen(app.urls.donate.gitHub) },
                        function cashApp() { modals.safeWinOpen(app.urls.donate.cashApp) },
                        function rateUs() { modals.safeWinOpen(app.urls.review.greasyFork) }
                    ], '', 478 // set width
                )

                // Format text
                const donateModal = document.getElementById(donateModalID)
                donateModal.querySelectorAll('p').forEach(p => // v-pad text, shrink line height
                    p.style.cssText = 'padding: 8px 0 ; line-height: 20px')

                // Format buttons
                const btns = donateModal.querySelectorAll('button')
                btns.forEach((btn, idx) => {
                    if (idx == 0) btn.style.display = 'none' // hide Dismiss button
                    else {
                        btn.style.cssText = 'padding: 8px 6px !important ; margin-top: -14px ; width: 107px ; line-height: 14px'
                        if (idx == btns.length -1) // de-emphasize right-most button
                            btn.classList.remove('primary-modal-btn')
                        else if (/rate/i.test(btn.textContent)) // localize 'Rate Us' label
                            btn.textContent = app.msgs.btnLabel_rateUs
                    }
                })
            }
        },

        safeWinOpen(url) { open(url, '_blank', 'noopener') } // to prevent backdoor vulnerabilities
    }

    // Define UI functions

    const navToggle = {
        insert() {

            // Insert toggle
            const toggleParent = document.querySelector('nav')
            if (!toggleParent.contains(navToggleDiv))
                 toggleParent.insertBefore(navToggleDiv, toggleParent.children[1])
    
            // Tweak styles
            const knobSpan = document.getElementById('auto-talk-toggle-knob-span'),
                  navicon = document.getElementById('auto-talk-toggle-navicon')
            navToggleDiv.style.flexGrow = 'unset' // overcome OpenAI .grow
            navToggleDiv.style.paddingLeft = '8px'
            if (knobSpan) knobSpan.style.boxShadow = (
                'rgba(0, 0, 0, .3) 0 1px 2px 0' + ( chatgpt.isDarkMode() ? ', rgba(0, 0, 0, .15) 0 3px 6px 2px' : '' ))
            if (navicon) navicon.src = `${ // update navicon color in case scheme changed
                app.urls.assetHost }/assets/images/icons/speaker/${
                chatgpt.isDarkMode() ? 'white' : 'black' }-icon.svg`
        },

        update() {
            if (config.toggleHidden) navToggleDiv.style.display = 'none'
            else {

                // Create/size/position navicon
                const navicon = document.getElementById('auto-talk-toggle-navicon') || document.createElement('img')
                navicon.id = 'auto-talk-toggle-navicon'
                navicon.style.width = navicon.style.height = '1.25rem'
                navicon.style.marginLeft = '2px' ; navicon.style.marginRight = '4px'
        
                // Create/ID/disable/hide/update checkbox
                const toggleInput = document.getElementById('auto-talk-toggle-input') || document.createElement('input')
                toggleInput.id = 'auto-talk-toggle-input' ; toggleInput.type = 'checkbox' ; toggleInput.disabled = true
                toggleInput.style.display = 'none' ; toggleInput.checked = !config.autoTalkDisabled
        
                // Create/ID/stylize switch
                const switchSpan = document.getElementById('atSwitchSpan') || document.createElement('span')
                switchSpan.id = 'atSwitchSpan'
                const switchStyles = {
                    position: 'relative', left: `${ env.browser.isMobile ? 211 : !ui.firstLink ? 160 : 154 }px`,
                    backgroundColor: toggleInput.checked ? '#ccc' : '#AD68FF', // init opposite  final color
                    bottom: `${ !ui.firstLink ? -0.15 : env.browser.isFF ? 0.05 : 0 }em`,
                    width: '30px', height: '15px', '-webkit-transition': '.4s', transition: '0.4s',  borderRadius: '28px'
                }
                Object.assign(switchSpan.style, switchStyles)
        
                // Create/ID/stylize knob, append to switch
                const knobSpan = document.getElementById('auto-talk-toggle-knob-span') || document.createElement('span')
                knobSpan.id = 'auto-talk-toggle-knob-span'
                const knobStyles = {
                    position: 'absolute', left: '3px', bottom: '1.25px',
                    width: '12px', height: '12px', content: '""', borderRadius: '28px',
                    transform: toggleInput.checked ? // init opposite final pos
                        'translateX(0)' : 'translateX(13px) translateY(0)',
                    backgroundColor: 'white',  '-webkit-transition': '0.4s', transition: '0.4s'
                }
                Object.assign(knobSpan.style, knobStyles) ; switchSpan.append(knobSpan)
        
                // Create/ID/stylize/fill label
                const toggleLabel = document.getElementById('auto-talk-toggle-label') || document.createElement('label')
                toggleLabel.id = 'auto-talk-toggle-label'
                if (!ui.firstLink) { // add font size/weight since no ui.firstLink to borrow from
                    toggleLabel.style.fontSize = '0.875rem' ; toggleLabel.style.fontWeight = 600 }
                toggleLabel.style.marginLeft = `-${ !ui.firstLink ? 23 : 41 }px` // left-shift to navicon
                toggleLabel.style.cursor = 'pointer' // add finger cursor on hover
                toggleLabel.style.width = `${ env.browser.isMobile ? 201 : 148 }px` // to truncate overflown text
                toggleLabel.style.overflow = 'hidden' // to truncate overflown text
                toggleLabel.style.textOverflow = 'ellipsis' // to truncate overflown text
                toggleLabel.innerText = ( app.msgs.mode_autoTalk ) + ' '
                                    + ( toggleInput.checked ? ( app.msgs.state_enabled  || 'enabled' )
                                                            : ( app.msgs.state_disabled ))
                // Append elements
                for (const elem of [navicon, toggleInput, switchSpan, toggleLabel]) navToggleDiv.append(elem)
        
                // Update visual state
                navToggleDiv.style.display = 'flex'
                setTimeout(() => {
                    switchSpan.style.backgroundColor = toggleInput.checked ? '#ad68ff' : '#ccc'
                    switchSpan.style.boxShadow = toggleInput.checked ? '2px 1px 9px #d8a9ff' : 'none'
                    knobSpan.style.transform = toggleInput.checked ? 'translateX(13px) translateY(0)' : 'translateX(0)'
                }, 1) // min delay to trigger transition fx
            }
        }
    }

    // Run MAIN routine

    menu.register() // create browser toolbar menu

    // Init BROWSER/UI props
    await Promise.race([chatgpt.isLoaded(), new Promise(resolve => setTimeout(resolve, 5000))]) // initial UI loaded
    await chatgpt.sidebar.isLoaded()
    const ui = { firstLink: chatgpt.getNewChatLink() }

    // Add/update TWEAKS style
    const tweaksStyleUpdated = 20241002 // datestamp of last edit for this file's `tweaksStyle`
    let tweaksStyle = document.getElementById('tweaks-style') // try to select existing style
    if (!tweaksStyle || parseInt(tweaksStyle.getAttribute('last-updated'), 10) < tweaksStyleUpdated) { // if missing or outdated
        if (!tweaksStyle) { // outright missing, create/id/attr/append it first
            tweaksStyle = document.createElement('style') ; tweaksStyle.id = 'tweaks-style'
            tweaksStyle.setAttribute('last-updated', tweaksStyleUpdated.toString())
            document.head.append(tweaksStyle)
        }
        tweaksStyle.innerText = (
            ( chatgpt.isDarkMode() ? '.chatgpt-modal > div { border: 1px solid white }' : '' )
          + '.chatgpt-modal button {'
              + 'font-size: 0.77rem ; text-transform: uppercase ;' // shrink/uppercase labels
              + `border: 2px dashed ${ chatgpt.isDarkMode() ? 'white' : 'black' } !important ; border-radius: 0 !important ;` // thiccen/square/dash borders
              + 'transition: transform 0.1s ease-in-out, box-shadow 0.1s ease-in-out ;' // smoothen hover fx
              + 'cursor: pointer !important ;' // add finger cursor
              + 'padding: 5px !important ; min-width: 102px }' // resize
          + '.chatgpt-modal button:hover {' // add zoom, re-scheme
              + 'transform: scale(1.055) ;'
              + ( chatgpt.isDarkMode() ? 'background-color: #2cff00 !important ; box-shadow: 2px 1px 54px #38ff00 !important ; color: black !important'
                                       : 'background-color: #c7ff006b !important ; box-shadow: 2px 1px 30px #97ff006b !important' ) + '}'
          + '.modal-buttons { margin-left: -13px !important }'
          + '* { scrollbar-width: thin }' // make FF scrollbar skinny to not crop toggle
        )
    }

    // Stylize ALERTS
    if (!document.getElementById('chatgpt-alert-override-style')) {
        const chatgptAlertStyle = document.createElement('style')
        chatgptAlertStyle.id = 'chatgpt-alert-override-style'
        chatgptAlertStyle.innerText = (
            ( chatgpt.isDarkMode() ? '.chatgpt-modal > div { border: 1px solid white }' : '' )
          + '.chatgpt-modal button {'
              + 'font-size: 0.77rem ; text-transform: uppercase ;'
              + 'border-radius: 0 !important ; padding: 5px !important ; min-width: 102px }'
          + '.modal-buttons { margin-left: -13px !important }'
        )
        document.head.append(chatgptAlertStyle)
    }

    // Create NAV TOGGLE div, add styles
    const navToggleDiv = document.createElement('div')
    navToggleDiv.style.height = '37px'
    navToggleDiv.style.margin = '2px 0' // add v-margins
    navToggleDiv.style.userSelect = 'none' // prevent highlighting
    navToggleDiv.style.cursor = 'pointer' // add finger cursor
    navToggle.update() // create children
    if (ui.firstLink) { // borrow/assign CLASSES from sidebar div
        const firstIcon = ui.firstLink.querySelector('div:first-child'),
              firstLabel = ui.firstLink.querySelector('div:nth-child(2)')
        navToggleDiv.classList.add(...ui.firstLink.classList, ...(firstLabel?.classList || []))
        navToggleDiv.querySelector('img')?.classList.add(...(firstIcon?.classList || []))
    }

    navToggle.insert()

    // Add LISTENER to toggle switch/label/config/menu
    navToggleDiv.onclick = () => {
        const toggleInput = document.getElementById('auto-talk-toggle-input')
        toggleInput.checked = !toggleInput.checked ; config.autoTalkDisabled = !toggleInput.checked
        navToggle.update() ; menu.refresh()
        notify(`${app.msgs.mode_autoTalk}: ${menu.state.words[+!config.autoTalkDisabled]}`)
        settings.save('autoTalkDisabled', config.autoTalkDisabled)
    }

    // Observe <main> for need to AUTO-PLAY response
    await Promise.race([chatgpt.isLoaded(), new Promise(resolve => setTimeout(resolve, 1000))])
    const autoPlayObserver = new MutationObserver(mutations => {
        if (config.autoTalkDisabled) return
        for (const mutation of mutations) { if (mutation.type === 'childList')
            mutation.addedNodes.forEach(node => { if (node?.tagName == 'DIV') {
                const playIcon = node.querySelector('path[d^="M11 4.9099C11"]')
                if (playIcon) setTimeout(() => {
                    if (!chatgpt.getStopGeneratingButton())
                        playIcon.closest('button').click()
                }, 50)
    }})}})
    autoPlayObserver.observe(document.querySelector('main'), { childList: true, subtree: true })

    // Monitor <html> to maintain NAV TOGGLE VISIBILITY on node changes
    new MutationObserver(mutations => mutations.forEach(mutation => {
        if (mutation.type == 'childList' && mutation.addedNodes.length && !config.toggleHidden)
            navToggle.insert()
    })).observe(document.documentElement, { childList: true, subtree: true })

    // Disable distracting SIDEBAR CLICK-ZOOM effect
    if (!document.querySelector('[sidebar-click-zoom-observed]')) {
        new MutationObserver(mutations => mutations.forEach(({ target }) => {
            if (target.closest('[class*="sidebar"]') // include sidebar divs
                && !target.id.endsWith('-knob-span') // exclude our navToggle
                && target.style.transform != 'none' // click-zoom occurred
            ) target.style.transform = 'none'
        })).observe(document.body, { attributes: true, subtree: true, attributeFilter: [ 'style' ]})      
        document.documentElement.setAttribute('sidebar-click-zoom-observed', true)
    }

})()