- Go 98.7%
- Dockerfile 1.3%
| Filename | Latest commit message | Latest commit date |
|---|---|---|
The strongest reason not to use a bot for this is not permissions but timing: clinical notes are written continuously, while chat is a queue of discrete messages with no draft, no cursor and no undo. The new first section grounds that in measurements taken from this code: three Notes round trips for a text entry, five plus two WebDAV for an attachment, about ten seconds of silence when a note is locked, and a typo in the initials producing a second patient card that the bot cannot edit or delete. A closing section lists five short alternatives so the document offers a choice rather than a single verdict. |
||
| .dockerignore | ||
| .env.example | ||
| .gitignore | ||
| attachment.go | ||
| attachment_forms_test.go | ||
| attachment_paths_test.go | ||
| attachment_test.go | ||
| attachmenterror.go | ||
| categories.go | ||
| categories.json | ||
| categories_test.go | ||
| commands.go | ||
| concurrency_test.go | ||
| config.go | ||
| dedupe.go | ||
| Dockerfile | ||
| dotted.go | ||
| dotted_test.go | ||
| e2e_test.go | ||
| go.mod | ||
| healthcmd.go | ||
| healthcmd_test.go | ||
| help_test.go | ||
| localization_test.go | ||
| lock_test.go | ||
| locknotice.go | ||
| locks.go | ||
| main.go | ||
| main_exit_test.go | ||
| messages.go | ||
| notelink_test.go | ||
| notes.go | ||
| notes_test.go | ||
| notescmd.go | ||
| paths_test.go | ||
| patient.go | ||
| patient_test.go | ||
| README.md | ||
| replay_test.go | ||
| signature.go | ||
| signature_test.go | ||
| talk.go | ||
| testserver_test.go | ||
| webhook.go | ||
| webhook_http_test.go | ||
| webhook_test.go | ||
| WHY-NOT-A-BOT.md | ||
NCNoteBotGo — Nextcloud Talk patient notes bot
NCNoteBotGo receives signed Nextcloud Talk webhooks, replies via the OCS Bot API, and creates or updates patient records in Nextcloud Notes directly from chat commands. The implementation uses only the Go standard library and has no external dependencies.
Language: Russian is the primary language. All replies, help text, error messages, and default category names are Russian, and the documented commands are Russian. English replies are available with BOT_LANGUAGE=en, and the Latin commands (/nc, /sc, …) and Latin category codes keep working in either mode, so a bilingual team does not have to agree on how to type. Patient names and note contents are never translated or modified.
Chat commands
| Command | Purpose |
|---|---|
/пинг |
Replies понг to confirm the bot is available |
/помощь |
Lists the commands |
/время |
Shows the current date and time in the configured timezone |
/эхо привет |
Repeats the supplied text |
/категории |
Lists the configured category codes |
/нк Иванов.и.и.Осмотр |
Adds an entry for Иванов И.И. in Корсеты |
/но Иванов.и.и.Осмотр |
Adds an entry in Ортезы |
/нс Иванов.и.и.Осмотр |
Adds an entry in Стельки |
/нп Иванов.и.и.Осмотр |
Adds an entry in Протезы |
/н к Иванов.и.и.Осмотр |
Same note command with the category code separated by a space |
/ск |
Lists patients in Корсеты in alphabetical order |
/ск Иванов.и.и. |
Displays a patient's note with a direct link |
/н.к.Иванов.и.и.Осмотр |
Dot-separated equivalent of /нк ... |
/с.к |
Dot-separated equivalent of /ск |
/с.к.Иванов.и.и. |
Dot-separated equivalent of /ск Иванов.и.и. |
The first letter of a note command is the action: н for add/update a note, с for show or list. The second letter identifies the category: к (Корсеты), о (Ортезы), с (Стельки), п (Протезы). Other categories can be configured in categories.json. /кат is also accepted as an alias for /категории.
English commands are accepted in both languages: /ping, /help, /time, /echo, /categories, /nc, /no, /ni, /np, /sc, /so, /si, /sp, and the Latin codes c, o, i, p. Reserved words are recognised before the short note forms, so /справка is help rather than the show action followed by a category.
For short commands without periods, the bot also recognizes names separated by spaces, for example:
/нк Иванов И И Осмотр тип B
/nc Smith J D Checkup type B
Patient names are stored in a normalized form: Иванов.и.и becomes a note titled ИвановИИ with a heading # Иванов И.И.. Existing patient names in any language are preserved. Hyphens belong to the surname, so Петрова-Иванова.а.б becomes Петрова-ИвановаАБ / Петрова-Иванова А.Б.. Only the first word is treated as the surname; a multiword surname such as van der Berg is not supported, because the remaining words are read as initials.
Files and photos
To add a photo, attach the file to a Talk message containing a note command in its caption:
/н.к.Иванов.и.и.Рентгенограмма
Every spelling accepted for a text command works here too, so the short forms are equivalent:
/нк Иванов.и.и.Рентгенограмма
/нк Иванов и и Рентгенограмма
/н к Иванов.и.и.Рентгенограмма
You can also place the command in the filename, without the initial slash, such as н.к.Иванов.и.и.png or нк Иванов и и Снимок.png. The bot finds or creates the patient note, downloads the file using the NOTES_USER account, uploads it via Notes API 1.4 (POST /attachment/{id}), and inserts a Markdown image reference.
A file sent without a note command is not saved, and the bot answers to say so rather than staying silent:
Файл «снимок.png» получен, но без команды — он не записан.
Добавьте подпись, например: /н.к.Иванов.и.и.Рентгенограмма
# Иванов И.И.
[2026-11-01] Рентгенограмма

If no description is supplied, the default entry text is изображение (image with BOT_LANGUAGE=en). Files must be readable by NOTES_USER. Spaces and parentheses in filenames are URL-escaped so the Notes editor can render the image.
Where Talk puts the file. Talk stores a conversation upload in the uploader's storage as Talk/<conversation name>-<token>/<display name>-<uid> (u)/<file>; the (u) suffix appears when the user folder is shared with update permission, and older servers keep the file directly in the conversation folder. The bot tries these layouts and then lists Talk/ and looks for the file by name, so a layout change does not break it. If the file is still not found, the reply names every path it tried and the account it read as — usually meaning the file is not visible to NOTES_USER at all (see Who can open the notes).
If a note is being edited and Nextcloud temporarily locks it, the bot retries the request for about ten seconds. A note does not unlock the instant the editor is closed, so the first retry tells the room Кажется, заметка открыта в редакторе, проверяю… and the final message reports the outcome — written, or still locked. The bot never claims the editor is open with certainty, because the lock can also come from another Notes client or a sync process.
Language
BOT_LANGUAGE selects the reply language; the default is ru. Unset or unrecognised values fall back to Russian, so a typo cannot silently switch a Russian-speaking workshop to English. en switches every reply, including help and errors. Command keywords are accepted in both languages regardless of this setting.
Mobile keyboard support
Smartphone keyboards may insert spaces after periods, capitalize initials, or use nonbreaking spaces. The bot accepts these variants:
/н.к.Иванов.и.и.Первый приём
/н. к. Иванов. и. и. Первый приём
Whitespace around periods is ignored, the action and category are case-insensitive, and periods in the note text are preserved. The first field is the surname; subsequent one- or two-letter fields are treated as initials. Full first names are reduced to initials: Иванов Иван Иванович and Иванов Илья Ильич both become ИвановИИ, so spell out different patients with distinct initials.
Use one separator, not both. Either dots throughout or spaces throughout:
/нк Иванов.и.и.Осмотр -> Иванов И.И.
/нк Иванов и и Осмотр -> Иванов И.И.
/нк Иванов.и.и Осмотр -> Иванов И., а «и» попадает в текст записи
A space between dotted initials and the note text makes the last initial part of the entry, which files the command under a different patient (ИвановИ instead of ИвановИИ). This is why mixed separators must be avoided.
Note storage and concurrency
Each note has a canonical title (for example ИвановИИ), a category folder (Корсеты, Ортезы, Стельки, or Протезы), and Markdown contents consisting of a patient-name heading followed by timestamped entries. The latest entry appears first. Updates use If-Match and the note's ETag to avoid silently overwriting concurrent edits.
Commands are processed by a small worker pool (BOT_WORKERS) with a bounded queue (BOT_QUEUE); when the queue is full the bot answers HTTP 503 instead of accepting unbounded work. Writes for one patient are serialized, so two people recording the same new patient at the same moment produce one note and both entries, rather than duplicate notes. The lock is per process: running several bot instances against one Nextcloud account is not supported.
Who can open the notes
Every note belongs to NOTES_USER. The bot links to it as
<NEXTCLOUD_URL>/index.php/apps/notes/note/<id>, where <id> is the note file's
Nextcloud file id. That id is server-wide, so a note keeps the same link for
every account that can see the file.
A clinician opening a link gets Not Found unless their account can access the file. Notes are ordinary files in the bot account's Notes folder, so the access has to be granted in Nextcloud, not by the bot:
- As
NOTES_USER, share the notes folder with the staff group — the whole folder, or the per-category folders such asКорсеты. - In Notes, add the shared folder as a notes folder if it does not appear automatically (Notes settings → Notes folders).
- Open the link. Editing requires a share with edit permission; a read-only share opens the note in read-only mode.
Sharing the folder is also what makes attachments readable: the bot downloads
files as NOTES_USER from the same storage, so files sent by the staff have to
be visible to that account.
Attachments and file ownership
Talk stores an upload in the uploader's storage, not the bot's:
Talk/<conversation name>-<token>/<display name>-<uid> (u)/<file>. The bot reads
as NOTES_USER, and Nextcloud does not let one account read another's files. An
attachment sent by a clinician is therefore invisible to the bot until the bot
account is let in.
The least setup: make the bot account a participant of the conversation.
Talk → conversation → Add participants → <NOTES_USER>
Talk already shares each uploader's folder with the room, so a room member can read the files. Nothing else needs configuring: no per-user shares, no admin settings, and it keeps working when staff change.
If the bot cannot be added as a participant in your version, share the
conversation folder Talk/<conversation name>-<token> with NOTES_USER instead.
Check as the bot account before retrying:
curl -s -u "$NOTES_USER:$NOTES_PASSWORD" -X PROPFIND -H 'Depth: 1' \
"$NEXTCLOUD_URL/remote.php/dav/files/$NOTES_USER/" | grep -o '<d:href>[^<]*'
The conversation folder should appear there, at the account root or under
Talk/; both are searched.
When the file is genuinely out of reach the reply names the account, the uploader, and the fix, and the full list of attempted DAV paths goes to the log rather than the chat.
Upgrading from the English layout: category folders were previously named Corsets, Orthoses, Insoles, Prostheses. Notes filed under those names are not migrated automatically. Back up the Notes folder and move or rename the old folders to the Russian names, or keep the old categories.json — it still works, because the Latin codes and the Russian codes resolve to the same category.
Requirements
- Go 1.22 or later to build from source.
- Nextcloud 27.1+ with Talk 17.1+ (
bots-v1) and the Notes application. Attachment upload requires Notes 6.1+ / API 1.4. - A Nextcloud account with permissions to create and update notes and access any intended attachments.
Build and run
cd ncnotebotgo
cp .env.example .env # configure BOT_SECRET, NOTES_USER, and NOTES_PASSWORD
go test ./...
go build -o ncnotebotgo .
./ncnotebotgo # reads .env from the current directory
If this checkout sits inside a parent Go workspace (go.work) that does not list this module, go reports directory prefix . does not contain modules listed in go.work. Either add ./service/ncnotebotgo to that workspace, or prefix the commands with GOWORK=off:
GOWORK=off go test ./...
Docker
docker build -t ncnotebotgo .
docker run -d --name ncnotebotgo \
--env-file .env --network nextcloud_default ncnotebotgo
Configuration is supplied through --env-file; .env is never copied into the image. The runtime image is distroless and runs as nonroot, so it has no shell, no package manager, and no writable filesystem. Mount a replacement over /app/categories.json to change category codes without rebuilding. Publish a port only when Nextcloud is outside the Docker network, and terminate TLS in front of the bot.
The image declares a HEALTHCHECK that runs /app/ncnotebotgo health, which exits 0 only when the local endpoint answers 200 with "ok": true. Because the image has no shell or curl, the binary probes itself. In Compose this enables depends_on: { ncnotebotgo: { condition: service_healthy } }, and docker compose up --wait blocks until the bot is actually serving. The probe calls loopback even when BOT_HOST is 0.0.0.0.
A startup failure is reported as such: if the bot cannot bind its port it logs fatal server error and exits with status 1, so restart: on-failure restarts it. SIGTERM and SIGINT are a normal stop and exit 0.
Run the binary under any process supervisor (for example a systemd unit) in a directory containing .env. If the bot is reachable from outside the Nextcloud host, terminate TLS in front of it and register the public https:// webhook URL.
Check the health endpoint with curl http://127.0.0.1:8080/ (or the host/port specified in .env). The response includes status, bot, and a command list for operators.
Configuration
| Variable | Description |
|---|---|
NEXTCLOUD_URL |
Nextcloud base URL for API calls; must also be the address clinicians use in a browser, because note links are built from it |
BOT_SECRET |
Secret registered using occ talk:bot:install (40–128 characters); signs webhook payloads and replies |
WEBHOOK_TOKEN |
Optional additional token in /webhook/<token> or the X-Webhook-Token header |
BOT_HOST, BOT_PORT |
HTTP listening address and port; defaults are defined in config.go |
BOT_WORKERS, BOT_QUEUE |
Number of webhook events processed at once and how many may wait; default 4 and 64 |
BOT_LANGUAGE |
Reply language: ru (default) or en |
TZ |
Timezone used by /время and note entry dates |
LOG_LEVEL |
DEBUG, INFO, WARNING, or ERROR |
NOTES_USER, NOTES_PASSWORD |
Nextcloud account and application password for Notes |
CATEGORIES_PATH |
Category mapping file, by default categories.json |
Register with Nextcloud Talk
Run the following with the correct occ location, user, and tokens for your installation:
php occ talk:bot:install \
"NCNoteBotGo" \
"<BOT_SECRET>" \
"https://bot.example.com/webhook/<WEBHOOK_TOKEN>" \
"Бот заметок пациентов" \
-f webhook -f response
php occ talk:bot:list
php occ talk:bot:setup <BOT_ID> <ROOM_TOKEN>
The bot needs to be added to each Talk conversation separately. The webhook endpoint must be reachable from the Nextcloud server.
Signing and authentication
The signature algorithm is hex(HMAC-SHA256(random + data, BOT_SECRET)).
| Direction | Signed data | Headers |
|---|---|---|
| Talk → bot | Raw webhook request 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 mismatched signature causes 403 for incoming webhooks or may cause 401 on outgoing messages. Do not leave BOT_SECRET empty except during isolated local development.
A valid signature stays valid forever, so the bot remembers recently verified signatures for ten minutes and answers a repeat delivery with {"ok":true,"reason":"duplicate webhook"} without running the command again. Identical text sent as a new message has a new random value and is processed normally.
Tests and troubleshooting
go vet ./...
go test ./...
Tests cover webhook signatures and replay rejection, ActivityStreams message parsing, attachments, note CRUD and ETags, concurrent note creation, command parsing, patient name normalization including hyphenated surnames, WebDAV path sanitization, queue backpressure, Russian-primary and English localization, and end-to-end Talk replies.
If the bot does not respond, check that it is added to the conversation, that the webhook URL is reachable from Nextcloud, and that BOT_SECRET matches the registration value. For Notes API 401 errors, check NOTES_USER and NOTES_PASSWORD (prefer an application password). For HTTP 412, retry the command after the concurrent update.
HTTP 423: the note is locked
Nextcloud Notes stores each note as one Markdown file and protects writes with Nextcloud's transactional file locking. That is mutual exclusion, not collaboration: the Nextcloud manual says plainly that locking "will not prevent multiple users['] simultaneous file saving". The practical consequence is that a bot and a clinician editing the same patient note contend for the same file lock, and the lock is not released the moment someone stops typing.
The database locking provider gives a lock a time-to-live of one hour
(DBLockingProvider defaults to ttl = 3600) and stores an absolute expiry
timestamp in oc_file_locks.ttl. A lock released normally disappears at once; a
lock left behind by a closed tab, a killed client, or an interrupted Text
session stays until it expires. That is why a note can report "locked" for
minutes after everything was closed.
Which backend holds the locks:
docker compose exec -u www-data nextcloud php occ config:system:get memcache.locking
# empty output -> database locking, rows live in oc_file_locks
With database locking, see what is held and when it expires:
docker compose exec db psql -U nextcloud -d nextcloud \
-c "SELECT key, lock, ttl, to_timestamp(ttl) AS expires_at FROM oc_file_locks;"
Clear locks that have already expired (safe; Nextcloud does the same itself):
DELETE FROM oc_file_locks WHERE ttl < EXTRACT(EPOCH FROM NOW());
Do not delete rows whose ttl is in the future without first confirming no
client is editing — that is a live lock, and removing it invites conflicting
writes. The bot never clears locks, because it cannot tell a stale lock from a
live one.
When the attachment upload succeeds but the note update gets a 423, the file is already stored in the note's attachment folder and only the entry text is missing. Sending the file again finishes the job instead of duplicating it: the bot reuses the copy that is already there.
Current limitations
A single Notes account (NOTES_USER) is used for the bot. Voice messages are not transcribed; a voice recording is treated like any other file, so without a caption it is not saved and the bot replies that the command is missing. Attachments are always inserted as Markdown images, so non-image files such as PDFs and audio render as a broken image in the Notes editor. The bot cannot delete patient notes. It can only access files shared with, or owned by, the configured Notes account. Multiword surnames are not supported, and patients whose names differ only in initials that normalize to the same key share one note.