- Notifications
You must be signed in to change notification settings - Fork5.7k
Closed
Labels
Description
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
importasynciofromtelegram.extimportApplicationfromsrc.configimportsettingsfromsrc.telegram_topic.services.topic_handlerimportTopicCommandHandlerfromsrc.telegram_topic.services.topic_managerimportTelegramTopicManagerasyncdefmain():# Create applicationapplication=Application.builder().token(settings.telegram.TELEGRAM_TOKEN).build()bot=application.bot# Create topic managertopic_manager=TelegramTopicManager(bot)topic_handler=TopicCommandHandler(topic_manager)topic_handler.register_handlers(application)# Start the bot with correct parametersawaitapplication.initialize()awaitapplication.start()awaitapplication.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
fromtelegramimportUpdatefromtelegram.extimportContextTypesfromabcimportABC,abstractmethodfromtelegram.extimportCommandHandlerfromsrc.telegram_topic.services.topic_managerimportTopicManagerclassCommandHandlerBase(ABC):"""Base abstract class for command handlers"""@abstractmethoddefregister_handlers(self,application)->None:"""Register command handlers in the application"""passclassTopicCommandHandler(CommandHandlerBase):"""Command handler for topic management"""def__init__(self,topic_manager:TopicManager):self.topic_manager=topic_managerdefregister_handlers(self,application)->None:application.add_handler(CommandHandler("create_topic",self.create_topic_command))application.add_handler(CommandHandler("edit_topic",self.edit_topic_command))asyncdefcreate_topic_command(self,update:Update,context:ContextTypes.DEFAULT_TYPE)->None:"""Handler for the create topic command"""ifnotcontext.argsorlen(context.args)<1:awaitupdate.message.reply_text("Usage: /create_topic <topic_name> [icon_color (0-7)]")returnname=context.args[0]icon_color=int(context.args[1])iflen(context.args)>1elseNonetry:chat_id=update.effective_chat.idforum_topic=awaitself.topic_manager.create_topic(chat_id,name,icon_color)awaitupdate.message.reply_text(f"Topic '{name}' created successfully! Topic ID:{forum_topic.message_thread_id}")exceptExceptionase:awaitupdate.message.reply_text(f"Error creating topic:{e}")asyncdefedit_topic_command(self,update:Update,context:ContextTypes.DEFAULT_TYPE)->None:"""Handler for the edit topic command"""ifnotcontext.argsorlen(context.args)<2:awaitupdate.message.reply_text("Usage: /edit_topic <topic_id> <new_name>")returntry:message_thread_id=int(context.args[0])name=context.args[1]chat_id=update.effective_chat.idresult=awaitself.topic_manager.edit_topic(chat_id,message_thread_id,name)ifresult:awaitupdate.message.reply_text("Topic edited successfully!")else:awaitupdate.message.reply_text("Failed to edit topic")exceptExceptionase:awaitupdate.message.reply_text(f"Error editing topic:{e}")
topic_manager.py
fromtelegramimportForumTopic,Botfromtelegram.constantsimportChatTypefromsrc.configimportlogfromabcimportABC,abstractmethodclassTopicManager(ABC):"""Abstract class for topic management"""@abstractmethodasyncdefcreate_topic(self,chat_id:int,name:str,icon_color:int=None)->ForumTopic:"""Create a new topic"""pass@abstractmethodasyncdefedit_topic(self,chat_id:int,message_thread_id:int,name:str=None,icon_custom_emoji_id:str=None, )->bool:"""Edit an existing topic"""passclassTelegramTopicManager(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=botasyncdefcreate_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=awaitself.bot.get_chat(chat_id)ifchat.type!=ChatType.SUPERGROUP:raiseValueError("Topics are only available in supergroups")# Create the topicparams= {"chat_id":chat_id,"name":name}ificon_colorisnotNone:params["icon_color"]=icon_colorforum_topic=awaitself.bot.create_forum_topic(**params)returnforum_topicexceptExceptionase:log.error(f"Error creating topic:{e}")raiseasyncdefedit_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}ifnameisnotNone:params["name"]=nameificon_custom_emoji_idisnotNone:params["icon_custom_emoji_id"]=icon_custom_emoji_idresult=awaitself.bot.edit_forum_topic(**params)returnresultexceptExceptionase: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