> For the complete documentation index, see [llms.txt](https://help.bots.business/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://help.bots.business/libraries-and-examples/membership.md).

# Check channel membership

Check subscriptions and add optional Force Join to your bot or supergroup with MembershipChecker.

Install `MembershipChecker` to ask Telegram whether a user has joined your configured chats or channels. The check completes through callback commands. Reading cached membership and starting a new check are different operations.

Before checking someone else with `getChatMember`, make the bot an administrator in each target chat; that is the condition under which Telegram guarantees this method for other users. [Telegram reference](https://core.telegram.org/bots/api#getchatmember).

{% stepper %}
{% step %}

### Configure the panel

1. Run `Libs.MembershipChecker.setup()` from an owner-only setup command.
2. Open [**Admin Panel**](https://help.bots.business/use-the-mobile-app/admin-panel.md#open-and-save-a-panel) → **Membership checker options** in the mobile app.
3. Enter target chats, separated by commas, for example `@example_channel`.
4. Choose the automatic checking delay in minutes.
5. Set `onNeedJoining` to `/join-required`, `onJoining` to `/membership-updated`, `onAllJoining` to `/all-joined`, and `onError` to `/membership-error`.
6. Save the panel. Running the updated `setup()` again adds missing fields while preserving your saved values and custom fields. Keep the setup command owner-only.
   {% endstep %}

{% step %}

### Start with a manual check

In `/check`:

{% code title="Start with a manual check · Example 1" overflow="wrap" %}

```javascript
if (!user || !chat || chat.chat_type !== "private") { return; }
Libs.MembershipChecker.check();
Bot.sendMessage("Checking your membership…");
```

{% endcode %}

In `/join-required`:

{% code title="Start with a manual check · Example 2" overflow="wrap" %}

```javascript
if (!options || !options.chat_id) { return; }
Bot.sendMessage("Please join " + options.chat_id + ", then send /check.");
```

{% endcode %}

In `/membership-updated`:

{% code title="Start with a manual check · Example 3" overflow="wrap" %}

```javascript
Bot.sendMessage("Membership updated.");
```

{% endcode %}

In `/all-joined`:

{% code title="Start with a manual check · Example 4" overflow="wrap" %}

```javascript
Bot.sendMessage("You have joined all required channels.");
```

{% endcode %}

In `/membership-error`:

{% code title="Start with a manual check · Example 5" overflow="wrap" %}

```javascript
Bot.sendMessage("Could not check membership. Please try again later.");
```

{% endcode %}

Inspect the detailed error privately in your test bot when diagnosing configuration. Do not send raw provider responses or internal state to every user.
{% endstep %}
{% endstepper %}

## Force Join: require a subscription

Want users to join your channel before using the bot? Enable **Force Join in private chats** in the panel. It is off by default.

Keep these callbacks:

| Field         | Command             |
| ------------- | ------------------- |
| onNeedJoining | `/join-required`    |
| onAllJoining  | `/all-joined`       |
| onStillJoined | `/all-joined`       |
| onError       | `/membership-error` |

Leave the other callback fields empty for this example. Set **Commands available without joining** to `/start,/check`. Use command names separated by commas; aliases are checked against their actual command names.

### Add one line to Before all

In the special `@` command:

```javascript
if (!Libs.MembershipChecker.guard()) { return; }
```

You do not need a separate `handle()` call in this flow.

Keep the `/check` command above. In `/start`, show your welcome message and ask the user to send `/check`. Everything outside the free-command list must wait for a verified subscription. If the first protected command starts a check, the library does not automatically replay that command afterward.

**Keep protected commands in BJS.** Their built-in Answer and Keyboard fields must be empty: returning from `@` does not suppress those fields. Do not cache protected commands or membership callbacks, and invalidate old command/file caches before enabling protection. Cached responses can bypass BJS entirely.

### Use the library's joining button

Replace the earlier `/join-required` example with:

```javascript
const result = options && options.membership_check;
if (!result || !result.notice) { return; }

Api.sendMessage({
  ...result.notice,
  text: "Please join " + Libs.MembershipChecker.getNotJoinedChats() +
    ", then press Joined below."
});
```

The library adds a **Joined** button and validates who pressed it. Keep the supplied destination, button, `on_result` and `bb_options`; add your own text without replacing those fields.

In `/all-joined`:

```javascript
const result = options && options.membership_check;
if (!result || !result.notice) { return; }

Api.sendMessage({
  ...result.notice,
  text: "Subscription verified! You can use the bot now."
});
```

In `/membership-error`:

```javascript
const result = options && options.membership_check;
if (!result || !result.notice) { return; }

Api.sendMessage({
  ...result.notice,
  text: "Could not check your subscription. Please try again later."
});
```

The library calls these result commands. Do not run them manually or use them as public entry points. Typing a callback's name does not grant access.

### How often is membership checked?

`guard()` uses the panel's checking delay, in minutes. A completed positive check permits subsequent protected commands during that time. When the result is stale, a new check is pending, or verification fails, those commands stay blocked. An old `isMember()` cache alone does not authorize Force Join.

This is not an immediate check on every action. For a sensitive action, start a fresh `check()` and perform the action only in its successful callback. Automatic retries and Joined presses have a 15-second cooldown; explicit `check()` keeps its two-second throttle.

## Force Join in a group

To use the same subscription requirement in a supergroup, enable **Force Join in a group** and enter its verified numeric ID in **Force Join supergroup ID**, for example `-1001234567890`. The private and group switches are independent and both default to off.

The bot must be an administrator in the required channels and have permission to restrict members in the configured supergroup. Group Force Join automatically inspects the source member; no `Api.getChatMember` or `Api.restrictChatMember` code is needed in your bot.

The library restricts ordinary members who have not joined, then restores only restrictions it recorded and can still recognize. Administrators, bans and other restrictions are left to a group moderator. Subscription confirmation alone does not mean a group restriction was removed: use `options.membership_check.access_status` when reporting that result.

The supplied `notice` uses Telegram [ephemeral messages](https://core.telegram.org/bots/api#ephemeral-messages-and-commands), visible only to the selected user. There is no public-message fallback. Keep those options when sending the message.

### Keep a private recovery button

A personal group message can disappear. Add a `/restore-access` command in the bot's private chat:

```javascript
Libs.MembershipChecker.guard({restore: true});
```

Add `/restore-access` to **Commands available without joining** and link it from your private menu as **Restore group access**.

This explicit action checks subscriptions again for the recorded group and user before attempting restoration. Its result is sent privately. Ordinary private subscription checks never change group permissions. If there is no recorded restriction, `onError` receives `options.error === "no_restriction"`; `"cooldown"` means the user should wait briefly.

For a complete working example with group status messages and recovery, see [BBChannelPromotionBot](https://t.me/BBChannelPromotionBot).

## Read the cached decision

`Libs.MembershipChecker.isMember()` returns the stored all-chats decision. Pass one chat ID to inspect that target only. `getChats()` returns the configured comma-separated string; `getNotJoinedChats()` returns a comma-separated list still missing from the cached state.

`check()` schedules a fresh check and throttles calls within two seconds for a user. It returns no membership result immediately. `handle()` uses the panel delay, in minutes, for suitable incoming commands. Keep an explicit `/check` entry for the first visit: `handle()` starts periodic checks only after the first explicit check.

For example, call `Libs.MembershipChecker.handle();` in your `@` command. Automatic checks accept ordinary human messages and message-bound callback queries in private chats, groups and supergroups. Channel posts, membership and service updates, edited messages, Widgets, anonymous sender chats, bot users and inconsistent user/chat context are ignored.

An explicit `check()` also supports a known user in a background command. Without a source chat, its callback origin stays `null`; routing a job through a private chat does not make that chat the origin. Empty target configuration raises an error before sending membership requests.

## Callback meanings

* `onNeedJoining`: a target is not joined; this can run once per target.
* `onNeedAllJoining`: every target is confirmed absent in the completed check.
* `onJoining`: a target is now joined after being absent or unknown in the cache.
* `onAllJoining`: all targets are confirmed joined and at least one was previously absent or unknown. This works independently of whether `onJoining` is configured.
* `onStillJoined`: all targets remain joined after an explicit check.
* `onError`: a target check failed or returned an unknown membership state.

The library accepts `member`, `administrator` and `creator`. A `restricted` result counts as joined only when Telegram returns `is_member: true`, and as absent when it returns `is_member: false`. An API error or unknown state preserves the affected target's cached membership; a check containing such an error does not produce an all-joined or all-absent callback.

Checks process targets sequentially. Callbacks are asynchronous and can take an additional scheduler step. Old, duplicate, mismatched or expired replies are ignored. A check expires after five minutes without progress.

## Callback context

Existing callback fields remain available:

* `options.result`: the Telegram target-member result.
* `options.chat_id`: the checked subscription target.
* `options.bb_options`: custom data passed to `check(data)`.

For example, `Libs.MembershipChecker.check({source: "joining-button"});` makes that object available as `options.bb_options` in the callback.

The additional `options.membership_check` object describes the check:

| Fields                                     | Meaning                                                  |
| ------------------------------------------ | -------------------------------------------------------- |
| `id`, `time`, `expires_at`                 | Check identity and timing                                |
| `targets`, `callback`                      | Target list and callback name                            |
| `user_id`, `telegram_user_id`              | Bots.Business and Telegram user IDs                      |
| `chat_id`, `telegram_chat_id`, `chat_type` | The source chat; absent when no source chat was supplied |
| `all_checked`, `not_joined_chats`          | Progress and targets still missing                       |
| `origin_member`, `origin_error`            | Optional source-group inspection, described below        |

Use the source chat explicitly when your callback sends a notification or changes group permissions. `options.chat_id` identifies the subscription target, which can be a channel; it is not the destination for a group notice. With Force Join disabled, the library does not change group permissions. With group Force Join enabled, it handles those changes and supplies message options; your callbacks provide the text. Debug messages, if enabled, use a valid source chat.

## Optional source-group inspection

`includeChatMember` is a panel setting, disabled by default. Enable it only when your callbacks need the user's current membership or permissions in the source group.

For a group or supergroup check, the library then calls Telegram's `getChatMember` for that source group immediately before a configured membership callback. It provides `options.membership_check.origin_member`, or `origin_error` if the lookup fails. Your bot's callback does not need its own `Api.getChatMember` call.

This does not change `options.result`, add the source group to the subscription targets, or affect `isMember()`. There is no extra source lookup when both this setting and group Force Join are disabled, for private checks, for background checks without a group origin, or for `onError`. A source lookup failure preserves the target result and cache; check `origin_error` before changing permissions.

To add this field to an existing panel, run the updated `Libs.MembershipChecker.setup()` from an owner-only command. It preserves the panel's saved values and custom fields. Then enable **Include source group member in callbacks** only if your own callbacks need it. Group Force Join performs this lookup automatically.

The bot needs administrator access in the checked targets for reliable membership checks, and the appropriate permissions in any group your callbacks moderate. Inspecting membership and changing permissions are separate Telegram operations; another administrator can change permissions between them.

## Force Join callback details

When Force Join is enabled for this context, `options.membership_check` also includes:

| Field            | Meaning                                                                                                       |
| ---------------- | ------------------------------------------------------------------------------------------------------------- |
| `notice`         | Options for `Api.sendMessage`, including the correct recipient and internal button/delivery handling.         |
| `access_status`  | `restricted`, `restored`, `unchanged`, `missing`, `moderator`, `lookup_failed`, `change_failed` or `pending`. |
| `access_changed` | True only after a confirmed permission change in this check.                                                  |
| `recovery`       | Whether this is an explicit private recovery request.                                                         |

Report posting access as restored only for `access_status === "restored"`. For lookup/change failures or a pending operation, ask the user to retry or contact a moderator. The demo includes these messages.

Normal private join prompts are removed after 15 minutes and confirmations after 3 minutes. Recovery and error messages do not replace the current Joined prompt. Telegram controls ephemeral-message lifetime; the library does not delete old ephemeral IDs.

Inspecting and changing permissions are separate operations. Simultaneous workers, a lost Telegram reply or an administrator changing permissions between requests can still require manual intervention.

## Compatibility

The original public methods remain supported: `setup`, `handle`, `check`, `isMember`, `getChats` and `getNotJoinedChats`. The only new public method is `guard()`, including the explicit `guard({restore: true})` recovery action. The helper methods stay inside the library.

Bots linked to the official Store library receive its code update without reinstalling it. Existing checking behavior, settings and cached data remain supported. Force Join is optional: to use it, add `guard()` to `@`, update your result commands as shown above and enable the relevant switch. Running the updated owner-only `setup()` adds missing settings without resetting existing values.

Do not enable library group moderation alongside old bot code that also changes group permissions. Upgrade that bot to the simpler callback flow at the same time. The demo upgrade preserves its saved restrictions and supports existing Joined buttons and pending permission confirmations.

Callbacks remain asynchronous and can take an additional scheduler step. Old replies without valid check context are ignored; a fresh explicit check starts the flow again.

For a sensitive action, perform a fresh verified check in that action's flow instead of relying on old membership. Increasing the checking delay reduces repeated work but makes cached state older. For ordinary repeated button presses, see [Cooldowns](https://help.bots.business/libraries-and-examples/cooldown.md).
