Skip to content
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

Add basic telegram notification integration #96

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions PlexAniSync.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
import anilist
import plexmodule
import graphql
import telegram
from _version import __version__

# Logger settings
Expand Down Expand Up @@ -59,6 +60,8 @@ def read_settings(settings_file) -> configparser.ConfigParser:
settings = read_settings(SETTINGS_FILE)
anilist_settings = settings["ANILIST"]
plex_settings = settings["PLEX"]
telegram_settings = settings["TELEGRAM"]
Copy link
Collaborator

Choose a reason for hiding this comment

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

I think this would also be useful for the Tautulli mode.

telegram.setup(telegram_settings)

graphql.ANILIST_ACCESS_TOKEN = anilist_settings["access_token"].strip()

Expand All @@ -79,6 +82,7 @@ def read_settings(settings_file) -> configparser.ConfigParser:
## Startup section ##
def start():
logger.info(f"PlexAniSync - version: {__version__}")
telegram.starting_sync(__version__)

anilist.CUSTOM_MAPPINGS = read_custom_mappings()

Expand Down Expand Up @@ -123,6 +127,7 @@ def start():
else:
anilist.match_to_plex(anilist_series, plex_series_watched)

telegram.report_to_telegram()
logger.info("Plex to AniList sync finished")


Expand Down
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,15 @@ Depending on your OS make sure to place the show name between single or double q

https://github.com/RickDB/PlexAniSync/wiki/Tautulli-sync-script

### Telegram Integration

We can inform you via Telegram about start / errors / finish of the sync process. This is especially useful for automatic daily syncs. In case an error occurs or a new anime got added that needs a custom mapping you are always informed.

To enable this you first have to create a new Telegram Bot by talking to the neat helper [BotFather](https://t.me/BotFather). From him you get a "bot_token" which you have to save in the `settings.ini`. After that you also need a chat
where to send the messages to. For that add the bot to any chatroom and use a bot like [IDBot](https://t.me/myidbot) to get the chats id. Save this to `chat_id` in the `settings.ini`.

Last but not least you have to enable the integration by settings `eneabled` in the `[TELEGRAM]` section of `settings.ini` to `True`.
Copy link
Collaborator

Choose a reason for hiding this comment

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

Suggested change
Last but not least you have to enable the integration by settings `eneabled` in the `[TELEGRAM]` section of `settings.ini` to `True`.
Last but not least you have to enable the integration by settings `enabled` in the `[TELEGRAM]` section of `settings.ini` to `True`.


## Docker

Docker version is located here: [PlexAniSync](https://github.com/RickDB/PlexAniSync/pkgs/container/plexanisync)
Expand Down
10 changes: 9 additions & 1 deletion settings.ini.example
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,12 @@ access_token = SomeVeryLongAccessToken
plex_episode_count_priority = False
skip_list_update = False
username = SomeUsername
log_failed_matches = False
log_failed_matches = False

[TELEGRAM]
# Set enabled to True to get Telegram notifications upon finish
enabled = False
# Only send errors and no start / finish indicators
errors_only = False
bot_token = TOKEN
chat_id = CHAT_ID
84 changes: 84 additions & 0 deletions telegram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
# coding=utf-8
import logging
import time

from io import StringIO
from requests import get, HTTPError

logger = logging.getLogger("PlexAniSync")
# Gets overriden by settings.ini
settings = {
'enabled': False,
'errors_only': False,
'bot_token': '',
'chat_id': '',
}

# Keep track of errors for Telegram integration
error_tracker = StringIO()
handler = logging.StreamHandler(error_tracker)
handler.setLevel(logging.WARNING)
logger.addHandler(handler)


def setup(ini_settings):
global settings
if ini_settings.get('enabled', '').lower().strip() == 'true':
enabled = True
bot_token, chat_id = ini_settings.get('bot_token', '').strip(), ini_settings.get('chat_id').strip()

if not bot_token:
logger.error('[TELEGRAM] Bot token not set, disabling telegram integration')
enabled = False
if not chat_id:
logger.error('[TELEGRAM] Chat id not set, disabling telegram integration')
enabled = False

settings['enabled'] = enabled
settings['bot_token'] = bot_token
settings['chat_id'] = chat_id
settings['errors_only'] = ini_settings.get('errors_only', '').lower().strip() == 'true'


def send_message(text):
if not settings['enabled']:
return

log_text = text if len(text) < 30 else (text[:27] + '...')
try:
response = get(
f'https://api.telegram.org/bot{settings["bot_token"]}/sendMessage',
data={
'chat_id': settings['chat_id'],
'text': text,
'parse_mode': 'markdown'
})
response.raise_for_status()
logger.info(f'[TELEGRAM] message sent to Telegram | chat_id: {settings["chat_id"]} | text: "{log_text}"')
except HTTPError as e:
logger.error(f'[TELEGRAM] Could not send message | chat_id: {settings["chat_id"]} | text: "{log_text}" | error: {e}')


def starting_sync(version):
if not settings['enabled'] or settings['errors_only']:
return

send_message(f'PlexAniSync - version: `{version}`\nSync Started - `{time.asctime()}`')


def report_to_telegram():
if not settings['enabled']:
return

if error_tracker.getvalue():
error = ''
for line in error_tracker.getvalue().split('\n'):
if len(error) + len(line) + 3 > 4096:
send_message(error)
error = ''
error += f'`{line}`\n'
if error:
send_message(error)

if not settings['errors_only']:
send_message(f'Sync Complete - `{time.asctime()}`')