A Telegram Bot for simple integration with "People I Know"
  • C# 94.8%
  • Shell 5.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Lars Richter b73f350462 Document every message the bot receives in JSON Lines logs
messages.jsonl has each message and button tap of the allowed users,
with what the bot did with it, so nothing gets lost even when People I
Know is down. strangers.jsonl has those of everybody else, with their
@username. When a log would grow past its size limit, its oldest lines
are removed; only the strangers' log has one by default (10 MB).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:21:19 +01:00
deploy Add a Telegram bot that adds notes to People I Know 2026-10-29 17:41:26 +01:00
PikBot Document every message the bot receives in JSON Lines logs 2026-10-29 18:21:19 +01:00
PikBot.UnitTests Document every message the bot receives in JSON Lines logs 2026-10-29 18:21:19 +01:00
.gitignore Document every message the bot receives in JSON Lines logs 2026-10-29 18:21:19 +01:00
deploy.sh Document every message the bot receives in JSON Lines logs 2026-10-29 18:21:19 +01:00
global.json Add a Telegram bot that adds notes to People I Know 2026-10-29 17:41:26 +01:00
LICENSE Add a Telegram bot that adds notes to People I Know 2026-10-29 17:41:26 +01:00
PikBot.slnx Add a Telegram bot that adds notes to People I Know 2026-10-29 17:41:26 +01:00
README.md Document every message the bot receives in JSON Lines logs 2026-10-29 18:21:19 +01:00

People I Know bot

A Telegram bot that adds notes to the timelines in People I Know, a self-hosted personal relationship manager. Write it a message like

John Doe: We met at Starbucks today. His wife is pregnant.

and it looks up "John Doe" in People I Know and adds "We met at Starbucks today. His wife is pregnant." to his timeline, dated when you sent the message.

  • One match: the note is saved, the bot answers "Saved for John Doe."
  • Several matches: the bot asks "Which "John Doe" do you mean?" with one button per contact (name · employer · tags) and a "Cancel" button. The note is saved once you tap a name. Questions expire after a day or when the bot restarts; then send the note again.
  • No match or more than 8 matches: nothing is saved, the bot tells you why.
  • The name is everything before the first colon, so times like "10:30" in the note are fine. The search works like People I Know's API: every word has to be part of the name, ignoring case, so "John Doe" also finds "John Michael Doe".

Only the Telegram users listed in Telegram:AllowedUserIds get an answer. Messages and button taps from anybody else, and anything written in groups, are ignored without a reply. Both are documented, see Message logs.

The bot uses Telegram's long polling, so it needs no public address, no open port and no phone number. Messages sent while it is down wait at Telegram (for up to 24 hours) and are handled when it starts again.

Keep in mind that bot chats are not end-to-end encrypted: your notes pass through Telegram's servers and stay in the chat history there, even though People I Know itself is self-hosted.

The bot needs People I Know with its API for bots (/api/contacts).

Set up

1. Create the Telegram bot

  1. Write /newbot to @BotFather and follow the steps. You get the bot's token.

  2. Optional, but recommended: /setjoingroups → your bot → Disable, so nobody can add it to a group.

  3. Find your own Telegram user id: write anything to your new bot, then (while the bot service isn't running)

    curl -s https://api.telegram.org/bot<TOKEN>/getUpdates | jq '.result[].message.from | {id, username}'
    

2. Create the Keycloak client

Set up the client peopleiknow-bot with the role api-notes as described in People I Know's README, section "Use the API (e.g. from a bot)". Its credentials tab has the client secret.

3. Configure

Settings live in PikBot/appsettings.json; put your values into appsettings.Production.json (on the server) or appsettings.Development.json / user secrets (locally), or use environment variables like Telegram__Token and Telegram__AllowedUserIds__0. These files are ignored by git, keep your secrets out of appsettings.json.

Setting What it is
Telegram:Token The token from @BotFather
Telegram:AllowedUserIds Your Telegram user id, e.g. [123456789]. Everybody else is ignored
PeopleIKnow:Url People I Know's address, e.g. https://pik.example.com/
Keycloak:Authority Your realm's URL, e.g. https://keycloak.example.com/realms/peopleiknow
Keycloak:ClientId / Keycloak:ClientSecret The bot's Keycloak client, default id peopleiknow-bot
MessageLog:Path Where every message of yours is documented, see Message logs. Default messages.jsonl in the working directory; empty turns it off
MessageLog:MaxBytes Size limit of your message log; when it is reached, the oldest lines are removed. Default 0, no limit
MessageLog:StrangersPath Where messages of everybody else are documented. Default strangers.jsonl in the working directory; empty turns it off
MessageLog:StrangersMaxBytes Size limit of the strangers' log, default 10485760 (10 MB)
Serilog Logging; by default to the console and to logs/log.txt (one file per day) in the working directory

The bot checks these settings on startup and refuses to start, naming what is missing, if they are incomplete.

{
  "Telegram": {
    "Token": "123456:ABC-DEF...",
    "AllowedUserIds": [123456789]
  },
  "PeopleIKnow": {
    "Url": "https://pik.example.com/"
  },
  "Keycloak": {
    "Authority": "https://keycloak.example.com/realms/peopleiknow",
    "ClientSecret": "..."
  }
}

The regular logs (Serilog) never contain the notes themselves, only the contact ids that got one. The notes are only in the message log.

Message logs

Every message from an allowed user is appended to MessageLog:Path as one JSON object per line, together with what the bot did with it, even if nothing was saved. Taps on the buttons of "Which John Doe do you mean?" are logged as well.

{"time":"2026-10-29T17:30:00+00:00","kind":"message","userId":123456789,"text":"John Doe: Met for coffee","outcome":"asked","contacts":[{"id":1,"fullName":"John Doe"},{"id":2,"fullName":"John Michael Doe"}]}
{"time":"2026-10-29T17:31:12+00:00","kind":"choice","userId":123456789,"text":"Met for coffee","outcome":"saved","contacts":[{"id":2,"fullName":"John Michael Doe"}]}
Field What it is
time When you sent the message (from Telegram), or when you tapped a button
kind message, or choice for a button tap
text The message as you sent it; for a choice, the note it was about (null if the question had expired)
outcome saved, asked (several matches, the bot asked), notFound, tooManyMatches, failed (People I Know didn't answer as expected), noNote (no "Name: note"), notPrivateChat (written in a group), cancelled, expired, unknownChoice
contacts The contact that got the note, or the matches the bot found

So nothing you sent gets lost, even if People I Know was down: jq 'select(.outcome == "failed")' messages.jsonl lists what still has to be saved. A log that can't be written is reported in the regular log, but never keeps a note from being saved. The file grows by one line per message (a few hundred bytes) and has no size limit by default, so nothing you sent is ever dropped; set MessageLog:MaxBytes if you want one.

Messages and button taps from everybody else go to MessageLog:StrangersPath instead, so you can see who found the bot and what they tried (they also show up as a warning with their user id in the regular log):

{"time":"2026-10-29T18:02:40+00:00","kind":"message","userId":987654321,"userName":"@somebody","chatId":987654321,"text":"/start"}

userName is the sender's @username, or their name if they have none; text is the message, or for a choice the button's data. Anybody who finds the bot can write to this file, so it is limited to 10 MB by default (MessageLog:StrangersMaxBytes).

When a line would take a log past its limit, the bot removes the oldest lines until the log is down to 80% of the limit, and then appends the line. So the file is rewritten only now and then, never on every message, and always holds the newest lines. The trimmed log is written to a temporary file next to it, which then replaces the log, so a crash in the middle never leaves a broken log behind. Limits are 0 (none) or at least 65536 bytes.

Run it locally

dotnet run --project PikBot

Only one instance can poll a bot at a time: stop the one on the server while you run it locally, or create a second bot for testing.

Deployment

deploy.sh deploys over ssh to a Linux server with the .NET 10 runtime, where the bot runs as the systemd user service pik-bot (e.g. next to People I Know). It keeps the releases side by side:

~/pik-bot/releases/<timestamp>/   one folder per deployment
~/pik-bot/current                 symlink to the running release
~/pik-bot/shared/                 appsettings.Production.json, messages.jsonl, strangers.jsonl and logs/

For the first deployment, create the settings on the server:

ssh user@server 'mkdir -p ~/pik-bot/shared && chmod 700 ~/pik-bot/shared'
scp appsettings.Production.json user@server:pik-bot/shared/

Then deploy:

HOST=user@server ./deploy.sh              # test, build, upload, install deploy/pik-bot.service and switch
HOST=user@server ./deploy.sh --rollback   # back to the previous release

Instead of passing HOST every time, put HOST=user@server into deploy.env next to the script; git ignores it. The server needs lingering enabled for your user (loginctl enable-linger), so the service runs without a login.

The script waits until the bot logs "Listening as @yourbot", otherwise it shows the service's log and fails. On the server, systemctl --user status pik-bot and journalctl --user --unit pik-bot show what the bot does. If the bot can't reach Telegram, e.g. right after a reboot, it exits and systemd starts it again 10 seconds later.

Running the tests

dotnet test

The unit tests cover the message parsing, the choice between several contacts, the allowlist, the Keycloak token handling and the API requests, without Telegram, Keycloak or People I Know.

Project layout

Folder What's in it
PikBot/Notes NoteBot, the bot's logic: parsing "Name: note", searching, asking, saving
PikBot/Chat Telegram: long polling (TelegramBotService) and sending messages and buttons (TelegramChat)
PikBot/PeopleIKnow The API client and the Keycloak service-account token
PikBot/MessageLog The message logs
PikBot/Configuration Settings and their startup check
PikBot.UnitTests xUnit tests
deploy The systemd unit used by deploy.sh

License

MIT, see LICENSE.