Skip to content

Add support for Telegram message attachments#153216

Merged
zweckj merged 18 commits intohome-assistant:devfrom
aviadlevy:add_file_id
Oct 16, 2025
Merged

Add support for Telegram message attachments#153216
zweckj merged 18 commits intohome-assistant:devfrom
aviadlevy:add_file_id

Conversation

@aviadlevy
Copy link
Copy Markdown
Contributor

@aviadlevy aviadlevy commented Sep 29, 2025

Breaking change

Nope

Proposed change

This PR adds support for Telegram message attachments by firing a new event with the attachment’s file_id, enabling automations to handle files sent to the bot.

Type of change

  • Dependency upgrade
  • Bugfix (non-breaking change which fixes an issue)
  • New integration (thank you!)
  • New feature (which adds functionality to an existing integration)
  • Deprecation (breaking change to happen in the future)
  • Breaking change (fix/feature causing existing functionality to break)
  • Code quality improvements to existing code or addition of tests

Additional information

Checklist

  • I understand the code I am submitting and can explain how it works.
  • The code change is tested and works locally.
  • Local tests pass. Your PR cannot be merged unless tests pass
  • There is no commented out code in this PR.
  • I have followed the development checklist
  • I have followed the perfect PR recommendations
  • The code has been formatted using Ruff (ruff format homeassistant tests)
  • Tests have been added to verify that the new code works.
  • Any generated code has been carefully reviewed for correctness and compliance with project standards.

If user exposed functionality or configuration variables are added/changed:

If the code communicates with devices, web services, or third-party tools:

  • The manifest file has all fields filled out correctly.
    Updated and included derived files by running: python3 -m script.hassfest.
  • New or updated dependencies have been added to requirements_all.txt.
    Updated by running python3 -m script.gen_requirements_all.
  • For the updated dependencies - a link to the changelog, or at minimum a diff between library versions is added to the PR description.

To help with the load of incoming pull requests:

@home-assistant
Copy link
Copy Markdown
Contributor

Hey there @hanwg, mind taking a look at this pull request as it has been labeled with an integration (telegram_bot) you are listed as a code owner for? Thanks!

Code owner commands

Code owners of telegram_bot can trigger bot actions by commenting:

  • @home-assistant close Closes the pull request.
  • @home-assistant rename Awesome new title Renames the pull request.
  • @home-assistant reopen Reopen the pull request.
  • @home-assistant unassign telegram_bot Removes the current integration label and assignees on the pull request, add the integration domain after the command.
  • @home-assistant add-label needs-more-information Add a label (needs-more-information, problem in dependency, problem in custom component) to the pull request.
  • @home-assistant remove-label needs-more-information Remove a label (needs-more-information, problem in dependency, problem in custom component) on the pull request.

@aviadlevy
Copy link
Copy Markdown
Contributor Author

@hanwg I started a discussion so feel free to discuss there or here. would love your feedback

https://github.com/orgs/home-assistant/discussions/1169

@hanwg
Copy link
Copy Markdown
Contributor

hanwg commented Sep 30, 2025

I'm just trying to visualize how the full flow looks like.

  1. Get the file_id from event.
  2. Invoke bot.get_file() to retrieve the download link. Perhaps you can also verify the limitations (20MB size, 1h expiry) mentioned here: https://core.telegram.org/bots/api#getfile
  3. What do we do with the link? Do we just download the file and write to config/www ?

@aviadlevy
Copy link
Copy Markdown
Contributor Author

Thanks for the quick feedback!

I suggest we split this into two parts:
First, keep firing an event with file_id (as in the draft). Automations can then use this data to trigger further actions, ensuring flexibility for different use cases.

Second, add a service called download_file or get_file. This service would accept:

  • The file_id (required)
  • An optional destination_path, defaulting to /config/www
  • An optional filename, defaulting to the original Telegram file name
    I have a small concern about choosing the default download location - we should review how similar integrations handle this to make sure we're consistent.

For future improvements, it might help to also include file type info (photo, document, audio, etc.) in the event for smarter automations.

What do you think?

@hanwg
Copy link
Copy Markdown
Contributor

hanwg commented Sep 30, 2025

You can include the original filename and other metadata (e.g. file type info) in the event.
A sample event would be good for illustration and documentation.

I haven't come across any integrations that perform downloads other than Downloader.
I think /config/www is a reasonable default.
The new get_file action that you suggested seems fine.

@aviadlevy
Copy link
Copy Markdown
Contributor Author

You can include the original filename and other metadata (e.g. file type info) in the event. A sample event would be good for illustration and documentation.

I added the mime type and file name when relevant.
I will continue formalizing it with the documentation and relevant examples and mark this as ready for review when done.

Small question first - you think I should add the new service to this PR as well? IMO it belongs to a separate PR which I'm more than willing to implement, but I don't mind adding this here in case you think it's the same context

@hanwg
Copy link
Copy Markdown
Contributor

hanwg commented Sep 30, 2025

I think we can keep them separate.

@aviadlevy aviadlevy marked this pull request as ready for review September 30, 2025 14:44
@aviadlevy
Copy link
Copy Markdown
Contributor Author

@hanwg
Marking this as ready for review since your feedback could also benefit the documentation. I’ve started drafting the docs PR and plan to proceed with it anyway, but getting your input early would help me align it better.

Comment thread homeassistant/components/telegram_bot/bot.py Outdated
Comment thread homeassistant/components/telegram_bot/bot.py Outdated
Copy link
Copy Markdown
Member

@erwindouna erwindouna left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me, thanks @aviadlevy! :)

@aviadlevy
Copy link
Copy Markdown
Contributor Author

@hanwg any chance you can take a look. I'll continue with the second PR once this PR approach will be approved and merged
Thanks!

Comment thread homeassistant/components/telegram_bot/bot.py
Comment thread homeassistant/components/telegram_bot/bot.py
@hanwg
Copy link
Copy Markdown
Contributor

hanwg commented Oct 8, 2025

Overall PR looks fine but might need to document down the limitations:
20MB limit, 1h download link expiry
heavy compression and rescaling if image exceeds certain size (1k resolution?).

@aviadlevy
Copy link
Copy Markdown
Contributor Author

Overall PR looks fine but might need to document down the limitations:
20MB limit, 1h download link expiry
heavy compression and rescaling if image exceeds certain size (1k resolution?).

Can you provide reference to those limitations? And did you want to add it in the web documentation or as comments in the code?
Worth mentioning that some limitations are only relevant when actually downloading the files with the getFile API call (which will be in another PR)

Comment thread tests/components/telegram_bot/conftest.py Outdated
Comment thread homeassistant/components/telegram_bot/bot.py
@aviadlevy aviadlevy marked this pull request as ready for review October 8, 2025 15:53
Copy link
Copy Markdown
Contributor

@hanwg hanwg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The tests look identical.
Perhaps they can be parameterized using @pytest.mark.parametrize?

@aviadlevy
Copy link
Copy Markdown
Contributor Author

The tests look identical.
Perhaps they can be parameterized using @pytest.mark.parametrize?

I actually wondered myself what's better in terms of readability, so I'll try to make that happen

@aviadlevy aviadlevy marked this pull request as draft October 9, 2025 12:05
@aviadlevy aviadlevy marked this pull request as ready for review October 9, 2025 12:12
Comment thread tests/components/telegram_bot/test_telegram_bot.py
Comment thread tests/components/telegram_bot/test_telegram_bot.py Outdated
Comment thread tests/components/telegram_bot/test_telegram_bot.py Outdated
Comment thread tests/components/telegram_bot/test_telegram_bot.py Outdated
Comment thread tests/components/telegram_bot/test_telegram_bot.py Outdated
Comment thread tests/components/telegram_bot/test_telegram_bot.py Outdated
Comment thread tests/components/telegram_bot/test_telegram_bot.py Outdated
@aviadlevy aviadlevy requested a review from hanwg October 15, 2025 07:13
Copy link
Copy Markdown
Contributor

@hanwg hanwg left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good to me.
I tested this and it works fine.

@aviadlevy aviadlevy requested a review from erwindouna October 16, 2025 06:41
@frenck frenck requested review from Copilot and removed request for erwindouna October 16, 2025 07:45
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR adds support for handling Telegram message attachments by introducing a new telegram_attachment event that fires when files are sent to the bot. The implementation extracts file metadata (file_id, mime_type, size, etc.) from attachment messages and makes it available for automation triggers.

Key Changes:

  • Adds new telegram_attachment event type with file metadata extraction
  • Implements support for photos and documents with appropriate metadata handling
  • Adds comprehensive test coverage for attachment handling

Reviewed Changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 2 comments.

Show a summary per file
File Description
homeassistant/components/telegram_bot/const.py Adds event constant and file attribute constants for attachment metadata
homeassistant/components/telegram_bot/bot.py Implements attachment detection logic and file metadata extraction
tests/components/telegram_bot/test_telegram_bot.py Adds parameterized test for photo and document attachment events
tests/components/telegram_bot/fixtures/update_message_attachment_photo.json Adds test fixture with sample photo attachment data
tests/components/telegram_bot/fixtures/update_message_attachment_document.json Adds test fixture with sample document attachment data

photos = cast(Sequence[PhotoSize], message.effective_attachment)
return {
ATTR_FILE_ID: photos[-1].file_id,
ATTR_FILE_MIME_TYPE: "image/jpeg", # telegram always uses jpeg for photos
Copy link

Copilot AI Oct 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment states 'telegram always uses jpeg for photos' but this is incorrect. Telegram can deliver photos in WebP format or JPEG depending on the client and API version. Consider using a more accurate comment like 'Telegram typically delivers photos as JPEG' or remove the hardcoded mime type and use getattr with a fallback.

Suggested change
ATTR_FILE_MIME_TYPE: "image/jpeg", # telegram always uses jpeg for photos
ATTR_FILE_MIME_TYPE: getattr(photos[-1], "mime_type", "image/jpeg"), # Telegram typically delivers photos as JPEG, but other formats are possible

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor Author

@aviadlevy aviadlevy Oct 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PhotoSize does not hold mime_type fields. other formats other than JPEG is only available as Document.
https://stackoverflow.com/a/64927595

Comment on lines +213 to +222
return {
k: getattr(message.effective_attachment, v)
for k, v in (
(ATTR_FILE_ID, "file_id"),
(ATTR_FILE_NAME, "file_name"),
(ATTR_FILE_MIME_TYPE, "mime_type"),
(ATTR_FILE_SIZE, "file_size"),
)
if hasattr(message.effective_attachment, v)
}
Copy link

Copilot AI Oct 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The dictionary comprehension silently skips attributes that don't exist using hasattr. This could mask issues if expected attributes are missing. Consider logging when attributes are missing or documenting which attachment types have which attributes to make the behavior more transparent.

Suggested change
return {
k: getattr(message.effective_attachment, v)
for k, v in (
(ATTR_FILE_ID, "file_id"),
(ATTR_FILE_NAME, "file_name"),
(ATTR_FILE_MIME_TYPE, "mime_type"),
(ATTR_FILE_SIZE, "file_size"),
)
if hasattr(message.effective_attachment, v)
}
result = {}
for k, v in (
(ATTR_FILE_ID, "file_id"),
(ATTR_FILE_NAME, "file_name"),
(ATTR_FILE_MIME_TYPE, "mime_type"),
(ATTR_FILE_SIZE, "file_size"),
):
if hasattr(message.effective_attachment, v):
result[k] = getattr(message.effective_attachment, v)
else:
_LOGGER.debug(
"Attachment of type %s is missing expected attribute '%s'",
type(message.effective_attachment).__name__,
v,
)
return result

Copilot uses AI. Check for mistakes.
Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I really don't think it's necessary to have that log, but willing to change that if anyone think otherwise

@aviadlevy

This comment was marked as off-topic.

@zweckj zweckj merged commit 6038f15 into home-assistant:dev Oct 16, 2025
30 checks passed
@zweckj
Copy link
Copy Markdown
Member

zweckj commented Oct 16, 2025

Please do not ping reviewers though, thanks!

@aviadlevy aviadlevy deleted the add_file_id branch October 16, 2025 13:00
@github-actions github-actions Bot locked and limited conversation to collaborators Oct 17, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants