From c61935fc4157c84bd90bcd5cc3b0d5f9e02ea873 Mon Sep 17 00:00:00 2001 From: hanwg Date: Tue, 1 Jul 2025 21:42:32 +0800 Subject: [PATCH] Include chat ID in Telegram bot subentry title (#147643) --- homeassistant/components/telegram_bot/config_flow.py | 11 ++++------- tests/components/telegram_bot/test_config_flow.py | 2 +- 2 files changed, 5 insertions(+), 8 deletions(-) diff --git a/homeassistant/components/telegram_bot/config_flow.py b/homeassistant/components/telegram_bot/config_flow.py index b6480b84f64..41f26ccd48d 100644 --- a/homeassistant/components/telegram_bot/config_flow.py +++ b/homeassistant/components/telegram_bot/config_flow.py @@ -237,12 +237,13 @@ class TelgramBotConfigFlow(ConfigFlow, domain=DOMAIN): subentries: list[ConfigSubentryData] = [] allowed_chat_ids: list[int] = import_data[CONF_ALLOWED_CHAT_IDS] + assert self._bot is not None, "Bot should be initialized during import" for chat_id in allowed_chat_ids: chat_name: str = await _async_get_chat_name(self._bot, chat_id) subentry: ConfigSubentryData = ConfigSubentryData( data={CONF_CHAT_ID: chat_id}, subentry_type=CONF_ALLOWED_CHAT_IDS, - title=chat_name, + title=f"{chat_name} ({chat_id})", unique_id=str(chat_id), ) subentries.append(subentry) @@ -380,7 +381,6 @@ class TelgramBotConfigFlow(ConfigFlow, domain=DOMAIN): """Shutdown the bot if it exists.""" if self._bot: await self._bot.shutdown() - self._bot = None async def _validate_bot( self, @@ -649,7 +649,7 @@ class AllowedChatIdsSubEntryFlowHandler(ConfigSubentryFlow): chat_name = await _async_get_chat_name(bot, chat_id) if chat_name: return self.async_create_entry( - title=chat_name, + title=f"{chat_name} ({chat_id})", data={CONF_CHAT_ID: chat_id}, unique_id=str(chat_id), ) @@ -663,10 +663,7 @@ class AllowedChatIdsSubEntryFlowHandler(ConfigSubentryFlow): ) -async def _async_get_chat_name(bot: Bot | None, chat_id: int) -> str: - if not bot: - return str(chat_id) - +async def _async_get_chat_name(bot: Bot, chat_id: int) -> str: try: chat_info: ChatFullInfo = await bot.get_chat(chat_id) return chat_info.effective_name or str(chat_id) diff --git a/tests/components/telegram_bot/test_config_flow.py b/tests/components/telegram_bot/test_config_flow.py index 659effdda7b..2586761b584 100644 --- a/tests/components/telegram_bot/test_config_flow.py +++ b/tests/components/telegram_bot/test_config_flow.py @@ -383,7 +383,7 @@ async def test_subentry_flow( assert result["type"] is FlowResultType.CREATE_ENTRY assert subentry.subentry_type == SUBENTRY_TYPE_ALLOWED_CHAT_IDS - assert subentry.title == "mock title" + assert subentry.title == "mock title (987654321)" assert subentry.unique_id == "987654321" assert subentry.data == {CONF_CHAT_ID: 987654321}