Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Telegram Bot for Forum Topic Management Gets Banned #4774

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
vv-m opened this issue May 1, 2025 · 1 comment
Closed

Telegram Bot for Forum Topic Management Gets Banned #4774

vv-m opened this issue May 1, 2025 · 1 comment
Labels

Comments

@vv-m
Copy link

vv-m commented May 1, 2025

Issue I am facing

Telegram Bot for Topics Management Gets Banned Immediately

Description

I've created a Telegram bot that manages topics in groups. The bot has functionality to create and edit topics. However, when I launch this bot, Telegram immediately bans the bot and blocks my account from creating bots for a month. This has already happened with two separate accounts.

Bot Functionality

  • Creating forum topics in supergroups
  • Editing existing forum topics

I have tried to use it in one my test group with 2 test topics and 2 test users.

Questions

Why might Telegram be automatically banning this bot?

Additional Information

I'm only intending to use this bot in controlled environments for work purposes, not for mass deployments or marketing.
Any guidance would be greatly appreciated as I've been restricted from creating bots on multiple accounts due to this issue.

Code

bot.py

import asyncio

from telegram.ext import Application

from src.config import settings
from src.telegram_topic.services.topic_handler import TopicCommandHandler
from src.telegram_topic.services.topic_manager import TelegramTopicManager


async def main():
    # Create application
    application = Application.builder().token(settings.telegram.TELEGRAM_TOKEN).build()
    bot = application.bot

    # Create topic manager
    topic_manager = TelegramTopicManager(bot)
    topic_handler = TopicCommandHandler(topic_manager)

    topic_handler.register_handlers(application)

    # Start the bot with correct parameters
    await application.initialize()

    await application.start()

    await application.updater.start_polling(
        poll_interval=2.0,
        timeout=30,
        drop_pending_updates=True,
        allowed_updates=["message", "edited_message", "callback_query"],
    )


if __name__ == "__main__":
    asyncio.run(main())

topic_handler.py

from telegram import Update
from telegram.ext import ContextTypes
from abc import ABC, abstractmethod
from telegram.ext import CommandHandler

from src.telegram_topic.services.topic_manager import TopicManager


class CommandHandlerBase(ABC):
    """Base abstract class for command handlers"""

    @abstractmethod
    def register_handlers(self, application) -> None:
        """Register command handlers in the application"""
        pass


class TopicCommandHandler(CommandHandlerBase):
    """Command handler for topic management"""

    def __init__(self, topic_manager: TopicManager):
        self.topic_manager = topic_manager

    def register_handlers(self, application) -> None:
        application.add_handler(CommandHandler("create_topic", self.create_topic_command))
        application.add_handler(CommandHandler("edit_topic", self.edit_topic_command))

    async def create_topic_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
        """Handler for the create topic command"""
        if not context.args or len(context.args) < 1:
            await update.message.reply_text("Usage: /create_topic <topic_name> [icon_color (0-7)]")
            return

        name = context.args[0]
        icon_color = int(context.args[1]) if len(context.args) > 1 else None

        try:
            chat_id = update.effective_chat.id
            forum_topic = await self.topic_manager.create_topic(chat_id, name, icon_color)
            await update.message.reply_text(f"Topic '{name}' created successfully! Topic ID: {forum_topic.message_thread_id}")
        except Exception as e:
            await update.message.reply_text(f"Error creating topic: {e}")

    async def edit_topic_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
        """Handler for the edit topic command"""
        if not context.args or len(context.args) < 2:
            await update.message.reply_text("Usage: /edit_topic <topic_id> <new_name>")
            return

        try:
            message_thread_id = int(context.args[0])
            name = context.args[1]

            chat_id = update.effective_chat.id
            result = await self.topic_manager.edit_topic(chat_id, message_thread_id, name)

            if result:
                await update.message.reply_text("Topic edited successfully!")
            else:
                await update.message.reply_text("Failed to edit topic")
        except Exception as e:
            await update.message.reply_text(f"Error editing topic: {e}")

topic_manager.py

from telegram import ForumTopic, Bot
from telegram.constants import ChatType
from src.config import log
from abc import ABC, abstractmethod


class TopicManager(ABC):
    """Abstract class for topic management"""

    @abstractmethod
    async def create_topic(self, chat_id: int, name: str, icon_color: int = None) -> ForumTopic:
        """Create a new topic"""
        pass

    @abstractmethod
    async def edit_topic(
        self,
        chat_id: int,
        message_thread_id: int,
        name: str = None,
        icon_custom_emoji_id: str = None,
    ) -> bool:
        """Edit an existing topic"""
        pass


class TelegramTopicManager(TopicManager):
    """Implementation of the Topic Manager for Telegram"""

    def __init__(self, bot: Bot):
        """
        Initialize the topic manager

        Args:
            bot (Bot): Telegram bot instance
        """
        self.bot = bot

    async def create_topic(self, chat_id: int, name: str, icon_color: int = None) -> ForumTopic:
        """
        Create a new topic in a group

        Args:
            chat_id (int): Group ID
            name (str): Topic name
            icon_color (int, optional): Topic icon color (0-7)

        Returns:
            ForumTopic: Information about the created topic

        Raises:
            ValueError: If the group is not a supergroup
            Exception: If topic creation fails
        """
        log.debug(f"{chat_id=}")
        try:
            # Check that this is a supergroup (topics only work in supergroups)
            chat = await self.bot.get_chat(chat_id)

            if chat.type != ChatType.SUPERGROUP:
                raise ValueError("Topics are only available in supergroups")

            # Create the topic
            params = {"chat_id": chat_id, "name": name}

            if icon_color is not None:
                params["icon_color"] = icon_color

            forum_topic = await self.bot.create_forum_topic(**params)

            return forum_topic

        except Exception as e:
            log.error(f"Error creating topic: {e}")
            raise

    async def edit_topic(
        self,
        chat_id: int,
        message_thread_id: int,
        name: str = None,
        icon_custom_emoji_id: str = None,
    ) -> bool:
        """
        Edit an existing topic

        Args:
            chat_id (int): Group ID
            message_thread_id (int): Topic ID
            name (str, optional): New topic name
            icon_custom_emoji_id (str, optional): Emoji ID for topic icon

        Returns:
            bool: True if editing was successful

        Raises:
            Exception: If topic editing fails
        """
        try:
            params = {"chat_id": chat_id, "message_thread_id": message_thread_id}

            if name is not None:
                params["name"] = name

            if icon_custom_emoji_id is not None:
                params["icon_custom_emoji_id"] = icon_custom_emoji_id

            result = await self.bot.edit_forum_topic(**params)
            return result
        except Exception as e:
            log.error(f"Error editing topic: {e}")
            raise

Traceback to the issue

Related part of your code

Operating System

MacOS

Version of Python, python-telegram-bot & dependencies

3.12.2
@vv-m vv-m added the question label May 1, 2025
@vv-m
Copy link
Author

vv-m commented May 1, 2025

πŸ” Solution Found: Telegram Bot Ban Issue

I found the answer to my problem. The issue wasn't related to the bot's code or functionality at all. It was caused by the icon I used for the bot. πŸ€¦β€β™‚οΈ

🚫 The Actual Issue

When creating the bot on my third account, Telegram blocked it before I could even connect the bot to my code. I wanted to create a bot that would manage project tasks as topics, so I asked an AI to create an icon for such a bot. The AI generated an icon featuring a paper airplane (similar to the Telegram logo) with a checkmark (representing a completed task).

🧩 Conclusion

While this seemed logical and the icon looked great, it turns out Telegram has systems that check bot icons and apparently blocks any bots with images resembling their logo. ⚠️

πŸ’‘ Recommendation for Others

If you're creating a Telegram bot, avoid using any imagery in your bot's profile picture that resembles the Telegram logo (paper airplane). This includes stylized versions or combinations with other elements. πŸš€

Hope this helps someone else avoid the same issue! πŸ™Œ

Image

Image

@vv-m vv-m closed this as completed May 1, 2025
@github-actions github-actions bot locked and limited conversation to collaborators May 9, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

1 participant