At home we keep three “Hangzhou All-Access” benefit cards, one per person.
The platform’s rule is one booking per card per item, so a single weekend outing means running the entire flow three times: open the mini-program, pick a card, pick a venue, pick a date, pick a ticket type, confirm — then back to step one.
Three passes isn’t the hard part. The hard part is that every pass needs the same judgements re-made: is this one points-free, does it need booking a day ahead, what’s the cutoff time, has this card already hit its daily limit, have we been to this venue before, is this order refundable. A person misses one of these every time.
I wrote about the script form of this before — that piece covered “why” and “how I got there”. This one is the engineering: what finally landed is a Go CLI plus a resident Feishu bot, running on a home Linux box with no Go toolchain of its own. On Saturday morning it posts a card by itself; I tap once, and all three cards order at the same time.
1. First, collapse the goal into one sentence
Every Saturday morning the machine proposes at most three candidates; I pick one; each of the three cards books that one; and the receipt updates on that same card.
Around that sentence the boundaries were nailed down too:
- book only refundable venues; non-refundable ones are listed as a warning and never ordered automatically;
- book only points-free ones (no extra money), and merely display the ones that require topping up 福点 (Fu points);
- if the same card already has an order for the same venue on the same day, skip it;
- no captcha solving, no inventory bypass, no high-frequency polling;
- every write operation defaults to dry-run and only really fires with an explicit
--yes.
2. The overall architecture
In the end there are three processes and two kinds of trigger:
|
A few deliberate choices:
| Decision | Why |
|---|---|
| Business logic and bot split into two binaries | iwen can run alone in a terminal, dry-run, and be tested; the bot only owns “when to run it and how to show the result” |
| CLI rewritten in Go, standard library only | The target machine has no Go, and I didn’t want to install Python dependencies either; CGO_ENABLED=0 gives one static binary, scp it over and it runs |
| The bot is Go too | Feishu’s official SDK has the most complete long-connection implementation, and it needs no public callback URL |
| Build on the dev machine, run on the home server | The home server is treated as “a socket with systemd” |
Repository layout:
|
iwen.py is the earliest implementation, kept as a fallback. The Go version was required to match it byte for byte in commands, arguments, text output and JSON output — cli/format_test.go is literally a diff between the two. That way, when the bot switched from “call Python” to “call the binary”, not a single line of its parsing logic had to change.
3. The platform side: login, inventory, ordering
3.1 Ruling out the “tap it by hand” route first
The most obvious idea is UI automation, and it was disproved quickly:
- inside the WeChat mini-program,
uiautomator dumpreturns an empty accessibility tree — a single empty node of 407 bytes, no controls to grab; - the PC client’s
__APP__.wxapkgchanged its key derivation in WeChat 4.2, so the oldV1MMWXdecryption fails and decompiling goes nowhere either.
What’s left is the backend API. The method: on a Windows box, point travel.iwen1.com at localhost, run a forwarder bound to 127.0.0.1 only, install a self-signed CA, capture one complete “login + order” run to get every endpoint and parameter — and then restore everything on the spot: hosts back, root certificate deleted, forwarder killed, DNS cache flushed.
Before archiving the capture, fields must be scrubbed: the card-list response contains real name, ID number, card number and card secret. Those go neither into the repo nor into the article.
3.2 Auth: one account-level, long-lived token
The key discovery was how “plain” the login state is: every endpoint rides on a single request header, x-auth-token, plus x-from-mini: 1, with the body as application/x-www-form-urlencoded.
Two calls to POST /MiniApp/Login with different WeChat code values returned the exact same Token — which means it is account-level and long-lived: not bound to a session, not bound to a device, not requiring WeChat to be online. That one fact collapsed the cost of the whole design: no phone, no browser, no emulator.
|
Only two business codes really matter: ResultCode=100 is success, 300 means the session is dead. These two must be handled separately — early versions treated 300 as “no data”, so the order list came back empty, the script concluded “this person has never booked anything”, stopped recommending venues we’d already visited, and silently degraded for a long time. Now 300 exits with an error:
|
The response headers also tell you the age of this system: server: Microsoft-IIS/7.5, x-aspnetmvc-version: 4.0, dates in the old .NET form /Date(1777305600000)/. Which is also why TLS occasionally wobbles, so the network layer has to retry.
3.3 The endpoint map
| Purpose | Path | Key parameters |
|---|---|---|
| Card list | POST /CardGroup/GetAvailableCard |
attrationId=-1 |
| Benefit packages | POST /AttractionGroup/GetCardThemeAttractionList |
CardThemeId, userCardId |
| Package balance | POST /AttractionGroup/GetZuHePackageSummary |
parentAttractionId, userCardId |
| Venues in a package | POST /AttractionGroup/GetCardThemeAttractionZuHeList |
cardThemeId, parentAttractionId, userCardId |
| Venue detail | POST /AttractionGroup/GetAttractionGroupDetailJson |
attractionId etc. |
| Schedule and inventory | POST /AttractionGroup/GetAttractionExchangeJson |
attrId, ucardKey, ParentattractionId |
| Place an order | POST /OrderGroup/ExchangeOrderZuHe |
see below |
| Cancel | POST /OrderGroup/CancelOrderGroup |
id |
| Order history | POST /OrderGroup/GetOrderGroupList |
page, pageSize |
| Fu-point pricing | POST /PayOrder/GetPriceDetails |
{} |
| SMS code | POST /MiniApp/SendSms |
mobile |
| Code for token | POST /MiniApp/BindMobile |
openid, mobile, code |
Every endpoint returns the same envelope: ResultCode / ResultMessage / Response or List / Entity.
3.4 Inventory and specKey
GetAttractionExchangeJson is the core of the whole thing. It returns a three-level structure that maps exactly to “date → session → ticket type”:
|
So “can I book” is not read from the Status field of the venue list — it’s whether the target date has any ticket type with Stock > 0. The venue list only tells you “this one is in your package”; only the schedule endpoint tells you “is there still a place on that day”.
The CLI flattens the whole leaf set of that tree into a Live structure and pulls all ticket types for a given date on demand:
|
This call runs with tries=4, wait=2s — it’s the most exposed to TLS wobble in the whole pipeline, and it’s also the most frequent (once per venue, per card, per package), so retrying is cheaper than starting over.
3.5 Ordering takes five fields
|
No signature, no nonce, no timestamp. All the difficulty is in choosing the right four IDs, not in the request itself.
ParentattractionId is the easiest one to get wrong. The first implementation picked the package with the largest N, assuming a bigger package was safer; when the same venue sits in two packages, the server treated it as the paid tier and answered “insufficient remaining uses”. It was later changed to try packages from the smallest N upward, stopping at the first success:
|
Note tries=1: ordering is never retried. That’s an idempotency decision — on a timeout the server may already have written the order, and retrying would create two. Better to raise an error and let a human look.
After a success there’s a sleep 600ms before the next card, a small gap between the three cards rather than hammering the platform.
3.6 How “points-free” is decided
The platform displays benefit uses and Fu points intermixed, which is easy to misread. The actual rule is:
If the venue’s cheapest Fu-point tier ≤ the “pick N” of the benefit package it belongs to, one benefit use covers it outright. Above that, you pay the whole thing in Fu points (1 point = 10 yuan).
|
Two cases verified against the real thing — one free, one not:
| Venue | Cheapest Fu tier | Package | Result |
|---|---|---|---|
| Lin’an Daming Mountain | 1.9 | C, pick 3 | 1.9 ≤ 3 → points-free, order receipt shows ExchangeNumber=0.0 |
| Anji Jialebi Fantasy Land | 7 | X, pick 5 | 7 > 5 → 7 Fu points = 70 yuan |
By this rule, of the 96 venues under the current package (CardThemeId=576), 67 are points-free and 29 need topping up.
3.7 The platform’s hard constraints
These rules could only be established by testing them one at a time, and every one of them is now in code:
| Rule | How it appears in the code |
|---|---|
| Each card: at most 6 items booked per day | dayLimit = 6, count the day’s existing orders before ordering |
StepDay=1 requires booking one day ahead |
The card goes out on Saturday precisely so Sunday can be booked |
NoLaterThanTime is that day’s submission cutoff |
Some sessions close as early as 12:00 |
SupportCancel=0 means a wrong booking can’t be undone |
Filtered by default; only --allow-noncancel makes an exception |
| The same card may book the same venue only once a year | Checked against history with Status=3 |
| Three cards, same venue, same day, one order each — allowed | The premise that makes the whole design work |
| Cancelling returns the benefit use | Measured: RemainCount 2 → 3, so the flow is reversible |
| Packages have an expiry | This batch runs to 2026-12-31; package A (pick 1) is exhausted on all three cards, and packages with 0 uses left are skipped in code |
3.8 Rate limiting and caching
There is no “retry like crazy” policy — quite the opposite, it holds back everywhere:
- venues, packages and card lists are cached for 6 hours (
~/.cache/awen-iwen/), and only ordering/cancelling actively clears the relevant prefixes; - inventory is checked once a week:
/planqueries at most 12 venues,/weekat most 25, and the card shows only the top 3; - 600 ms between the three cards when ordering;
- network errors back off
2s × attempt; business errors neither back off nor retry.
4. The Feishu side: long connection, cards, commands
4.1 Why a long connection
At first I considered a group-robot webhook: trivial setup, one line of curl to send a message. But it can only “send”, not “receive” — someone has to catch the button press on the card.
Receiving events has two routes: a public callback URL, or a long connection. The house has no public IP and I didn’t want to open a port for this, so: long connection. The bot process dials out to Feishu and events arrive down that WebSocket.
The cost is a trap that’s easy to step in: one Feishu app can have only one long-connection consumer. This machine already ran a bot related to the blog, on the same app — the new bot consequently received only emoji reactions, with all messages going to the old process. The fix was to create a separate self-built app for this thing, so the two don’t interfere.
4.2 Permissions and subscriptions to enable
- the Bot capability;
- event subscriptions:
im.message.receive_v1(private messages),card.action.trigger(card interaction callbacks),application.bot.menu_v6(bot menu, optional); - permissions:
im:message(send messages),application:app_slash_command:read/write(sync slash commands); - publish a version.
In long-connection mode there’s no request URL to configure, so there’s no “callback URL verification” step either. The SDK exchanges App ID / Secret for a tenant token when connecting, and the SDK itself verifies the event envelope.
4.3 Cards: turning “the choice” into buttons
The candidate card holds at most three venues, one “Book this one” button each, and a “Skip this week” at the bottom. The structure is just Feishu card JSON:
|
value is a custom payload: when the button is pressed, the whole thing comes back inside event.action.value of the card.action.trigger event. So the bot needs no server-side state about “what did I send last time” — the date and venue ID travel with the card, and restarting or replacing the process changes nothing.
Handling a click goes “acknowledge first, work later, then update the card in place”:
|
Three details worth writing down:
- The callback must return fast. Feishu has a timeout for card callbacks, while ordering three cards takes from seconds to tens of seconds — so respond immediately with a toast, push the real work into a goroutine, and use
im.message.patchto rewrite the card when it’s done. - The double-click guard locks on message id. Clicking again while a card is mid-booking only gets a “booking in progress” toast; no duplicate order.
- The card is itself the results page. Success, partial failure, and the reasons all render on the same card, leaving exactly one entry in the chat history.

4.4 Commands: slash, backslash, Chinese aliases all accepted
Pushing the card automatically is the main path, but if you want to check something or cancel an order right now, you can’t wait until Saturday. So there’s a set of commands in private chat:
| Command | Aliases | What it does |
|---|---|---|
/week [date] |
\周末, \weekend, \去哪 |
Weather plus points-free venues that still have inventory |
/plan [date] |
\周日, \sunday |
Produce the choice card |
/orders |
\订单, \预约 |
Pending bookings, each with a cancel button |
/cancel <Id> / /cancel all |
\取消 |
Cancel one order / all of them |
/cards |
\卡, \余量 |
Remaining uses per package on the three cards |
/status |
\状态, \体检 |
Session health check (read-only) |
/help |
\帮助 |
Help |
This parsing layer looks trivial but decides whether the thing feels pleasant to use:
|
Two more real-world details:
- when the bot is @-mentioned in a group, the text carries a placeholder like
@_user_1that has to be stripped first; - commands only work in private chat. Group @-mentions do produce events, but
/cancel allreally refunds orders — that must not be mis-triggered in a group.
“Who may speak” was solved without any account system, using the bluntest method: the first time a message arrives, store the sender’s open_id in ~/.local/state/awen-iwen/admin_open_id; every other private message is ignored. The config item FEISHU_ADMIN_OPEN_ID can pre-set it.

The commands themselves also have to be registered with the open platform, or they never appear in the input box’s / suggestion list. There’s no official SDK wrapper for these, so it’s raw HTTP:
|
awen-iwen-bot slash sync upserts idempotently by command name: update the description if it exists, create if it doesn’t, and running it twice never produces duplicates. Two things to note: the command field carries no leading / and must match ^[a-z][a-z0-9_-]{0,31}$; and clicking a slash command only puts the text into the input box, so triggering still goes through im.message.receive_v1 — which means the im:message permission and a published version are mandatory.
4.5 Notifications and alerts
Outgoing messages come in three kinds:
- choice cards (the Saturday timer): interactive cards;
- receipts (button callbacks): patch the original card;
- alerts (session expired): a red error card with recovery steps.
An older channel is also kept: group-robot webhook, plain text. Its value is “it can still send when the bot process itself is dead” — iwen sunday --notify is run by cron or by hand and doesn’t depend on the long connection. When the custom robot has signing enabled, the signature is base64(HMAC-SHA256(secret, timestamp + "\n" + secret)), sent in the sign field of the body:
|
A note while we’re here: when a Feishu webhook send fails, HTTP is still 200 — the error only appears in the body’s code. Code that looks solely at the status line will believe the message went out.
5. Scheduling and reliability
5.1 systemd user units
The home server has no Docker and no supervisor, so systemd’s user instance does it: no root needed, logs appended straight to a file.
|
|
tickis oneshot: check Sunday’s weather, choose candidates, send the card, exit;serveis resident: it only receives events, withRestart=alwaysandRestartSec=5;checkis the health probe: daily at 09:30, withRandomizedDelaySec=10mso it doesn’t collide with other jobs on the hour;- every timer is
Persistent=true: if the machine was off at the time, it catches up once after boot.
There is exactly one log file, ~/logs/awen-iwen.log, and each module carries its own prefix: [tick], [card], [book], [send], [doctor], [msg], [cmd]. When something breaks, grepping one prefix is enough.
5.2 Idempotency: three questions before ordering
buildPick is the single entry point for “can this be booked”, and it checks against three datasets:
|
The three questions block three kinds of duplication: the same card booking the same venue on the same day twice, the same card visiting the same venue twice in a year, more than 6 items in one day. On the bot side there’s a further busy lock against a shaky finger.
5.3 Process shutdown has to be fast
The long-connection library is insensitive to context cancellation: after systemd sends SIGTERM, if the process doesn’t exit, stop waits until TimeoutStopSec before it kills. The deploy script stops the bot on every run, and 90 seconds of waiting is painful. So a backstop was added:
|
TimeoutStopSec=15 plus those 2 seconds turned a restart from 90 seconds into 2. The deploy script keeps one more trick: if stop hasn’t exited after two seconds, send SIGKILL — otherwise the old process keeps occupying the long connection and the new one receives nothing.
5.4 Self-healing session
The token is account-level and in theory long-lived, but the platform can invalidate it or let it expire. The full self-healing chain:
|
Three design points, all added after being bitten.
First, renew only when the server explicitly answers 300. Network wobble, TLS failure, 5xx, an empty card list all count as unknown:
|
The cost of getting this wrong is a real SMS landing on a real phone, which is annoying.
Second, at most one SMS per 30 minutes. The gate is the mtime of ~/.config/awen-iwen/sms.stamp; once renewal succeeds the session is back, so the next health check won’t fire it again — the interval only matters when renewal keeps failing and retrying.
Third, judge “a new message” by the server’s auto-increment ID, not by timestamp. An SMS date is produced on the phone with System.currentTimeMillis(); when the phone’s clock runs one or two seconds behind the server, a message that just arrived looks “older” than the moment we requested the code. On 2026-11-14 we really did lose a verification code this way. Now the code records the largest ID in the list before requesting the code, and afterwards only accepts messages with a larger ID:
|
The code itself comes from a self-hosted SMS forwarding service, GET /api/sms?limit=10 with a Bearer token, bodies encrypted with AES-256-GCM in the form base64(iv(12) || ciphertext || tag(16)). So the target machine doesn’t need cryptography, the decryption is implemented with nothing but standard libraries (Go’s crypto/aes + crypto/cipher, and the Python fallback re-implements AES in pure Python).
Measured: a full renewal takes 51 seconds, about 45 of them waiting for the SMS; when the session is healthy the check’s fast path is 0.25 seconds.
5.5 No secrets in the logs
Several hard rules:
- the token is written 0600, and only its length and sha256 prefix are printed — the value itself never appears;
open_idpasses throughmask()in logs:abcd…wxyz;- phone numbers are masked as
138****00; - message events log only “type + first 120 characters” — command text carries no secrets;
- order logs record order id, date, venue and a card alias, never an ID number.
5.6 Dry-run must intercept writes
Every write operation defaults to dry-run and needs --yes; that’s enforced at the CLI layer. The bot has a rehearsal mode as well: awen-iwen-bot cmd '\周末' doesn’t connect to Feishu and just prints what it would reply with.
There was an incident here: the rehearsal mode originally blocked only “sending messages”, not iwen‘s write operations. A local rehearsal of \取消全部 really did cancel three pending bookings. Now guardWrite inspects the subcommand and its arguments before executing:
|
The lesson is blunt: a rehearsal mode has to block side effects, not output.
6. Deployment and configuration
6.1 Paths and permissions
| Path | Contents | Mode |
|---|---|---|
~/.config/awen-iwen/token |
the x-auth-token, one line |
0600 |
~/.config/awen-iwen/account.json |
phone + openid (for renewal) | 0600 |
~/.config/awen-iwen/sms.conf |
SMS channel URL / token / AES key | 0600 |
~/.config/awen-iwen/sms.stamp |
when the last SMS was sent (throttle) | 0600 |
~/.config/awen-iwen/feishu.conf |
App ID / Secret / admin open_id | 0600 |
~/.cache/awen-iwen/ |
cards, packages, venues cache (6h) | 0700 |
~/.local/state/awen-iwen/admin_open_id |
the owner, remembered automatically | 0600 |
~/bin/iwen, ~/bin/awen-iwen-bot |
static binaries | 0755 |
~/logs/awen-iwen.log |
all logs | 0640 |
Configuration is plain KEY=VALUE text; the parser skips # comments and tolerates an export prefix and quotes. The sample file contains key names only:
|
6.2 One deployment
|
What deploy.sh does:
- cross-builds the two static binaries (
CGO_ENABLED=0, so the target machine needs no Go); - creates the remote directories and
chmod 700 ~/.config/awen-iwen; - stops the bot first, and SIGKILLs it if it’s still alive two seconds later (during a binary swap the old process would keep holding the long connection);
scps the two binaries,iwen.py/aesgcm.py(fallback) and the systemd units;- on a first deployment, copies the local token / account.json / sms.conf / sms.stamp over (never overwriting what already exists);
daemon-reload,enable --nowthe health-check timer, andstartthe bot if needed.
Because the binaries are static, rollback is simple too: scp the old file back and systemctl --user restart.
6.3 Self-check commands
|
7. Known limits and risk control
This is “automating my own account’s operations”, not “getting around the platform”. Both the boundaries and the risks are stated plainly:
Rules layer
- the benefit cards expire on 2026-12-31; after that the code is only of reference value;
- package A (pick 1) is empty on all three cards, and the number of bookable visits is finite;
- 67 of 96 venues are points-free and 29 need Fu points; the ones needing points are never booked automatically;
- non-refundable venues (rafting, wetlands and the like) are only flagged by default, never ordered;
- entry requires the original ID document — a machine cannot do that step.
Engineering layer
- inventory is a race: between the check and the order someone else can take it, and then the only answer is “insufficient balance”, with no retrying to death;
- single points of failure: the home server, the home network, the Feishu long connection — if any one drops, that week’s card doesn’t go out.
Persistent=trueonly covers “the machine was off”, not “the service died”; - the platform is an old IIS 7.5 + ASP.NET MVC 4 stack with occasional TLS wobbles, so the network layer must retry;
- the endpoints are undocumented, and one platform update can break everything. That’s why the handling of
ResultCodeis conservative: any code we don’t recognise isunknown, never a guess.
Security layer
- an account-level token equals full control of the account: read cards, place orders, cancel orders. It lives only in
~/.configon the target machine, mode 0600, and never in logs, chat history or git; - the SMS channel’s token + AES key can decrypt every SMS on the phone, bank codes included. This is the most sensitive link in the whole system: its own 0600 file, not stored with other config, never copied off-box;
- the capture archive (
capture/chain.json) must have names, ID numbers, card numbers and card secrets scrubbed before it enters the repo; - on the Feishu side exactly one admin may use private chat, and messages from anyone else are dropped outright — because
/cancel allgenuinely refunds orders.
Compliance layer
- this is a personal tool serving the account holder and family;
- no bulk registration, no booking on behalf of others, no API exposed to outsiders;
- request rates deliberately kept low: 6-hour cache, one full inventory query a week, 600 ms between orders, at most three candidates.
8. Things worth carrying over
- Falsify the intuitive option first. UI automation looks the most “legitimate”, but with an empty accessibility tree and an undecryptable package, spending two hours proving it impossible beats spending two weeks making it marginally stable.
- A capture run needs a restore checklist. hosts backup, certificate thumbprint, processes, temp directory — restore on the spot, don’t leave a debug environment on the machine.
- Write platform rules as assertions, not as comments. “6 items a day”, “N days ahead”, “once a year” must be judgements in code; people miss things, machines don’t.
- Writes default to dry-run, and rehearsal mode must block side effects. Printing the list of requests that would be sent is more instructive than any documentation.
- Handle business codes and network errors separately. 300 is 300, a timeout is a timeout: the first needs a human, the second can back off and retry. Mixing them is how you get silent degradation.
- Acknowledge the event callback first, then do the work. Every IM platform has a callback timeout: push heavy work to the background, use the message ID as an idempotency lock, then patch the original message when you’re back.
- Judge “new message” by server sequence numbers, not client clocks. A one- or two-second skew is enough for a verification code to never be seen.
- One app, one long-connection consumer. Several processes competing for the same app’s events show up as “sometimes it receives something”, which is brutal to debug; split the app when it needs splitting.
In closing
What automation actually saves isn’t money. It’s the ten minutes on a Saturday morning: no opening the mini-program, no cross-checking three cards against inventory, no hesitating over “is this one refundable”.
The machine folds up the repeated judgements; the human only has to tap “Book this one”.
Where we actually go — that’s still better left to me.
评论
0 条评论