Устаць па тэлефон? Лепш напішам дадатак

Сяджу сабе на чыле з ноўтам. На тэлефон павінен прыйсці код. Засталося толькі ўстаць, знайсці тэлефон, разблакаваць яго і перапісаць некалькі лічбаў.
Але так лянота.
Мы ж не слабакі, каб проста схадзіць па тэлефон. Мы — тыя, каго называюць чумой праграмавання. Нас хэйцілі яшчэ тады, калі мы толькі пісалі «прывітанне» ў чат з ШІ. Мы — вайбкодзеры.
Таму замест дзвюх хвілін на пошук тэлефона я выбраў цалкам разумны шлях: зрабіць асобны Android-дадатак. Каб ён збіраў новыя SMS з маіх тэлефонаў і дасылаў іх мне ў Telegram. Бо калі тэлефонаў некалькі, хадзіць па кожны — гэта ўжо кардыё. А я тут увогуле сядзець прыйшоў.
Так лянота і ШІ падштурхнулі мяне аўтаматызаваць паход па код. Колькі часу на гэтым зэканоміў — пытанне спрэчнае. Затое цяпер можна не ўставаць. Амаль: наладзіць усё адзін раз усё ж давядзецца.
Ніжэй — што робіць дадатак, як яго наладзіць і промпт для тых, хто таксама лічыць адлегласць да тэлефона тэхнічнай праблемай.
Што прыходзіць у Telegram
Разам з тэкстам SMS дадатак дасылае адпраўніка, час атрымання і звесткі пра SIM-карту. Калі нумар ёсць у кантактах і доступ да іх дазволены, замест нумара будзе імя чалавека. Калі дазволу няма, перасылка ўсё адно працуе.
Нумар сваёй SIM можна ўвесці ўручную: Android не заўсёды ўмее яго вызначыць. Калі паведамленні збіраюцца з некалькіх тэлефонаў, хочацца адразу разумець, на які нумар яны прыйшлі.
Трымаць дадатак адкрытым не трэба: прыём і адпраўка працуюць у фоне. Калі знікае інтэрнэт, паведамленні захоўваюцца ў зашыфраванай чарзе і чакаюць наступнай спробы адпраўкі. Праўда, Android можа адкладаць фонавыя задачы дзеля эканоміі батарэі, таму імгненная дастаўка не гарантуецца.
SMS і RCS: што ўлічыць
У Google Messages SMS і RCS могуць выглядаць амаль аднолькава, але для Android гэта розныя спосабы абмену паведамленнямі. Таму аднаго дазволу на прыём SMS недастаткова, каб перасылаць яшчэ і RCS.
Для SMS дадатак выкарыстоўвае сістэмны механізм Android. Для RCS ёсць асобны рэжым: ён бярэ тэкст з новых апавяшчэнняў Google Messages. Карыстальнік павінен дазволіць доступ да апавяшчэнняў у наладах тэлефона.
У гэтага спосабу ёсць абмежаванні. Калі чат адкрыты, апавяшчэнні выключаныя або сістэма хавае іх змесціва, паведамленне можа не трапіць у перасылку. Нумар SIM з апавяшчэння таксама можа быць недаступны. Таму перад штодзённым выкарыстаннем варта асобна праверыць і SMS, і RCS на сваім тэлефоне.
Як наладзіць у сябе
Гатовым APK тут не дзелімся: ніжэй ёсць самадастатковы промпт для агента, які ўмее ствараць файлы і запускаць зборку Android. Спачатку дайце яму сабраць дадатак, а затым наладзьце бота:
- Стварыце бота праз @BotFather. Адпраўце каманду
/newbot, прайдзіце кароткую наладку і скапіруйце токен — ключ доступу да бота. - Напішыце свайму боту. Адкрыйце яго ў Telegram, націсніце Start і адпраўце любое паведамленне.
- Знайдзіце ID чата. У браўзеры адкрыйце
https://api.telegram.org/botТОКЕН/getUpdates, падставіўшы свой токен. У адказе патрэбная лічба знаходзіцца ўmessage.chat.id; побач павінна быць"type":"private". Калі бачыце"result":[], напішыце боту яшчэ раз і абнавіце старонку. - Усталюйце APK на тэлефон, з якога хочаце перасылаць паведамленні. Увядзіце токен і ID чата. Telegram на гэтым тэлефоне не патрэбны. Даныя можна ўвесці ўручную або перанесці з камп’ютара праз USB з дапамогай ADB.
- Пацвердзіце чат і ўключыце перасылку. Націсніце «Адправіць тэставае паведамленне», увядзіце код з Telegram і захавайце налады. Затым націсніце «Уключыць перасылку» і дазвольце прыём SMS. У раздзеле SIM пры патрэбе ўвядзіце свой нумар.
- Калі патрэбны RCS, уключыце і яго. Націсніце «Дазволіць доступ да апавяшчэнняў», дайце дазвол у Android, вярніцеся ў дадатак і выберыце «Уключыць RCS з апавяшчэнняў».
Пасля наладкі адпраўце на тэлефон сапраўдную SMS, а затым асобна RCS. Для другога тэсту пакіньце чат у Google Messages закрытым, каб з’явілася апавяшчэнне. Дайце дадатку крыху часу: апрацоўка апавяшчэнняў пачынаецца не раней чым праз 20 секунд, а Android можа затрымаць яе яшчэ.
На астатніх тэлефонах паўтарыце тыя ж крокі. Бот і асабісты чат могуць быць агульнымі.
Пра што варта памятаць
Перасылаюцца ўсе новыя ўваходныя SMS, у тым ліку аднаразовыя коды ўваходу. Таму токен бота нельга перадаваць іншым, а доступ да Telegram-акаўнта трэба берагчы. У самім дадатку токен і чарга захоўваюцца ў зашыфраваным выглядзе.
Прыбіраць дадатак са спісу апошніх можна. А вось пасля кнопкі «Прымусова спыніць» у наладах Android яго трэба адкрыць зноў.
Перад тым як разлічваць на перасылку, праверце яе ў звычайных умовах: з выключаным экранам, без інтэрнэту і пасля аднаўлення сувязі. Тэставае паведамленне ад бота пацвярджае доступ да Telegram-чата; прыём сапраўднай SMS або RCS трэба праверыць асобна.
Промпт для стварэння свайго дадатку
Скапіруйце тэкст цалкам у агента з доступам да файлаў і тэрмінала. Ён павінен стварыць праект і сабраць APK на вашым камп’ютары. Звычайны чат без інструментаў зборкі можа толькі напісаць код. Токен бота ў промпт устаўляць не трэба — ён уводзіцца ў гатовым дадатку.
text1Build a complete Android application from scratch in the current workspace. 2Use React Native with TypeScript for the settings screen and Kotlin for native 3SMS reception, notification access, persistent storage, and background delivery. 4Write the actual files, run the build, fix errors, and deliver an installable APK. 5Do not stop at a plan, code snippets, or an unverified claim that it should work. 6This prompt is the full specification; no existing project or README is provided. 7 8PURPOSE 9I own several Android phones and want their new incoming SMS messages forwarded 10to one verified private chat with my Telegram bot. Telegram does not need to be 11installed on the source phones. Also provide an optional, explicitly enabled 12mode that forwards incoming text exposed by Google Messages notifications, 13so that RCS messages can be forwarded when such notifications are available. 14 15IMPLEMENTATION AND BUILD 16- Inspect the workspace and available Node.js, JDK, Android SDK, Gradle, and ADB 17 before making changes. Preserve unrelated files and existing user data. 18- Choose mutually compatible, currently supported stable React Native, React, 19 Kotlin, Android Gradle Plugin, and Gradle versions. Consult official docs 20 when needed. Do not blindly use old versions or assume Java/SDK paths. 21- Include a package lockfile, Gradle Wrapper scripts and JAR, manifest, resources, 22 native module registration, and all configuration required to build from source. 23- The app must support Android 8.0/API 26 and newer, including modern Android 24 background restrictions, runtime permissions, system-bar insets, and 16 KB 25 memory pages. Use a theme compatible with ReactActivity/AppCompat. 26- A debug APK must include its JavaScript bundle and required runtime libraries. 27 It must launch without Metro, a development server, or a computer connection. 28 29SMS RECEPTION 30- Receive SMS in a manifest-declared Kotlin BroadcastReceiver. Do not rely on 31 JavaScript, an open activity, polling, or a continuously running JS process. 32- Ask for RECEIVE_SMS only when the user enables forwarding. Do not request 33 READ_SMS or SEND_SMS and do not import historical messages. 34- Forward every new incoming SMS received after enabling; apply no sender, 35 content, or OTP filters. Assemble multipart SMS into one logical message. 36- Keep the receiver short: persist the message durably before finishing its 37 asynchronous work, and perform network requests in WorkManager instead. 38- Resolve numeric senders to contact names only if READ_CONTACTS is granted. 39 Otherwise preserve the original sender. Preserve service names such as 40 INPOST and short codes. Contact access must remain optional. 41- Determine the receiving subscription and SIM slot where possible. Provide 42 manual phone-number overrides for each active SIM/eSIM, keyed by subscription 43 identity rather than only list position. Manual values take precedence. 44 Handle missing permissions, unavailable numbers, and SIM replacement safely. 45 Never guess the receiving SIM or invent its phone number. 46 47TELEGRAM FORMAT 48Use plain text, for example: 49📩 Новая SMS 50Прылада: Home phone 51На нумар +48 XXX XXX XXX · SIM 1 52Адпраўнік Аляксей Каваль 53Атрымана 14.11.2026, 16:42 54Буду праз 10 хвілін. 55 56Use the actual sender, local receipt time, and body. Use “SIM не вызначана” 57when the receiving SIM cannot be determined. Include an editable device label 58so messages from several phones can be distinguished. Split messages exceeding 59Telegram's text limit without losing content or breaking Unicode characters. 60 61OPTIONAL GOOGLE MESSAGES NOTIFICATION MODE 62- Use a native NotificationListenerService with a separate opt-in setting. 63 The user must grant notification access in Android settings themselves. 64- Process only notifications from com.google.android.apps.messaging. 65 Do not collect notifications from Telegram or other apps. 66- Extract individual incoming text messages from structured MessagingStyle 67 notifications. Ignore summaries, historical entries from before opt-in, 68 local replies, and attachment-only entries with no available text. 69- Persistently deduplicate notification updates. Minimize double forwarding 70 when a native SMS also appears as a Google Messages notification. Use bounded 71 correlation and document its limits; identical legitimate messages must not 72 be suppressed forever. Handle process death and concurrent workers safely. 73- Clearly label this source as a Google Messages notification (RCS/SMS), since 74 the notification may not reliably identify the transport. Use the displayed 75 sender and mark the SIM as unknown unless reliable metadata is available. 76- Explain in the UI that this is not direct access to the RCS database: 77 an open conversation, disabled notifications, hidden/redacted content, or OS 78 restrictions can cause missed messages. Do not promise all RCS messages, 79 attachment forwarding, exact SIM identification, or perfect deduplication. 80- Do not use root, Accessibility scraping, private Google APIs, or mechanisms 81 that bypass Android permissions or sensitive-content restrictions. 82 83SECURITY, QUEUE, AND RETRIES 84- Store the bot token and queued message content encrypted at rest using 85 authenticated encryption with a key protected by Android Keystore. 86 Never hardcode credentials or put them in logs, exception messages, analytics, 87 WorkManager input data, source control, screenshots, or build artifacts. 88- Use HTTPS with normal certificate validation and finite network timeouts. 89- Use durable local storage and WorkManager with network constraints and retry 90 backoff. Handle timeouts, offline operation, Telegram rate limits including 91 retry_after, and temporary server failures without discarding messages. 92 Expose actionable, sanitized errors for invalid credentials or blocked bots. 93- Make queue transitions atomic. Avoid concurrent sends of the same entry, 94 preserve progress for split messages, and recover after process death/reboot. 95 Preserve settings, the encryption key, and the queue across APK updates. 96- Telegram sendMessage has no general exactly-once guarantee. Document that 97 a lost response or a crash after delivery can produce a duplicate. 98- Bind queued messages to the verified destination. Never silently redirect 99 an existing queue when credentials or chat settings change. Define a safe, 100 usable recovery flow for a nonempty queue with invalid credentials. 101- Disabling forwarding must stop collecting new messages and pause delivery. 102 Explain what happens to queued entries and already-running requests. 103 104PRIVATE CHAT VERIFICATION 105- Accept one private chat only; verify its identity and type using Telegram 106 getChat. Reject groups, supergroups, and channels. 107- Send a test message containing a random, short-lived confirmation code. 108 Require the user to enter that code before activating the destination. 109 Bind confirmation to the exact token/chat pair; invalidate it when those 110 fields change. Never display the expected code inside the app itself. 111- Validate all required settings before requesting permissions or enabling. 112 Do not require users to put tokens into this coding conversation. 113 114SETTINGS SCREEN 115Create one clear, scrollable screen in Belarusian with: 116- bot token with masked input and an indication when a token is already stored; 117- private chat ID, device label, and per-SIM manual number fields; 118- optional contact permission and SIM discovery controls; 119- “Адправіць тэставае паведамленне”, confirmation-code entry, and save action; 120- enable/disable forwarding, and separate notification-access/RCS controls; 121- visible verified destination, queue count including pending notifications, 122 last successful delivery time, and latest sanitized error; 123- a clear disclosure before enabling: all new messages in the selected mode, 124 including personal messages and one-time codes, go to the verified chat. 125Preserve unsaved form values across ordinary backgrounding where practical. 126Prevent Android autofill from treating the bot token as a website password. 127Recheck permissions when returning from system settings and show revoked access. 128 129VALIDATION AND DELIVERY 1301. Install dependencies and run the TypeScript check. 1312. Run ./gradlew assembleDebug from the android directory. Fix build errors 132 and verify android/app/build/outputs/apk/debug/app-debug.apk exists. 133 Check APK signing, bundled JS, and 16 KB native-library/package alignment. 1343. Add meaningful tests for queue persistence/encryption, multipart assembly, 135 notification parsing, duplicate handling, and permission-denied fallbacks. 136 Run destructive fixture tests only on isolated test storage or an emulator, 137 never against a user's real queue, credentials, contacts, or messages. 1384. If an authorized phone or emulator is available, install the APK and verify 139 cold launch without Metro. Use explicit device serials when several devices 140 are connected. Preserve app data on updates. Never uninstall a user's app 141 just to resolve an installation problem. 1425. If real devices, a configured bot, and test messages are available, verify 143 SMS from a saved contact, an unknown number, a service sender, multipart SMS, 144 offline queuing/recovery, and background receipt. Separately test an actual 145 Google Messages RCS notification. Do not claim that a bot test message or 146 a synthetic unit test proves end-to-end SMS/RCS delivery. 1476. Provide a short, self-contained setup guide: BotFather /newbot, starting a 148 private conversation, finding message.chat.id via getUpdates, handling an 149 empty result or an invalid token, confirming the chat, setting SIM numbers, 150 enabling permissions, testing SMS versus RCS, and background/force-stop limits. 151 Explain that Telegram is needed only on the device used to read the chat. 1527. Include reproducible build commands and separate instructions for a signed 153 release AAB using an upload key outside source control. Explain current 154 Google Play SMS permission declaration/eligibility requirements; do not 155 imply that a sideloadable APK is automatically eligible for Play publication. 1568. In the final response, give the absolute APK path, build result, devices 157 actually tested, scenarios verified, and remaining limitations. If the 158 environment blocks building, give the exact error and rebuild command. 159 Do not invent a successful build or an APK path that does not exist.
Каментары
Увайдзіце ў свой уліковы запіс, каб пакінуць каментар
Пакуль няма каментароў — будзьце першым!