diff --git a/README.md b/README.md index c358e0a..f3a4d82 100644 --- a/README.md +++ b/README.md @@ -12,6 +12,7 @@ Transmission downloading progress on Telegram * Self-adjustment of `Telegram` bot limits based on number of torrents tracked * Easy configuration +* Uploading new torrent - just send torrent file to chat ## Installation diff --git a/backends/transmission.py b/backends/transmission.py index 4d0dcb0..33929ac 100644 --- a/backends/transmission.py +++ b/backends/transmission.py @@ -13,6 +13,9 @@ def __init__(self, host, port): """ self.transmission = transmissionrpc.Client(host, port) + def add_torrent(self, torrent, timeout=None, **kwargs): + return Torrent(self.transmission.add_torrent(torrent, timeout, **kwargs)) + def get_torrents(self): """Yields Torrents objects.""" yield from map(lambda torrent: Torrent(torrent), diff --git a/handlers/__init__.py b/handlers/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/handlers/message_handlers.py b/handlers/message_handlers.py new file mode 100644 index 0000000..a4dd186 --- /dev/null +++ b/handlers/message_handlers.py @@ -0,0 +1,24 @@ +import base64 +import logging + +from telegram.ext import Filters, MessageHandler + + +class UploadNewTorrent(MessageHandler): + + filters = Filters.document.mime_type('application/x-bittorrent') + + def __init__(self, client): + self.client = client + super().__init__(self.filters, self.callback) + + def callback(self, update, context): + torrent = update.message.document.get_file().download_as_bytearray() + filedump = base64.b64encode(torrent).decode('utf-8') + self.client.add_torrent(filedump) + logging.info('Added new torrent file %s', + update.message.document.file_name) + context.bot.send_message( + chat_id=update.effective_chat.id, + text='Added *{}*'.format(update.message.document.file_name), + parse_mode='markdown') diff --git a/tdpt.py b/tdpt.py index e8576e7..08193de 100644 --- a/tdpt.py +++ b/tdpt.py @@ -7,8 +7,10 @@ import telegram +from telegram.ext import Updater from telegram.utils.helpers import escape_markdown +from handlers.message_handlers import UploadNewTorrent from helpers import format_speed CONFIG = configparser.ConfigParser() @@ -123,16 +125,24 @@ def cleanup(): return +def init_polling(client): + updater = Updater(token=CONFIG['Telegram']['bot_token'], use_context=True) + dispatcher = updater.dispatcher + dispatcher.add_handler(UploadNewTorrent(client)) + updater.start_polling() + + def main(): + logging.basicConfig( + format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', + level=logging.INFO) backend_name = CONFIG.get('General', 'backend') backend = importlib.import_module('backends.' + backend_name.lower()) client = backend.Client(CONFIG.get(backend_name, 'host'), CONFIG.get(backend_name, 'port')) - logging.basicConfig( - format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', - level=logging.INFO) + init_polling(client) torrents_tracked = set() time_counter = TimeCounter() while True: