Please Subscribe To My YouTube Channel Subscribe Now!

Add ban & unban feature in any repository

Please wait 0 seconds...
Scroll Down and click on Go to Link for destination
Congrats! Link is Generated

Ban & Unban feature

Ban helps you to ban a user from using your telegram bot. Unban helps you to unban the banned user so they can use the bot again.

Follow the below steps to add ban & unban feature in any Repo.

1. Add this code in your database file in '__init__' def.

self.banned_users = db["banned_users"]

2. Add this code in your database file.

    async def ban_user(self, user_id: int, reason: str = None) -> bool:
        try:
            ban = {"user_id": user_id, "reason": reason}
            await self.banned_users.insert_one(ban)
            return True
        except Exception as e:
            print("Error in banUser:", e)
            return False

    async def unban_user(self, user_id: int) -> bool:
        try:
            result = await self.banned_users.delete_one({"user_id": user_id})
            return result.deleted_count > 0
        except Exception as e:
            print("Error in unbanUser:", e)
            return False

    async def is_user_banned(self, user_id: int) -> bool:
        try:
            user = await self.banned_users.find_one({"user_id": user_id})
            return user is not None
        except Exception as e:
            print("Error in isUserBanned:", e)
            return False

3. Add this commands in your admin file & don't forget to import necessary things.

@Client.on_message(filters.command("ban") & filters.private & filters.user(ADMIN))
async def ban(c: Client, m: Message):
    try:
        command_parts = m.text.split()
        if len(command_parts) < 2:
            await m.reply_text("Usage: /ban user_id {reason}")
            return
        user_id = int(command_parts[1])
        reason = " ".join(command_parts[2:]) if len(command_parts) > 2 else None
        try:
            user = await c.get_users(user_id)
        except Exception:
            await m.reply_text("Unable to find user.")
            return
        if await tb.ban_user(user_id, reason):
            ban_message = f"User {user.mention} has been banned."
            if reason:
                ban_message += f"\nReason: {reason}"
            await m.reply_text(ban_message)
            try:
                notify = f"You have been banned from using the bot."
                if reason:
                    notify += f"\nReason: {reason}"
                await c.send_message(user_id, notify)
            except Exception:
                await m.reply_text("User banned, but could not send message (maybe they blocked the bot).")
        else:
            await m.reply_text("Failed to ban user.")
    except ValueError:
        await m.reply_text("Please provide a valid user ID.")
    except Exception as e:
        await m.reply_text(f"An error occurred: {str(e)}")

@Client.on_message(filters.command("unban") & filters.private & filters.user(ADMIN))
async def unban(c: Client, m: Message):
    try:
        command_parts = m.text.split()
        if len(command_parts) < 2:
            await m.reply_text("Usage: /unban user_id")
            return
        user_id = int(command_parts[1])
        try:
            user = await c.get_users(user_id)
        except Exception:
            await m.reply_text("Unable to find user.")
            return
        if await tb.unban_user(user_id):
            await m.reply_text(f"User {user.mention} has been unbanned.")
            try:
                await c.send_message(user_id, "You have been unbanned. You can now use the bot again.")
            except Exception:
                await m.reply_text("User unbanned, but could not send message (maybe they blocked the bot).")
        else:
            await m.reply_text("Failed to unban user or user was not banned.")
    except ValueError:
        await m.reply_text("Please provide a valid user ID.")
    except Exception as e:
        await m.reply_text(f"An error occurred: {str(e)}")

@Client.on_message(filters.command('banlist') & filters.private & filters.user(ADMIN))
async def banlist(client, message):
    response = await message.reply("Fetching banned users...")
    try:
        banned_users = await tb.banned_users.find().to_list(length=None)
        if not banned_users:
            return await response.edit("No users are currently banned.")
        text = "🚫 Banned Users:\n\n"
        for user in banned_users:
            user_id = user.get("user_id")
            reason = user.get("reason", "No reason provided")
            text += f"• {user_id} — {reason}\n"
        await response.edit(text)
    except Exception as e:
        await response.edit(f"Error: {str(e)}")

4. Now add this code in your main function of bot.

    if await tb.is_user_banned(m.from_user.id):
        await m.reply("**🚫 You are banned from using this bot**",
                      reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton("Support", url="https://telegram.me/TechifyBots")]]))
        return

Note: Change functions names according to your repository.

Important

If you still face any issues, then click on the below button.

Copying the post and using it without permission is strictly prohibited.

Post a Comment

Cookie Consent
We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
Oops!
It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
AdBlock Detected!
We have detected that you are using adblocking plugin in your browser.
The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
Site is Blocked
Sorry! This site is not available in your country.