Telegram· 5 min read

Telegram group moderation bot: ban, restrict and join requests


A Telegram bot can moderate a group once it is an administrator with the matching rights. can_restrict_members covers banChatMember, unbanChatMember and restrictChatMember. can_delete_messages lets it remove other users’ messages, and can_invite_users lets it handle join requests. Membership changes reach the bot only if you list chat_member in allowed_updates. Method details below come from the Bot API reference at Bot API 10.3, August 24, 2026 (accessed 2026-11-04). Telegram publishes no request samples for these methods, so the code is assembled from the parameter tables.

Admin rights the bot needs

Promote the bot to administrator in the group settings and turn on the rights its jobs require. The descriptions come from ChatAdministratorRights (ChatAdministratorRights).

Right Reference description What it allows here
can_restrict_members “can restrict, ban or unban chat members, or access supergroup statistics” Ban, unban, mute
can_delete_messages “can delete messages of other users” deleteMessage on any message in a supergroup
can_invite_users “allowed to invite new users to the chat” Receiving and answering join requests

Admin status also changes what the bot sees. The FAQ says “bot admins and bots with privacy mode disabled will receive all messages except messages sent by other bots” (Bots FAQ, accessed 2026-11-04). A moderation bot needs that, because it has to read messages that weren’t addressed to it. Telegram privacy mode explains what a non-admin bot receives instead.

Ban and unban without surprises

banChatMember bans a user “in a group, a supergroup or a channel”. In supergroups and channels, the user can’t come back through invite links “unless unbanned first” (banChatMember). It takes chat_id, user_id, an optional until_date in Unix time, and revoke_messages. That last flag deletes all of the user’s messages from the chat, and the reference says it is “always True for supergroups and channels”. A ban in a supergroup always wipes the user’s history there.

A ban whose until_date is more than 366 days or less than 30 seconds from now counts as permanent. Compute the timestamp from the current time, and clamp anything short to at least a minute. The reference applies until_date to supergroups and channels only.

unbanChatMember can remove a user who was never banned. By default it “guarantees that after the call the user is not a member of the chat”. If the user is still a member, “they will also be removed” (unbanChatMember). Call it on someone who was never banned and you kick them. Pass only_if_banned: true to make the call do nothing unless the user is banned. An unbanned user doesn’t return automatically. They can join again through a link.

Mute with restrictChatMember and ChatPermissions

restrictChatMember works in supergroups only. It takes a permissions object of type ChatPermissions, an optional until_date, and use_independent_chat_permissions (restrictChatMember). Leave that flag false and the media permissions follow can_send_other_messages and can_add_web_page_previews. Set it true and each field counts on its own, which is easier to reason about.

Field group Covers
can_send_messages Text messages, contacts and similar
can_send_audios, _documents, _photos, _videos, _video_notes, _voice_notes One media type each
can_send_polls Polls and checklists
can_send_other_messages Animations, games, stickers and inline bots
can_add_web_page_previews Link previews
can_change_info, can_invite_users, can_pin_messages, can_manage_topics Chat settings, invites, pins, forum topics

Every field is optional. can_react_to_messages, added in Bot API 10.0, defaults to the value of can_send_messages when you omit it. can_change_info and can_pin_messages are ignored in public supergroups.

The same 366-day and 30-second rule applies to until_date. A ten-second mute becomes a permanent one. To lift a restriction early, the reference says to “pass True for all permissions”. A ChatMemberRestricted object with until_date of 0 means the user is restricted forever.

Track joins, leaves and bans with chat_member

The chat_member update fires when a member’s status changes. The bot “must be an administrator in the chat and must explicitly specify chat_member in the list of allowed_updates” (Update). The default, an empty list, leaves it out, and the setting persists between calls, as the getUpdates walkthrough explains. my_chat_member reports changes to the bot’s own status and needs no opt-in.

Each update is a ChatMemberUpdated with chat, from (who made the change), date, old_chat_member and new_chat_member. Compare the two status values:

Status string Member type
creator ChatMemberOwner
administrator ChatMemberAdministrator
member ChatMemberMember
restricted ChatMemberRestricted
left ChatMemberLeft
kicked ChatMemberBanned

A banned user shows as kicked. Code that waits for "banned" never matches. The update also carries invite_link for joins through a link and via_join_request for users who joined after a direct request.

Approve or decline join requests

Create an invite link with creates_join_request set to true, and users who open it need approval from an administrator. Each request reaches the bot as a chat_join_request update, but only if the bot holds can_invite_users (Update). The request carries chat, from, user_chat_id, date, and optionally bio and invite_link. The reference lets the bot use user_chat_id to message the user for 5 minutes while the request is pending, provided no other administrator has contacted them.

Answer with approveChatJoinRequest or declineChatJoinRequest. Both take chat_id and user_id, and both require can_invite_users. Bot API 10.1 (June 11, 2026) added join request queries (answerChatJoinRequestQuery, sendChatJoinRequestWebApp) for bots “assigned to process join requests”, but the reference doesn’t explain assignment.

Delete messages within 48 hours

deleteMessage removes a message only “if it was sent less than 48 hours ago” (deleteMessage). Service messages about creating a supergroup, channel or forum topic can’t be deleted at all. An admin bot in a group can delete any message there, and in a supergroup it needs can_delete_messages. deleteMessages takes 1 to 100 message ids at once and skips any it can’t find. Telegram documents no rate limits specific to these moderation calls.

A moderation bot with the standard library

This bot runs on Python 3.9 or later with long polling. Moderators reply to a message with /ban, /mute 30 (minutes) or /unmute, or send /unban USER_ID. The bot trusts only the user ids in MODERATOR_IDS, so a regular member can’t trigger a ban. /mute also deletes the replied-to message if it is under 48 hours old, which needs can_delete_messages. Register the commands with setMyCommands to show them in the menu.

import json
import os
import time
import urllib.error
import urllib.request

TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
API = f"https://api.telegram.org/bot{TOKEN}/"
MODERATORS = {int(x) for x in os.environ.get("MODERATOR_IDS", "").split(",") if x.strip()}
BLOCKED = set()  # user ids whose join requests you always decline

SEND_FIELDS = [
    "can_send_messages", "can_send_audios", "can_send_documents", "can_send_photos",
    "can_send_videos", "can_send_video_notes", "can_send_voice_notes", "can_send_polls",
    "can_send_other_messages", "can_add_web_page_previews",
]
MUTED = {field: False for field in SEND_FIELDS}
UNMUTED = dict({field: True for field in SEND_FIELDS},
               can_change_info=True, can_invite_users=True,
               can_pin_messages=True, can_manage_topics=True)
MIN_SECONDS = 60            # under 30 seconds counts as forever
MAX_SECONDS = 365 * 86400   # over 366 days counts as forever


class TelegramError(Exception):
    pass


def call(method, params=None, timeout=10):
    request = urllib.request.Request(
        API + method,
        data=json.dumps(params or {}).encode("utf-8"),
        headers={"Content-Type": "application/json"},
    )
    try:
        with urllib.request.urlopen(request, timeout=timeout) as response:
            body = json.loads(response.read())
    except urllib.error.HTTPError as err:
        try:
            body = json.loads(err.read())
        except ValueError:
            raise TelegramError(f"{method}: HTTP {err.code}") from err
    if not body.get("ok"):
        raise TelegramError(f"{method}: {body.get('description')}")
    return body["result"]


def restrict(chat_id, user_id, permissions, minutes=None):
    params = {
        "chat_id": chat_id,
        "user_id": user_id,
        "permissions": permissions,
        "use_independent_chat_permissions": True,
    }
    if minutes is not None:
        seconds = min(max(minutes * 60, MIN_SECONDS), MAX_SECONDS)
        params["until_date"] = int(time.time()) + seconds
    call("restrictChatMember", params)


def delete_if_recent(chat_id, message):
    if time.time() - message["date"] < 48 * 3600:
        call("deleteMessage", {"chat_id": chat_id, "message_id": message["message_id"]})


def handle_command(message):
    sender = message.get("from", {}).get("id")
    text = message.get("text", "")
    if sender not in MODERATORS or not text.startswith("/"):
        return
    command, _, arg = text.partition(" ")
    command = command.split("@")[0]  # accept /ban@YourBot
    chat_id = message["chat"]["id"]

    if command == "/unban" and arg.strip().isdigit():
        call("unbanChatMember", {"chat_id": chat_id, "user_id": int(arg), "only_if_banned": True})
        return

    target = message.get("reply_to_message")
    if not target or "from" not in target:
        return
    user_id = target["from"]["id"]
    if command == "/ban":
        call("banChatMember", {"chat_id": chat_id, "user_id": user_id, "revoke_messages": True})
    elif command == "/mute":
        restrict(chat_id, user_id, MUTED, int(arg) if arg.strip().isdigit() else 60)
        delete_if_recent(chat_id, target)
    elif command == "/unmute":
        restrict(chat_id, user_id, UNMUTED)


def handle_member(update):
    old = update["old_chat_member"]["status"]
    new = update["new_chat_member"]["status"]
    user = update["new_chat_member"]["user"]
    print(f"chat {update['chat']['id']}: user {user['id']} {old} -> {new}")


def handle_join_request(request):
    method = "declineChatJoinRequest" if request["from"]["id"] in BLOCKED else "approveChatJoinRequest"
    call(method, {"chat_id": request["chat"]["id"], "user_id": request["from"]["id"]})


def main():
    offset = None
    allowed = ["message", "chat_member", "chat_join_request"]
    while True:
        params = {"timeout": 30, "allowed_updates": allowed}
        if offset is not None:
            params["offset"] = offset
        try:
            updates = call("getUpdates", params, timeout=40)
        except (TelegramError, OSError) as err:
            print("getUpdates failed:", err)
            time.sleep(5)
            continue
        for update in updates:
            offset = update["update_id"] + 1
            try:
                if "message" in update:
                    handle_command(update["message"])
                elif "chat_member" in update:
                    handle_member(update["chat_member"])
                elif "chat_join_request" in update:
                    handle_join_request(update["chat_join_request"])
            except (TelegramError, OSError) as err:
                print("update", update["update_id"], "failed:", err)


if __name__ == "__main__":
    main()

Run it with TELEGRAM_BOT_TOKEN=YOUR_TOKEN MODERATOR_IDS=YOUR_USER_ID python3 bot.py. If you later move the bot to a webhook, pass the same three types in the allowed_updates of setWebhook so chat_member keeps arriving.

/unmute restores every permission, following the reference’s rule for lifting restrictions. If your group’s defaults are stricter than that, store each user’s earlier permissions and restore those instead. /mute without a number lasts 60 minutes, and the clamps keep a typo such as /mute 0 from muting someone forever.

Z-API Omni team