Перейти к основному содержимому
S

dsh-telegram-bot

soffits/dsh-telegram-bot

Telegram client for DSH sessions, one forum topic per session shared with the Web UI: streamed answers, turns from other clients mirrored in, tool approvals and ask_user_question as buttons, model and permission controls, photos, files and transcribed voice messages, and a send-to-topic API for scripts and other plugins. Maintained fork of Boobaw/dsh-telegram-bot.

Установка

dsh plugin --profile web add github:soffits/dsh-telegram-bot

README

dsh-telegram-bot

This is a maintained fork of Boobaw/dsh-telegram-bot with /new, user-created topics with a workspace picker, two-way sync, sending into topics by thread id, and reply, quote and forward context. See MAINTAINING.md for what differs and how upstream changes are merged in.

Telegram client for DeepSeek Harness. It connects a DSH profile to a Telegram bot and keeps the same DSH sessions available in both interfaces.

Demo

First setup: https://youtu.be/QEeVucfBsWk

Installation, bot token, the allowlist, /start, /sessions and a test prompt.

Enable Threaded mode

BotFather: Bot Settings → Threaded mode → Enable

BotFather: Bot Settings → Threaded mode → Enable. Leave Disallow users to create new threads off: you create a topic for each conversation yourself.

Features

  • One Telegram topic per DSH session; Web and Telegram use the same session.

  • You create the topics. A new topic asks which workspace to use, then whether to start a new session or continue an existing one from that workspace. The message that opened the topic runs once the session is chosen.

  • Topic names are yours: the bot never renames a topic after the session title. /rename renames it on request.

  • A Telegram session is titled Telegram-<person>-<what the conversation is about> in DSH, for example Telegram-Ana-Plan a weekend trip, so the sidebar shows where each session comes from and whose chat it is. <person> is the name set for the chat's user in userNames or userNamesFile, else the user's Telegram first name; in a group it is the group's title. The last part is DSH's own title from its title model; until it exists, and for good when no title model is set up, the topic name stands in for it. In a chat without topics it is DSH's title or, without a title model, the first words of the first message. Sessions with titles from earlier versions (<topic name> · <task>, a bare topic name) are moved to this form when the bot starts. Earlier versions put the sender line (before 0.6.1) and reply or forward context (before 0.6.2) at the top of each prompt, so some first-prompt titles read like Telegram-Ana-[Telegram message from Ana (@ana,; on start the bot scans every DSH session once and retitles those from the first words the person actually sent. A title someone types for the session is left alone.

  • Renaming a topic also records a short note in its session, such as Telegram topic renamed: "Old" -> "New" (thread 123), so searching earlier sessions finds it under either name.

  • A session the bot creates for a topic is never handed out as a blank session. DSH's New conversation reuses a session that has not started a turn yet; the bot therefore starts one empty turn as soon as it creates a session, and stops it before any model request. Without this, a topic session waiting for its first message could be picked up by the Web UI, and that Web chat would be mirrored into the topic.

  • Deleted topics clean themselves up: when Telegram answers any call for a topic with "message thread not found", TOPIC_ID_INVALID or TOPIC_DELETED, the bot drops that topic's session binding and name and logs it. The session stays in DSH. A closed topic keeps its binding, since it can be reopened.

  • /workspace moves the topic to another workspace: pick the workspace, then a new or existing session there. A session's working directory is fixed when it is created, so the previous session is not continued in this topic; it stays in DSH and can be bound again later as an existing session.

  • Two-way sync: turns started anywhere else (Web UI, scheduled tasks, other plugins) also appear in the session's topic. The prompt is shown with a From Web or Scheduled task label, followed by the streamed answer. Messages sent from Telegram are not echoed back, and context that plugins add on their own (time, runtime notes) is not shown. A Telegram message sent while such a turn runs waits for it. Approvals and questions from those turns are answered where the turn started. Turn this off with Show turns from other clients.

  • /sessions lists workspaces and existing sessions, and can create a new session in a selected workspace.

  • Assistant answers stream into the topic with Telegram Markdown formatting. A message sent while the agent is working (text, photos, files, voice, forwards, replies) goes into the running turn, the way a message typed into the DSH Web UI during a turn does: the agent sees it at its next step, and the message gets a 👀 reaction (a short note where reactions are unavailable). If the turn ends just as the message arrives, DSH starts a new turn for it, and that turn's answer appears in the topic. /clear removes Telegram messages the agent has not picked up yet without stopping the current answer. Set busyMessages: queue to hold such messages until the turn ends instead.

  • Files the agent shows in the Web UI also reach the topic: files it hands over with present, and local images in its final answer (![alt](/path/to/image.png)), are uploaded as photos (JPEG, PNG, WebP up to 10 MB) or documents (up to 50 MB) and logged like telegram_send messages. A file already sent to the topic earlier in the same turn (by telegram_send from that session, by present, or in the answer) is not uploaded again. This follows Show turns from other clients for turns started elsewhere.

  • Automatic goal rounds of a topic's session are shown in the topic like a Telegram turn, with thinking, tool calls and the final answer, also when Show turns from other clients is off. Their approvals and questions are answered in the topic.

  • While a turn runs in a topic's session (started from Telegram or shown from another client), that topic shows "typing…". Each topic shows its own; it stops when the turn ends, fails or is stopped.

  • Reasoning and tool calls are shown as temporary messages and removed after the answer. Each tool-call entry is capped at two lines.

  • Subagents show in the topic. When a turn the topic shows starts subagents, one quiet status message lists them, each with its description, model and running time, and is edited in place as they start and finish (✓ done, ✗ failed with the reason). Changes that land within about 1.5 seconds share one edit, and running times are refreshed at most once a minute, which keeps well inside Telegram's edit limits. Subagents started by subagents are listed under their parent. Once all of them are done the message stays as it is, and the next subagent opens a new one. For example:

    🤖 3 subagents · 1 running
    ✓ Compare flight prices · claude-opus-5-5 · 2m 14s
    ↳ ✓ Check baggage rules · claude-haiku-4-5 · 41s
    ⏳ Find a hotel near the venue · deepseek-v4-flash · 3m
    
  • /agents lists the session's running and most recent subagents (up to eight, nested ones included), with their state, model, time, when they started and the beginning of their last report (the last message they sent their parent, or their final answer). It reads DSH's saved sessions, so it also covers subagents from before a restart; one cut off by a restart shows as interrupted.

  • Inline controls for model, reasoning effort, permission mode and context usage. The model picker offers every provider and model of the Web UI's model picker (provider first, then its models, with paging) and switches the session the way the Web UI does, which also makes the pick the default for new sessions. The panel always shows the model the session runs now; /new starts the next session on that model.

  • Tool approvals with Deny / Allow buttons.

  • ask_user_question support: options, multi-select, custom answers and plan review.

  • Documents and photos sent in a session topic are saved as DSH attachments and passed to the agent.

  • Voice messages, audio files and round video messages are saved as files and transcribed; the agent gets the transcript and the file's path, so it can check a doubtful transcript against the recording. See Voice messages.

  • Every prompt from Telegram comes right after a short notice naming the sender and when the message was sent, such as [Telegram message from Ana Silva (@ana, user id 123), sent Mon 2026-03-02 09:41 UTC+01:00], so the agent knows who is writing when several allowed users share the bot, and how much time passed between messages (a queued message or one that waited out a restart keeps its real time). The time is Telegram's own (for an edited message, the edit), shown with weekday, date, local time and UTC offset in timeZone; times in reply and forward context use the same zone. The same notice carries the message's context: what it replies to (with the quoted text), a message the bot posted for someone else, or where a forward comes from. The notice is its own message (source kind telegram-sender), so the prompt holds only what the person sent (for a forward, the forwarded text) and DSH's first-prompt title never starts with bot text. Prompts typed in the Web UI are not labelled. The sender is also recorded as data on the prompt's source as principal, the field DSH uses for the caller behind a user message: { kind: 'telegram-user', channel: 'telegram', id: '123', name: 'Ana Silva', username: 'ana', chat: { id, thread, name } }, where chat is the chat, its topic thread and the topic's name. Scripts that read session logs can use it instead of parsing the line.

  • Replies, quotes and forwards keep their context. The agent sees the text of the replied-to message (or only the quoted part), who wrote it and when; a replied-to photo or document is attached too. A forwarded message is labelled with its origin (person, hidden account, group or channel with a message link) and original date. Several messages forwarded together become one prompt, and forwarded text never runs as a command. Long replied-to text is cut at about 2,000 characters with a note.

  • Replies to messages sent into a topic by a script, job, plugin or another session (see Send to a topic) also carry the full original text, when it was sent, and the sending session and job, even if the topic has moved to a new session since.

  • /new, /workspace, /last, /agents, /goal, /rename, /topic, /fork, /clear, /stop, /restart, /status and /menu.

  • /goal shows the current DSH goal and the command hints. /goal <objective> creates or replaces the goal and starts working immediately; /goal edit <objective> updates the objective and resumes a paused, blocked or disarmed goal; /goal pause, /goal resume and /goal clear manage the current goal. /goal <objective> and /goal edit <objective> replace the current panel with one fresh message; later goal changes edit that message in place. The panel is never pinned.

  • /new in a session topic starts a fresh DSH session in the same workspace and binds it to the same topic; the previous session stays in DSH. In All it opens a new session topic.

  • One session is bound to at most one topic: binding it to a new topic releases the old one.

  • /fork [name] creates a DSH session fork in a new Telegram topic; without a name it uses the previous title plus the branch number.

  • The session picker also has 🔀 Continue in Telegram fork; automatic fork topics end with (N).

  • ▶️ Continue in Telegram from All opens a fresh topic for the session. From inside a topic it continues in that topic. The previous topic stays in Telegram and can be deleted manually; reusing it from All is unsafe because Telegram can keep accepting messages for a topic deleted in the client.

  • English and Russian bot messages.

  • Bot token stays in the DSH credential store.

Requirements

  • DSH 0.2.1-rc.2 or newer, Node.js 22+.
  • A Telegram bot token from @BotFather.
  • Threaded mode enabled in BotFather, Topics enabled in the bot chat, and Disallow users to create new threads left off.

Install

From npm:

npx @deepseek-ai/dsh plugin --profile web add @soffits/dsh-telegram-bot@latest

From a clone of this repository:

npx @deepseek-ai/dsh plugin --profile web add .

The unscoped dsh-telegram-bot package on npm is the upstream release without this fork's features.

Restart dsh web after installing or updating the plugin. Then open Settings → Telegram.

Configure

FieldMeaning
Bot tokenToken from @BotFather; stored in the credential store
tokenRefCredential/env name for the token; default TELEGRAM_BOT_TOKEN
cwdWorking directory for Telegram-created sessions
agentPresetPreset mounted for Telegram sessions; default standard
timeZoneIANA zone of the people writing to the bot, such as Europe/Berlin; message times are shown in it and DSH gets it as each prompt's client zone, so the time-context clock reads in that zone instead of asking for one. Empty (default) means the DSH process's zone
Allowed usersTelegram user ids or @usernames
Allowed chatsTelegram chat ids or @channelnames
controlChatChat id or @channelname for lifecycle notices ("Telegram bot enabled", Threaded mode warnings); empty means the private chat of the first allowed user
Show model thinkingShow reasoning in a temporary message
Show tool callsShow tool calls in a temporary message
Show turns from other clients (mirrorTurns)Mirror turns started outside Telegram into the bound topic; default on
busyMessagessteer (default): messages sent during a turn go into it; queue: they wait until the turn ends
transcriberdsh (default), command or off; see Voice messages
transcribeLanguageLanguage hint for DSH speech-to-text, such as zh or en; empty uses its own setting
transcribeCommandProgram and arguments for transcriber: command
ffmpegPathffmpeg used to decode recordings for DSH speech-to-text; default ffmpeg
userNamesNames for Telegram user ids (or group chat ids) in session titles, such as { "123456789": "Alex" }
userNamesFileJSON file with more such names, re-read when it changes; userNames wins
userNamesKeyKey of the id → name object inside userNamesFile; empty means the whole file is the map
Bot languageen (default) or ru
Enable botStart or pause Telegram polling

The voice fields, the name fields, timeZone, controlChat and busyMessages have no controls on the settings page yet; set them in the profile's cordis.patch.yml under the telegram-bot row's config.

The token field only reports whether a token is configured. A token supplied through the environment cannot be overwritten from the page.

First run

  1. Create a bot with @BotFather and save its token in Settings → Telegram.
  2. In @BotFather open Bot Settings → Threaded mode and enable it. Leave Disallow users to create new threads off.
  3. Open the bot chat, tap the bot name and enable Topics.
  4. Send /start in All. With an empty allowlist the bot replies with your user and chat ids.
  5. Add your user id to Allowed users and press Save. List your own id first: lifecycle notices go to the first allowed user's private chat unless controlChat names another chat. If the first entry is a @username, set controlChat, since a username has no chat id the bot can send to.
  6. Create a topic and send a message in it. Choose a workspace, then New session or one of the listed sessions. Your message runs in that session.

A message sent in All makes Telegram create a topic for it; the bot treats it like any new topic and asks for the workspace (if Telegram delivers it to All instead, the bot opens a new topic in the default workspace). Chat-wide commands are the exception: when /start, /help, /sessions, /status, /menu, /id, /ping or /restart is sent in All and Telegram makes a topic for it, the bot answers in All and deletes that topic. If the topic cannot be deleted, it leaves a short note there. /sessions in All still opens existing sessions in new topics, and commands such as /fork and /last work as before.

Topics bound by an earlier version keep their sessions after an upgrade.

Delete topics

  • /topic delete <name or thread id> deletes one known topic and its Telegram messages. Numeric targets must be real topic thread ids; ids larger than 2^31 (for example a user id) are rejected. Send /id inside the topic to read its id.
  • /topic wipe asks for confirmation first; send /topic wipe confirm to delete every topic known to the bot in this chat. DSH sessions themselves are not deleted.

Topics are known after the bot creates them, after /rename, or after Telegram reports a topic creation/rename. Unknown topics cannot be listed through the Bot API.

Troubleshooting topics

The bot checks has_topics_enabled and allows_users_to_create_topics on startup, writes them to ~/.dsh/telegram/status.json, and posts a warning in the control chat when Threaded mode is off or users cannot create topics.

A correct configuration contains:

"threadedMode": true,
"usersCanCreateTopics": true

Topic creation is single-shot: a network timeout is never retried, because retrying a createForumTopic that Telegram already committed creates a duplicate topic. Concurrent open requests for the same session are coalesced.

Private-chat topics send with message_thread_id. If Telegram answers message thread not found, the bot retries once with direct_messages_topic_id (the Bot API 10 direct-message-topic field). A send that Telegram accepts without returning any topic field is treated as undelivered, so a deleted topic is recreated instead of silently receiving messages in All.

Send to a topic

Scripts, scheduled jobs, other plugins and agents can post into a topic by its numeric thread id (/id in the topic shows it). The message (text, files, a sticker) appears in the topic and is also recorded in the session bound to that topic, without starting a turn, labelled with who sent it. The record's source (kind telegram-post) names the topic it went to (channel: 'telegram', chatId, threadId, topic) and the sender as principal: { kind: 'cron-job', channel: 'cron', id, name, sessionId? } for a scheduled job, { kind: 'dsh-session', channel: 'dsh', id } for a DSH session, or { kind: 'external', channel: 'external', id: <label> } for a caller that gave only a label. This holds for the bound session's own sends too, so a Web UI reader of that session sees the same pictures, files and stickers: pictures and stickers (as their still image) are recorded as images, other files as file attachments. An idle session gets the record at once; a busy one gets it at its next step. Thread ids belong to one chat, so the message goes to the chat the bot saw that thread in (its binding or known name), not the chat that last wrote to the bot. A thread id the bot does not know in any chat is an error; nothing is created. In the rare case two chats have a topic with the same thread id, the send fails until the caller names the chat (chat, --chat). Topic names are only labels, never addresses. A known topic with no session gets a new one first, made the way /new makes it (the configured working directory and preset, titled after the topic), so the message is recorded; only a topic whose user is still choosing its session just shows the message, and the result says so (note). If no session can take the record, the message is still sent and the result carries recordError.

The bot also remembers each such send ($DSH_HOME/telegram/sent-messages.json: the last 1,000 sends from the past 180 days, text up to 20,000 characters). When someone replies to or quotes one of those messages, the agent gets the whole original text, however many Telegram messages it was split into, with its send time, job name and sending session, and a hint to open that session for more context. This works after /new too, when the current session never saw the message.

The bot learns a topic's name when it creates the topic, when Telegram reports a topic being created or renamed, and on /rename, and uses it in the labels of recorded messages and as the placeholder in session titles.

From a shell (no bot token needed):

dsh-telegram-send --thread 12345 "Backup finished"
some-report | dsh-telegram-send --thread 12345 --job nightly-report
dsh-telegram-send --thread 12345 --file /tmp/report.pdf "Monthly report"

Who sent it: --job <name> names the job or script, and --from-session <id> the DSH session. Inside a DSH session --from-session defaults to $DSH_SESSION_ID; pass --from-session '' to leave it out. --from <label> is a free-form label for senders that are neither. When the sending session is the one bound to the topic, it gets no second copy.

Long text is split into several Telegram messages. Every --file is sent after the text, one message per file.

The command writes the request into $DSH_HOME/telegram/outbox/ and waits up to --timeout seconds (default 30) for the plugin's answer. Exit codes: 0 sent, 1 failed (the error is printed, for example an unknown thread id), 2 bad arguments, 3 still queued (the bot sends it once it runs). --no-wait returns right after queueing. The spool keeps requests while DSH is stopped, which is why it is a directory and not a socket; a request interrupted by a restart is sent again. The command is installed as the package's bin; link it onto your PATH if needed (node_modules/.bin/dsh-telegram-send in the profile).

From another Host plugin:

const result = await ctx.get('telegramTopics').send({
  to: '12345',                  // the topic's thread id
  text: 'Backup **finished**',
  files: ['/tmp/report.pdf'],   // absolute paths, optional
  from: { job: 'backup', sessionId: 'session-…' }, // optional; `label` for other senders
})
// { chatId, threadId, topic, sessionId, recorded, messageIds }, plus note or recordError when it was not recorded
ctx.get('telegramTopics').topics() // [{ chatId, threadId, name, sessionId }]: known topics in every chat, name may be null

send rejects when the message was not sent. Errors that a retry cannot fix (an unknown thread id, a topic that was deleted, a missing or oversized file, nothing to send, or a failure after part of a long message already went out) carry retryable: false; others, such as the bot not running yet, are worth trying again. This is the shape dsh-cron-jobs expects from a delivery channel, so deliver: { via: telegramTopics, to: 12345 } sends scheduled job results into the topic, with the job and its session named as the sender.

From an agent: the telegram_send tool takes thread (the thread id), text, files (absolute paths) and, only when two chats share the thread id, chat. The calling session is named as the sender and does not get a copy of its own message.

Text is Markdown, converted for Telegram like assistant answers. JPEG, PNG and WebP files up to 10 MB are sent as photos, other files as documents (up to 50 MB).

Stickers

A sticker sent to the bot (also when replied to) reaches the agent as an image with a note naming its emoji, set and id, plus the meaning saved for it, if any. Static stickers are passed as they are; animated (.tgs) and video (.webm) stickers use Telegram's thumbnail, or for a video sticker without one, its first frame (ffmpeg, ffmpegPath). An animated sticker without a thumbnail comes as the note only.

Every received sticker is kept in a sticker library ($DSH_HOME/telegram/stickers.json, previews in sticker-previews/), keyed by Telegram's file_unique_id, with the file_id needed to send it again. The agent's telegram_sticker tool works with it:

ActionDoes
findSearch by words in the saved meaning, emoji, set name or title (query, emoji, set, limit)
viewShow one sticker (id) as an image
noteSave what a sticker means and when to use it (id, meaning)
add_setAdd every sticker of a set (set: its name or t.me/addstickers/ link)
sendSend a sticker (id) into a topic (thread); recorded in the bound session and the send log like telegram_send

A Telegram turn that already sent its own topic a sticker, file or message and ends with no text posts nothing more, so a sticker can be the whole reply. A turn that sent nothing and has no text still ends with ✅ Done.

Models often can't end a turn with no text at all (DSH counts an empty answer as a failed EMPTY_RESPONSE call and retries or falls back), so a final answer of exactly [SILENT] also posts nothing: after a sticker, or alone when the agent chooses to stay quiet. Text that may still turn into [SILENT] is held back while it streams, so the marker never shows up in the topic.

Voice messages

Voice messages, audio files and round video messages (also when replied to or forwarded) are downloaded, stored as a DSH file attachment and transcribed. The agent receives a note with the transcript, who transcribed it and the stored file's path, followed by the file itself. When transcription fails or is off, the file is still passed on and the note says why. A recording sent without text gets no "analyze the file" prompt: its transcript is the message.

  • transcriber: dsh (default) uses DSH's own speech-to-text service, the one behind voice input in the Web UI (the @deepseek-ai/dsh-experimental-voice-input-bundle bundle with a provider such as the local SenseVoice model). Its default provider and language apply; transcribeLanguage overrides the language for Telegram. Recordings are decoded to 16 kHz mono WAV with ffmpeg, which must be installed (ffmpegPath).
  • transcriber: command runs a program of your choice without a shell, for example a Whisper script or a client for a cloud service. {file} in transcribeCommand is replaced by the recording's path (it is appended when missing), and the transcript is read from standard output. Keys for a cloud service belong in that program's environment or the DSH credential store, not in the plugin config.
  • transcriber: off passes only the file.
- id: telegram-bot
  config:
    transcriber: command
    transcribeCommand: ["/usr/local/bin/transcribe", "--language", "auto", "{file}"]

Plugins page

The plugin page is informational. It points to Settings → Telegram and lists the manual configuration files. Use the bundle switch there to enable or disable the plugin; Enable bot is a soft pause that keeps the plugin loaded but stops polling.

Headless profile

The bot can run without the Web UI:

mkdir -p ~/.dsh/profiles/tg
cd ~/.dsh/profiles/tg

package.json:

{
  "name": "dsh-profile-tg",
  "private": true,
  "dependencies": { "@soffits/dsh-telegram-bot": "latest" },
  "dsh": {
    "profile": {
      "bundles": ["@deepseek-ai/dsh-base", "@soffits/dsh-telegram-bot"]
    }
  }
}

cordis.patch.yml:

- id: telegram-bot
  name: '@soffits/dsh-telegram-bot'
  config:
    enabled: true
    allowedUsers: ["<user-id>"]
    allowedChats: ["<chat-id>"]

Install and run:

npm install
printf 'TELEGRAM_BOT_TOKEN=%s\n' '<token>' >> ~/.dsh/.env
chmod 600 ~/.dsh/.env
npx @deepseek-ai/dsh --profile tg

Do not put the token in cordis.patch.yml.

Security

  • The bot token lives in the credential store, not in the profile patch.
  • Empty Allowed users answers only in private chats with the setup hint.
  • Group and channel chats require an entry in Allowed chats.
  • Do not run two pollers with the same token; Telegram returns 409 Conflict.
  • A DSH plugin runs in-process with the Host. Install only source you trust.

Development

No build step is needed.

npm install
node --check index.js
node --check client.js
npm test

src/app.js is the Host runtime: Telegram polling, topic routing and the session bridge. src/update-ledger.js persists Telegram update cursors, src/admission.js uses the native DSH session queue. src/formatting.js, src/state.js, src/status.js, src/utils.js, src/errors.js, src/config.js and src/constants.js hold the supporting layers. src/index.js is the public entry point; root index.js is the loader-compatible wrapper. Root client.js is the loader-compatible client bundle. src/client.js contains the client source. src/message-context.js turns replies, quotes and forwards into the labelled context the agent reads. src/topics.js resolves send targets to thread ids, picks the topic field for private-chat topics, checks delivery and recognises deleted topics, src/voice.js decodes and transcribes recordings, src/outbox.js is the file spool behind bin/dsh-telegram-send.js, src/sent-log.js remembers sent messages for later replies, and src/steer.js sends messages into a running turn, and src/stickers.js is the sticker library, and src/models.js reads a session's live model and the Web model catalog for the model picker. The plugin adds two model-facing tools, telegram_send and telegram_sticker, and no system-prompt text.

License

MIT

Credits

Markdown to Telegram formatting uses telegramify-markdown (MIT).

Похожие плагины