No description
This repository has been archived on 2026-11-02. You can view files and clone it, but you cannot make any changes to its state, such as pushing and creating new issues, pull requests or comments.
  • Go 99.3%
  • Dockerfile 0.7%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
surdeus 206a900010 Truncate the echo so a long note's confirmation arrives
Found by driving the bot through a simulated Nextcloud in Docker: a note of
about 36 000 characters was written in full, and the confirmation never
arrived. The reply repeated the whole text, and Talk rejects a bot message over
32 000 characters — so the clinician saw silence after a successful write, and
the obvious next move is to write it again.

The note keeps every character; only the chat echo is cut at 300, which is
plenty to recognise the entry. The idle-gate question embeds the same text and
is cut the same way.
2026-11-02 23:28:41 +05:00
.dockerignore Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
.env.example Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
.gitignore Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
adversarial_test.go Route on «!»: commands are prefixed, everything else is a note 2026-11-02 22:38:55 +05:00
architecture.md Docs: the folder directive 2026-11-02 23:19:23 +05:00
attachment.go Big bang: the old command grammar is gone 2026-11-02 17:59:58 +05:00
attachment_flow.go Big bang: the old command grammar is gone 2026-11-02 17:59:58 +05:00
attachment_test.go Big bang: the old command grammar is gone 2026-11-02 17:59:58 +05:00
categories.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
categories.json Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
chart.go A folder is a second «!» word 2026-11-02 23:19:23 +05:00
cli.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
commands.go Big bang: the old command grammar is gone 2026-11-02 17:59:58 +05:00
config.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
config_test.go Route on «!»: commands are prefixed, everything else is a note 2026-11-02 22:38:55 +05:00
console.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
console_test.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
dedupe.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
dedupe_test.go Route on «!»: commands are prefixed, everything else is a note 2026-11-02 22:38:55 +05:00
Dockerfile Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
e2e_test.go Big bang: the old command grammar is gone 2026-11-02 17:59:58 +05:00
fuzz_test.go A folder is a second «!» word 2026-11-02 23:19:23 +05:00
go.mod Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
greeting.go A folder is a second «!» word 2026-11-02 23:19:23 +05:00
greeting_test.go Big bang: the old command grammar is gone 2026-11-02 17:59:58 +05:00
handler.go A folder is a second «!» word 2026-11-02 23:19:23 +05:00
handler_test.go Truncate the echo so a long note's confirmation arrives 2026-11-02 23:28:41 +05:00
health.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
lock_other.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
lock_unix.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
main.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
name.go Route on «!»: commands are prefixed, everything else is a note 2026-11-02 22:38:55 +05:00
name_test.go Harden: six defects found by attacking the bot 2026-11-02 18:20:55 +05:00
notes.go Resolver: classify a message before anything is written 2026-11-02 17:51:50 +05:00
notes_test.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
ocs.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
onboarding.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
onboarding_test.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
README-DEPLOY.md Docs: one rule instead of a classifier 2026-11-02 22:38:57 +05:00
README.md Docs: the folder directive 2026-11-02 23:19:23 +05:00
resolve.go Route on «!»: commands are prefixed, everything else is a note 2026-11-02 22:38:55 +05:00
resolve_test.go Route on «!»: commands are prefixed, everything else is a note 2026-11-02 22:38:55 +05:00
service.go Harden: six defects found by attacking the bot 2026-11-02 18:20:55 +05:00
session.go Clinician flow: control words, prompts, echo, and the write paths 2026-11-02 17:55:35 +05:00
session_test.go Session state: active patient, pending question, idle gate 2026-11-02 17:52:59 +05:00
signature.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
signature_test.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
sourcepath.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
sourcepath_test.go Big bang: the old command grammar is gone 2026-11-02 17:59:58 +05:00
state.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
strings_ru.go Truncate the echo so a long note's confirmation arrives 2026-11-02 23:28:41 +05:00
talk.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
talkcontext.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
talkcontext_test.go Big bang: the old command grammar is gone 2026-11-02 17:59:58 +05:00
testserver_test.go Harden: six defects found by attacking the bot 2026-11-02 18:20:55 +05:00
webhook.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
webhook_http_test.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00
webhook_test.go Baseline: working bot before the clinician-interaction rewrite 2026-11-02 17:23:39 +05:00

NCNoteBot — patient notes bot for Nextcloud Talk

NCNoteBot receives signed Nextcloud Talk webhooks, replies through the OCS Bot API, and creates or appends patient records in Nextcloud Notes straight from chat commands. It uses only the Go standard library and has no third-party dependencies.

Language: the bot's interface is Russian — commands, help, errors, category names and note text. This document is English; Russian interface strings appear in code spans or quoted blocks. Patient names and note contents are never translated.

How a clinician works

One rule, and the whole interface follows from it:

С «!» — команда, без «!» — запись. With «!» a message is a command; without it, a note.

A command is addressed to the bot: choose a patient, search, browse a category, confirm, end the session. Everything else is content about the patient and goes straight into the active chart — text, a voice message, a file.

1. Choose the patient.

!ИвановАА            or   !Иванов А.А.

The bot replies with the card and remembers the patient:

Пациент: Иванов Пётр Сергеевич
Ответьте текстом — запись попадёт в «Корсеты».

2. Send the notes. Plain text, a voice message, or a file, with no prefix at all. Every reply repeats the patient and the text:

✅ Иванов Пётр Сергеевич · «Корсеты» · записано: «первичный приём»

3. !готово when the appointment ends.

The prefix exists because the two kinds of message cannot be told apart by their content: жалобы на and иванов аа have the same shape. Any attempt to guess produced accidents — a surname filed into one chart, a note turned into a patient card, a stray да recorded as clinical text. One character removes the guess.

Name format

Two strings per patient, and the difference matters:

title     Иванов Пётр Сергеевич    the note title, the filename, the identity
initials  ИвановПС                a search key, NOT unique

A name is accepted only when the surname/initials boundary is visible and the initials are exactly two letters:

!ИвановАА  !Иванов АА  !Иванов а.а  !Иванов.АА  !ИВАНОВ АА   → ИвановАА
!ИвановА   !Иванов АБВ  !ивановаа    !ИВАНОВАА                → refused

Creation asks for the full name — Фамилия Имя Отчество — because two people can share a surname and initials. Only a capitalised name is ever offered for creation, so three lowercase words can never become a patient.

What a message means

Commands:

You send The bot does
!ИвановПС shows the card, makes the patient active
!ИвановПС примерка writes, and makes the patient active
!Иванов Пётр Сергеевич offers to create, if nobody matches
!Иванов lists everyone with that surname
!стельки lists patients in that category (read-only)
!1 picks from the last numbered list
!ИвановИИ примерка lists the matches, then writes the note once you pick one
!ИвановИИ !стельки примерка writes into his «Стельки» record, creating it if he has none
!Петров Пётр Сергеевич !ортезы offers to create the card in «Ортезы»
!готово ends the session
!да / !нет answers the bot's question

Notes:

You send The bot does
примерка note for the active patient
ИвановАА note for the active patient, verbatim
да, стало лучше note for the active patient

A file or voice message goes to the active patient. A file captioned with a patient's name goes to that patient and makes them active, so the follow-up note needs no prefix either — explicit beats remembered.

A ! command that matches nothing is answered rather than ignored, because the clinician meant to act. A message without the prefix is never interpreted, so ordinary chat cannot reach a chart by accident — but it also means nothing is written without a patient being chosen first.

Choosing the folder

A folder is named in the same line, as a second ! word:

!ИвановИИ !стельки примерка      → запись в «Стельки»
!ИвановИИ !стельки               → карта, дальше записи идут в «Стельки»
!Петров Пётр Сергеевич !ортезы   → новая карта в «Ортезы»
!да !стельки                     → создать в «Стельки» вместо предложенного

Without a folder the bot follows the patient's newest note, so the directive is only needed when the answer would be wrong. The record is created when the patient has none in that folder — "I'm on his insoles record now".

A ! word that is not a folder is refused, never filed as text: !Ортэзы answers with the list of folders. A second folder in the same command is refused too. Inside a word, ! is punctuation: жалобы! сильные is saved as written.

! followed by a space is punctuation, not a command. ! срочно перезвонить is a note, saved as «срочно перезвонить». A phone keyboard, a typing habit or dictation puts a bang in front of a sentence, and no command begins with a space, so nothing legitimate is lost. A bare ! on its own stays a command: the bot asks what was meant instead of saving it.

When the bot has just asked something, an exact да, нет or list number typed without the prefix is not written: the bot replies with Похоже, это ответ боту. Напишите с «!» — например, «!да» или «!1».

Slash commands

Command Purpose
/старт Short reminder; the same text onboarding sends
/помощь Full help
/пинг Liveness check; replies на связи
/время Current date and time
/категории Category codes
/пациенты Every patient, grouped by category
/эхо текст Repeats the text

Service commands keep the slash instead of !: words like «помощь» appear in ordinary sentences, and the slash is the habit the clinic already has.

Files and photos

Send the file to the active patient — no caption needed:

[photo]                                   → entry text «изображение»
[voice message]                           → entry text «голосовое сообщение»
[photo] captioned "Рентген грудной клетки" → that caption is the entry text
[photo] captioned "ИвановПС"               → attaches to that patient

A caption that is a patient's name selects the patient rather than describing the file, so the photo of this patient needs no session at all. Any other caption becomes the entry text.

The bot downloads the file as NOTES_USER, uploads it through Notes API 1.4, and inserts a Markdown image reference:

# Иванов Пётр Сергеевич

[01.11.2026] [Смит А.А.] Рентген грудной клетки
![снимок.png](<.attachments.314/снимок 1 (2).png>)

Filenames are kept readable: Cyrillic is not percent-encoded, and the destination is wrapped in angle brackets so spaces and parentheses survive. Only characters that actually break something are escaped — %, ?, #, <, > and \ — because the Notes app decodes the path as a URI and truncates it at a query string. markdown-it encodes non-ASCII itself when rendering, so the stored form and the rendered form agree.

Path resolution. Talk gives a bot only the file name, not its folder, so the bot asks Talk instead of guessing: it fetches the message back through the chat API as the Notes account (GET /ocs/v2.php/apps/spreed/api/v1/chat/{token}/{id}/context). For a logged-in participant Talk resolves file parameters against that account's own file tree, so the answer is a path the bot can actually read.

If that request fails — the account is not a participant, the chat API is unavailable, or the resolved path is unreadable — the bot falls back to a small set of known layouts under the Talk attachment root, and remembers which one worked per conversation. Attachments degrade to the slower path; they do not fail.

A voice message cannot carry a name (Talk sends it as a file share whose text is literally {file}), which is why the active patient exists at all. With no active patient and no name in the caption, the bot asks which patient and attaches nothing.

If a note is locked in the Notes editor, the bot retries and then asks the clinician to close the note and resend.

Duplicate deliveries

Talk retries webhook deliveries, and a clinician who is unsure whether a command worked will often resend it. The bot remembers the last 1000 message ids in memory and ignores a repeat of one it has already handled, so a retry cannot append a second entry to the chart.

A suppressed repeat is answered with уже записано, so the clinician is never left guessing whether the first attempt landed. A resend that carries a new message id is kept, because a visible duplicate is recoverable while a silently discarded entry is not.

The set is deliberately not persisted. It exists to absorb retries that arrive within seconds or minutes; a restart simply forgets it.

Note format

Each note has a canonical title (ИвановИИ), a category folder («Корсеты», «Ортезы», «Стельки», «Протезы»), and Markdown content: a patient heading followed by dated entries, newest first.

Every entry is signed with the Talk display name of the clinician who sent the command:

[01.11.2026] [Смит] Осмотр, поясничный корсет

The chart is shared, so an unsigned entry would not say who wrote what. When the Talk display name is unavailable the entry is signed [Неизвестный] rather than left blank: an entry that admits it does not know is better than one that looks anonymous by accident.

Updates use If-Match with the note's ETag so a concurrent edit is not silently overwritten.

Dates are ДД.ММ.ГГГГ. Entries are prepended, so ordering never depends on the date format.

Same-chat usage rules

  • One action per message.
  • The bot ignores its own messages, so it cannot loop.
  • Note text is preserved verbatim, including periods and commas.
  • A note sent after a gap of more than four hours is confirmed first, with the patient named, rather than written to a possibly stale card.
  • State is per conversation and in memory. A restart costs one message.

Requirements

  • Docker to run the container; Go 1.22+ to build outside Docker.
  • Nextcloud 27.1+ with Talk 17.1+ (bots-v1) and the Notes app. Attachments require Notes 6.1+ / API 1.4.
  • A Nextcloud account that can create and update notes and read the intended attachments.

Build and run

cp .env.example .env     # set BOT_SECRET, NOTES_USER and NOTES_PASSWORD
go test ./...
go build -o NCNoteBot .
./NCNoteBot            # reads .env from the current directory

The supported deployment is the container image built from Dockerfile; see README-DEPLOY.md. There is no systemd installation path.

Health check: curl http://127.0.0.1:8390/, or ncnotebot health inside the container. The response includes status, bot and the command list.

Operator commands

Enrolment and the roster are managed two ways, and both call the same implementation: a console room in Talk, and CLI subcommands. Neither contains onboarding logic of its own — each parses its input, calls Onboarder.Add/Remove/Reconcile, and formats the result.

Console room

Set CONSOLE_TOKEN to the token of a private room and add the bot to it as a moderator. Admin commands are English, because operators are technical and the room never carries clinical text. Clinician conversations are Russian and the two grammars never mix.

!clinician add smith        create the 1:1, enable the bot, greet
!clinician remove smith     disable the bot and drop the record
!clinician list             who is enrolled
!clinician status smith     one clinician, including the last error
!greeting show              current welcome text
!greeting set <text>        store new text and bump its version
!reconcile                  re-enable the bot, deliver pending greetings
!status                     configuration and roster summary
!help                       the list above

Replies are one line per action, so the room stays a log rather than a conversation. Ordinary chatter in the console room is ignored.

Changing the greeting does not deliver it by itself: !reconcile sends it to everyone who has not had that version, and each version is sent once.

CLI

The same operations, for the case where the console room is not set up yet and for scripting.

ncnotebot clinician add smith          # create the 1:1, enable the bot, greet
ncnotebot clinician list               # who is enrolled, and their state
ncnotebot clinician remove smith       # disable the bot, drop the record
ncnotebot reconcile                    # repair: re-enable, re-greet if needed

In the container:

docker exec ncnotebot /app/ncnotebot clinician list

add is idempotent. Running it again reuses the existing conversation, re-enables the bot if it was switched off, and only sends the greeting when the person has not had the current wording. That is also how a half-finished onboarding is repaired.

remove disables the bot in the conversation and drops the roster entry. Dropping only the record would leave the bot reading a conversation it must no longer answer. Past notes keep their author; history is not rewritten.

The CLI is also the bootstrap path: before the bot is enabled in the console room there is no way to type an admin command, but clinician add only needs the account credentials.

The roster is the access boundary

Any moderator can enable a bot in a room of theirs, so being present in a conversation is not permission to use the bot. A delivery from a conversation that is not enrolled is acknowledged and dropped before its text is parsed.

While the roster is empty the bot answers everything and logs a warning at startup: that keeps a single-room deployment working after an upgrade, and the first clinician add switches the boundary on.

State

The roster lives in one JSON file (STATE_PATH, /data/state.json in the container):

{
  "schema_version": 1,
  "greeting": {"text": "...", "version": 1},
  "clinicians": {
    "abcd1234": {"uid": "smith", "token": "abcd1234", "state": "welcomed",
                 "greeting_version": 1, "updated_at": 1793000000}
  }
}

Writes go to a temp file, are fsynced, and are renamed into place, so a crash cannot leave a half-written roster. Mutations also take an advisory file lock and re-read the file first: the server and an operator's CLI run are separate processes, and without that a CLI enrolment would be invisible to the running bot and would be erased by its next write.

This file holds only who may talk to the bot. The active patient, the open question and the recent patients are kept in memory, per conversation: losing them on restart costs one message — the clinician re-names the patient — while persisting them would mean a write on every message and a file lock on the hot path. Nothing in a chart depends on them.

Configuration

Variable Description
NC_API_URL Nextcloud base URL the bot calls (OCS, Notes, WebDAV); NEXTCLOUD_URL is accepted as a fallback
NC_PUBLIC_URL Base URL for the note links in replies; defaults to NC_API_URL
BOT_SECRET Secret from occ talk:bot:install (40–128 characters); signs webhooks and replies
WEBHOOK_TOKEN Optional token in /webhook/<token> or the X-Webhook-Token header
BOT_HOST, BOT_PORT HTTP listen address and port
TZ Timezone for /время and entry dates
LOG_LEVEL DEBUG, INFO, WARNING or ERROR
NOTES_USER, NOTES_PASSWORD Nextcloud account and app password for Notes
CATEGORIES_PATH Category mapping file, categories.json by default
BOT_ID Bot id from occ talk:bot:install; required for enrolment
STATE_PATH Roster file, /data/state.json in the container
CONSOLE_TOKEN Conversation accepted for admin commands; empty disables it

Register with Nextcloud Talk

php occ talk:bot:install \
  "NCNoteBot" \
  "<BOT_SECRET>" \
  "http://ncnotebot:8390/webhook/<WEBHOOK_TOKEN>" \
  "Бот для заметок о пациентах" \
  -f webhook -f response

php occ talk:bot:list
php occ talk:bot:setup <BOT_ID> <ROOM_TOKEN>

The bot has to be added to each conversation separately, and the webhook endpoint must be reachable from the Nextcloud server.

Signing and authentication

hex(HMAC-SHA256(random + data, BOT_SECRET)).

Direction Signed data Headers
Talk → bot Raw webhook body X-Nextcloud-Talk-Random, X-Nextcloud-Talk-Signature
Bot → Talk Message text in the JSON message field X-Nextcloud-Talk-Bot-Random, X-Nextcloud-Talk-Bot-Signature, OCS-APIRequest: true

A bad signature gives 403 on inbound webhooks and 401 on outbound messages. Leaving BOT_SECRET empty disables verification and is for isolated development only.

Tests and troubleshooting

go vet ./...
go test ./...

Tests cover webhook signatures, ActivityStreams parsing, attachments and path resolution, note CRUD with ETags, duplicate suppression, attribution, mobile-keyboard command parsing, and end-to-end replies.

If the bot is silent, check that it is in that conversation, that the webhook URL is reachable from Nextcloud, and that BOT_SECRET matches. A Notes 401 means NOTES_USER / NOTES_PASSWORD; prefer an application password. Retry on 412 after a concurrent change. On 423, close the note in the editor.

Limitations

A single Notes account (NOTES_USER) is used. The bot does not transcribe voice messages, delete notes, or reach files unavailable to that account.

  • A surname containing a space is refused on creation (ван дер Берг). The stored title carries no marker for where the surname ends, so a derived search key could silently fail to match. Single-token surnames are fully supported.
  • A name typed entirely in lowercase that matches nobody is treated as note text, not as a creation offer: capitalisation is what distinguishes «Петров Борис Сергеевич» from a sentence. The echo shows the mistake at once.
  • A patient without a patronymic needs the clinic's convention for the third part, e.g. Иванов Иван Н.
  • Attachment path resolution asks the chat API first and still falls back to known layouts if that fails.