Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Telegram bot token from @BotFather
BOT_TOKEN=123456789:AAExampleTokenReplaceMe

# Telegram numeric user ID of the owner (get from @userinfobot)
OWNER_ID=123456789

# Secret path segment used to validate incoming webhook requests from Telegram
WEBHOOK_SECRET=change-this-to-a-long-random-string

# Public HTTPS base URL of this deployment (e.g. https://your-app.deno.dev)
PUBLIC_URL=https://your-app.deno.dev
101 changes: 101 additions & 0 deletions .github/workflows/codeql.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# For most projects, this workflow file will not need changing; you simply need
# to commit it to your repository.
#
# You may wish to alter this file to override the set of languages analyzed,
# or to provide custom queries or build logic.
#
# ******** NOTE ********
# We have attempted to detect the languages in your repository. Please check
# the `language` matrix defined below to confirm you have the correct set of
# supported CodeQL languages.
#
name: "CodeQL Advanced"

on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
schedule:
- cron: '15 21 * * 3'

jobs:
analyze:
name: Analyze (${{ matrix.language }})
# Runner size impacts CodeQL analysis time. To learn more, please see:
# - https://gh.io/recommended-hardware-resources-for-running-codeql
# - https://gh.io/supported-runners-and-hardware-resources
# - https://gh.io/using-larger-runners (GitHub.com only)
# Consider using larger runners or machines with greater resources for possible analysis time improvements.
runs-on: ${{ (matrix.language == 'swift' && 'macos-latest') || 'ubuntu-latest' }}
permissions:
# required for all workflows
security-events: write

# required to fetch internal or private CodeQL packs
packages: read

# only required for workflows in private repositories
actions: read
contents: read

strategy:
fail-fast: false
matrix:
include:
- language: actions
build-mode: none
- language: javascript-typescript
build-mode: none
# CodeQL supports the following values keywords for 'language': 'actions', 'c-cpp', 'csharp', 'go', 'java-kotlin', 'javascript-typescript', 'python', 'ruby', 'rust', 'swift'
# Use `c-cpp` to analyze code written in C, C++ or both
# Use 'java-kotlin' to analyze code written in Java, Kotlin or both
# Use 'javascript-typescript' to analyze code written in JavaScript, TypeScript or both
# To learn more about changing the languages that are analyzed or customizing the build mode for your analysis,
# see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/customizing-your-advanced-setup-for-code-scanning.
# If you are analyzing a compiled language, you can modify the 'build-mode' for that language to customize how
# your codebase is analyzed, see https://docs.github.com/en/code-security/code-scanning/creating-an-advanced-setup-for-code-scanning/codeql-code-scanning-for-compiled-languages
steps:
- name: Checkout repository
uses: actions/checkout@v7

# Add any setup steps before running the `github/codeql-action/init` action.
# This includes steps like installing compilers or runtimes (`actions/setup-node`
# or others). This is typically only required for manual builds.
# - name: Setup runtime (example)
# uses: actions/setup-example@v1

# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v4
with:
languages: ${{ matrix.language }}
build-mode: ${{ matrix.build-mode }}
# If you wish to specify custom queries, you can do so here or in a config file.
# By default, queries listed here will override any specified in a config file.
# Prefix the list here with "+" to use these queries and those in the config file.

# For more details on CodeQL's query packs, refer to: https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
# queries: security-extended,security-and-quality

# If the analyze step fails for one of the languages you are analyzing with
# "We were unable to automatically build your code", modify the matrix above
# to set the build mode to "manual" for that language. Then modify this step
# to build your code.
# ℹ️ Command-line programs to run using the OS shell.
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
- name: Run manual build steps
if: matrix.build-mode == 'manual'
shell: bash
run: |
echo 'If you are using a "manual" build mode for one or more of the' \
'languages you are analyzing, replace this with the commands to build' \
'your code, for example:'
echo ' make bootstrap'
echo ' make release'
exit 1

- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v4
with:
category: "/language:${{matrix.language}}"
51 changes: 51 additions & 0 deletions .github/workflows/jekyll-gh-pages.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Sample workflow for building and deploying a Jekyll site to GitHub Pages
name: Deploy Jekyll with GitHub Pages dependencies preinstalled

on:
# Runs on pushes targeting the default branch
push:
branches: ["main"]

# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false

jobs:
# Build job
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Build with Jekyll
uses: actions/jekyll-build-pages@v1
with:
source: ./
destination: ./_site
- name: Upload artifact
uses: actions/upload-pages-artifact@v3

# Deployment job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
needs: build
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v5
163 changes: 74 additions & 89 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,113 +1,98 @@
# wrappergram
# Telegram-Bot — Production Build

<div align="center">
A Deno/V8-based Telegram business management, communication, and automation
system, implementing the owner/users/groups model described in the system
overview: publishing, editable buttons, scheduling, destination management,
access control, and group-mention assistance.

[![Bot API](https://img.shields.io/badge/Bot%20API-7.7+-blue?logo=telegram&style=flat&labelColor=000&color=3b82f6)](https://core.telegram.org/bots/api)
[![npm](https://img.shields.io/npm/v/wrappergram?logo=npm&style=flat&labelColor=000&color=3b82f6)](https://www.npmjs.org/package/wrappergram)
[![npm downloads](https://img.shields.io/npm/dw/wrappergram?logo=npm&style=flat&labelColor=000&color=3b82f6)](https://www.npmjs.org/package/wrappergram)
[![JSR](https://jsr.io/badges/@gramio/wrappergram)](https://jsr.io/@gramio/wrappergram)
[![JSR Score](https://jsr.io/badges/@gramio/wrappergram/score)](https://jsr.io/@gramio/wrappergram)
[![bundlejs](<https://deno.bundlejs.com/badge?q=wrappergram&treeshake=[*]&text=%22const+telegram+=+new+Telegram(process.env.BOT_TOKEN+as+string);\n\ntelegram.api.sendMessage({\n++++chat_id:+617580375,\n++++text:+%22Hello!%22,\n});%22>)](https://bundlejs.com/?q=wrappergram&treeshake=%5B*%5D&text=%22const+telegram+%3D+new+Telegram%28process.env.BOT_TOKEN+as+string%29%3B%5Cn%5Cntelegram.api.sendMessage%28%7B%5Cn++++chat_id%3A+617580375%2C%5Cn++++text%3A+%5C%22Hello%21%5C%22%2C%5Cn%7D%29%3B%22)
## Stack

</div>
- **Runtime:** Deno (webhook server via `Deno.serve`, background jobs via `Deno.cron`)
- **Telegram framework:** [grammY](https://grammy.dev)
- **Storage:** Deno KV (built-in, zero external dependency; swap for Postgres/etc. by reimplementing `src/db.ts` if you outgrow it)
- **Hosting:** Deno Deploy (recommended) or any host that runs Deno with `--unstable-kv --unstable-cron`

Simple and tiny code-generated **Telegram Bot API** wrapper for TypeScript/JavaScript with [file upload](https://core.telegram.org/bots/api#sending-files) support.
## Project layout

🌐 **Multi-runtime** - Works on [Node.js](https://nodejs.org/), [Bun](https://bun.sh/) and [Deno](https://deno.com/)

⚙️ **Code-generated** - For example, [code-generated and auto-published Telegram Bot API types](https://github.com/gramiojs/types))

🛡️ **Type-safe** - Written in TypeScript with love ❤️

🤏 **Tiny** - Simple `sendMessage` call cost some [![bundlejs](https://edge.bundlejs.com/?text=import%20%7B%20Telegram%20%7D%20from%20%22wrappergram%22%3B%0A%0Aconst%20telegram%20%3D%20new%20Telegram%28process.env.BOT_TOKEN%29%3B%0A%0Atelegram.api.sendMessage%28%7B%0A%20%20%20%20chat_id%3A%20617580375%2C%0A%20%20%20%20text%3A%20%22Hello%21%22%2C%0A%7D%29%3B&badge)](https://bundlejs.com/?q=wrappergram&treeshake=%5B*%5D&text=%22const+telegram+%3D+new+Telegram%28process.env.BOT_TOKEN+as+string%29%3B%5Cn%5Cntelegram.api.sendMessage%28%7B%5Cn++++chat_id%3A+617580375%2C%5Cn++++text%3A+%5C%22Hello%21%5C%22%2C%5Cn%7D%29%3B%22) in bundle size. So it is a good choice for browser/serverless environments

But if you need a more complete framework, then please look to [`GramIO`](https://gramio.dev/).

### Usage

```ts
import { Telegram, getUpdates } from "wrappergram";

const telegram = new Telegram(process.env.BOT_TOKEN as string);

telegram.api.sendMessage({
chat_id: 617580375,
text: "Hello!",
});

for await (const update of getUpdates(telegram)) {
console.log(update);

if (update.message?.from) {
telegram.api.sendMessage({
chat_id: update.message.from.id,
text: "Hi! Thanks for the message",
});
}
}
```
telegram-bot/
├── main.ts # webhook server + cron entry point
├── deno.json # tasks + import map
├── .env.example # required environment variables
├── scripts/set_webhook.ts # one-time webhook registration
└── src/
├── config.ts # env var loading
├── types.ts # domain types
├── db.ts # Deno KV persistence layer
├── bot.ts # command/message routing
├── middleware/auth.ts # owner-only / approved-only gates
└── features/
├── destinations.ts # connect/list/remove channels & groups
├── publish.ts # multi-destination publish + wizard
├── buttons.ts # update a button's URL across old posts
├── scheduling.ts # /schedule + cron-driven publication
├── access.ts # request/approve/decline access
├── groupMention.ts # respond only when @mentioned in groups
└── assistance.ts # simple FAQ-style business assistance
```

This example on bundlejs cost [![bundlejs](https://deno.bundlejs.com/badge?q=wrappergram&treeshake=[*]&share=MYewdgzgLgBFCmAbeBzATgQwLYwLwzHgHcYAVJVTLACgAc0Rh4IIA6eMAN1YCEB5UgH1SfANIBRAHIBKANwAoeQmTpsrDLQCWrCBwAmAWWYQMKeNQDe8mDZjAAFhiiDNegFwwAbAEYA7AFYADgAGAGYAgBprWwQADygPACIACSREEABCRKiAXzlFADMQNBgMIgxNWGpQSFgAV1o9J3gYEAKYMygAVUbmiGplSmxpaRgrWztwCBBkVnSUagamhHzom012xd6EVixjU3gAflYChixR8YmYilUsdS0dfSMWA8s1q4mHJxd3GCXm3b7MwnM6sVxRD4fOIJGApTQZMiOMAAawgMCKJSg9haexeZmy7wmeQURPkOSAA)](https://bundlejs.com/?q=wrappergram&treeshake=%5B*%5D&share=MYewdgzgLgBFCmAbeBzATgQwLYwLwzHgHcYAVJVTLACgAc0Rh4IIA6eMAN1YCEB5UgH1SfANIBRAHIBKANwAoeQmTpsrDLQCWrCBwAmAWWYQMKeNQDe8mDZjAAFhiiDNegFwwAbAEYA7AFYADgAGAGYAgBprWwQADygPACIACSREEABCRKiAXzlFADMQNBgMIgxNWGpQSFgAV1o9J3gYEAKYMygAVUbmiGplSmxpaRgrWztwCBBkVnSUagamhHzom012xd6EVixjU3gAflYChixR8YmYilUsdS0dfSMWA8s1q4mHJxd3GCXm3b7MwnM6sVxRD4fOIJGApTQZMiOMAAawgMCKJSg9haexeZmy7wmeQURPkOSAA)

> [!IMPORTANT]
> Use `getUpdates` only **once** in your code otherwise it will cause double calls to [getUpdates](https://core.telegram.org/bots/api#getupdates)
## Setup

### Call api
1. **Create the bot** with [@BotFather](https://t.me/BotFather) and copy the token.
2. **Get your Telegram user id** from [@userinfobot](https://t.me/userinfobot) — this becomes `OWNER_ID`.
3. Copy `.env.example` to `.env` and fill in `BOT_TOKEN`, `OWNER_ID`, a random `WEBHOOK_SECRET`, and `PUBLIC_URL` (set after your first deploy).
4. Install the [Deno CLI](https://deno.com) if running locally.

You can send requests to Telegram Bot API Methods via `telegram.api` with full type-safety!
## Local development (polling is simplest locally, but this build uses webhooks)

```ts
const response = await telegram.api.sendMessage({
chat_id: "@gramio_forum",
text: "Hello, world!",
});
For local testing, the quickest path is a tunnel (e.g. `deno task dev` behind `ngrok http 8000`), setting `PUBLIC_URL` to the tunnel's HTTPS URL, then running:

if (!response.ok) console.error("Something went wrong");
else console.log(`New message id is ${response.result.message_id}`);
```
deno task setwebhook
deno task dev
```

### Send keyboards

For keyboards you need to install [`@gramio/keyboard`](https://www.npmjs.com/package/@gramio/keyboards) library and just use it!
## Deploying to Deno Deploy

```ts
import { Keyboard } from "@gramio/keyboards";
1. Push this project to a GitHub repo.
2. Create a new Deno Deploy project linked to the repo, entry point `main.ts`.
3. Add the environment variables from `.env.example` in the Deno Deploy dashboard.
4. Set `PUBLIC_URL` to your `*.deno.dev` URL, redeploy, then run `deno task setwebhook` locally (pointing at the same env vars) to register the webhook.

// telegram init
telegram.api.sendMessage({
chat_id: "@gramio_forum",
text: "Hello, world!",
reply_markup: new InlineKeyboard().url(
"GitHub",
"https://github.com/gramiojs/wrappergram"
),
});
```
## Using the bot

This example cost - [![bundlejs](<https://deno.bundlejs.com/badge?q=wrappergram,@gramio/keyboards&treeshake=[*],[*]&text=%22const+telegram+=+new+Telegram(process.env.BOT_TOKEN);\n\ntelegram.api.sendMessage({\n++chat_id:+617580375,\n++text:+%22Hello!%22,\n++reply_markup:+new+InlineKeyboard().url(%22GitHub%22,+%22https://github.com/gramiojs/wrappergram%22)\n});%22>)](https://bundlejs.com/?q=wrappergram%2C%40gramio%2Fkeyboards&treeshake=%5B*%5D%2C%5B*%5D&text=%22const+telegram+%3D+new+Telegram%28process.env.BOT_TOKEN%29%3B%5Cn%5Cntelegram.api.sendMessage%28%7B%5Cn++chat_id%3A+617580375%2C%5Cn++text%3A+%5C%22Hello%21%5C%22%2C%5Cn++reply_markup%3A+new+InlineKeyboard%28%29.url%28%5C%22GitHub%5C%22%2C+%5C%22https%3A%2F%2Fgithub.com%2Fgramiojs%2Fwrappergram%5C%22%29%5Cn%7D%29%3B%22)
**Owner commands** (only work for the Telegram account matching `OWNER_ID`):

[Read more here](https://gramio.dev/keyboards/overview)
| Command | Purpose |
|---|---|
| `/adddestination <label>` | Run inside a channel/group to connect it |
| `/listdestinations` | List connected destinations and their ids |
| `/removedestination <id>` | Disconnect a destination |
| `/publish` | Start the guided publish flow (text → buttons → destinations) |
| `/schedule <when> \| <dest ids> \| <text>` | Schedule a post, e.g. `/schedule 2026-09-10T10:00 \| main-channel,promo \| Big sale tomorrow!` |
| `/changebutton <buttonId> <newUrl>` | Update a button's destination across every post that used it |
| `/requests` | Review and approve/decline pending access requests |

### Send files
**User commands:**

[`@gramio/files`](https://gramio.dev/files/overview) already used under the hood so you don't need to install it
| Command | Purpose |
|---|---|
| `/start` | Greeting and basic guidance |
| `/requestaccess` | Ask the owner for approval to use gated features |
| plain text | Answered by the FAQ-style business assistance handler |

```ts
import { MediaUpload } from "wrappergram";
**Groups:** the bot only responds when explicitly mentioned, e.g. `@YourBot price of Product A?`.

telegram.api.sendPhoto({
chat_id: "@gramio_forum",
text: "Hello, world!",
photo: MediaUpload.path("./cute-cat.png"),
});
## Extending

telegram.api.sendDocument({
chat_id: "@gramio_forum",
text: "Hello, world!",
photo: Bun.file("README.md"), // you can use File instance to upload files
});
```
- **Business assistance:** `src/features/assistance.ts` has a small keyword-matched FAQ table — swap the `answerBusinessQuestion` function for an LLM call or CMS lookup as needed.
- **Gated features for approved users:** wrap any handler with the `approvedOnly` middleware from `src/middleware/auth.ts`.
- **Storage:** all persistence goes through `src/db.ts`; replace its internals to move off Deno KV without touching feature code.

This example cost - [![bundlejs](<https://deno.bundlejs.com/badge?q=wrappergram&text=%22const+telegram+=+new+Telegram(process.env.BOT_TOKEN);+\n\ntelegram.api.sendPhoto({+\n++chat_id:+%22@gramio_forum%22,+\n++text:+%22Hello,+world!%22,+\n++photo:+MediaUpload.path(%22./cute-cat.png%22),+\n});%22>)](https://bundlejs.com/?q=wrappergram&treeshake=%5B*%5D&text=%22const+telegram+%3D+new+Telegram%28process.env.BOT_TOKEN%29%3B+%5Cn%5Cntelegram.api.sendPhoto%28%7B+%5Cn++chat_id%3A+%5C%22%40gramio_forum%5C%22%2C+%5Cn++text%3A+%5C%22Hello%2C+world%21%5C%22%2C+%5Cn++photo%3A+MediaUpload.path%28%5C%22.%2Fcute-cat.png%5C%22%29%2C+%5Cn%7D%29%3B%22)
## Data retention

[Read more here](https://gramio.dev/files/overview)
Following the privacy principle in the system overview, only functionally
necessary data is stored permanently (destinations, published posts + button
index, schedules, access decisions). In-progress conversation state (the
publish wizard) is stored with a 30-minute TTL and expires automatically if
abandoned.
Loading