pibooth-telegram-upload/pibooth_telegram_upload.py

85 lines
2.4 KiB
Python
Raw Permalink Normal View History

2022-06-06 21:22:17 +02:00
# -*- coding: utf-8 -*-
"""pibooth plugin for uploading pictures to Telegram"""
import os
import telegram
try:
from telegram.error import TelegramError
except ImportError:
InstalledAppFlow = None
pass
import pibooth
from pibooth.utils import LOGGER
2024-09-03 19:31:12 +02:00
__version__ = "1.0.3"
2022-06-06 21:22:17 +02:00
SECTION = "Telegram"
@pibooth.hookimpl
def pibooth_configure(cfg):
"""Declare the new configuration options"""
cfg.add_option(SECTION, "telegram_token", "", "Telegram Token")
cfg.add_option(SECTION, "telegram_chat_id", "", "Telegram chat ID")
2024-09-03 19:28:08 +02:00
cfg.add_option(SECTION, "telegram_thread_id", "", "Telegram thread ID")
2022-06-06 21:22:17 +02:00
cfg.add_option(
SECTION,
"telegram_message",
"",
2024-09-03 19:28:08 +02:00
"Message sent with every posted photo",
2022-06-06 21:22:17 +02:00
)
@pibooth.hookimpl
def pibooth_startup(app, cfg):
"""Verify Telegram credentials"""
telegram_token = cfg.get(SECTION, "telegram_token")
telegram_chat_id = cfg.get(SECTION, "telegram_chat_id")
2024-09-03 19:28:08 +02:00
telegram_thread_id = cfg.get(SECTION, "telegram_thread_id")
2022-06-06 21:22:17 +02:00
if not telegram_token:
LOGGER.error(
"Telegram Token not defined in ["
+ SECTION
+ "][telegram_token], uploading deactivated"
)
elif not telegram_chat_id:
LOGGER.error(
"Telegram Chat ID not defined in ["
+ SECTION
+ "][telegram_chat_id], uploading deactivated"
)
2024-09-03 19:29:43 +02:00
elif not telegram_thread_id:
2024-09-03 19:28:08 +02:00
LOGGER.error(
"Telegram Thread ID not defined in ["
+ SECTION
+ "][telegram_thread_id], uploading deactivated"
)
2022-06-06 21:22:17 +02:00
else:
LOGGER.info("Initializing Telegram client")
app.telegram_client = telegram.Bot(token=telegram_token)
@pibooth.hookimpl
def state_processing_exit(app, cfg):
"""Upload picture to Telegram chat"""
if hasattr(app, "telegram_client"):
chat_id = cfg.get(SECTION, "telegram_chat_id").strip('"')
2024-09-03 19:28:08 +02:00
thread_id = cfg.get(SECTION, "telegram_thread_id").strip('"')
2022-06-06 21:22:17 +02:00
message = cfg.get(SECTION, "telegram_message")
try:
response = app.telegram_client.send_photo(
chat_id=chat_id,
2024-09-03 19:28:08 +02:00
message_thread_id=thread_id,
2022-06-06 21:22:17 +02:00
caption=message,
2022-06-13 20:04:02 +02:00
photo=open(app.previous_picture_file, 'rb'),
2022-06-06 21:22:17 +02:00
parse_mode=telegram.ParseMode.MARKDOWN,
)
2022-06-13 20:36:19 +02:00
LOGGER.info("File uploaded to Telegram chat: " + str(response))
2022-06-06 21:22:17 +02:00
except TelegramError as e:
LOGGER.error(e)