main.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import logging
  2. import os
  3. from subprocess import CalledProcessError
  4. from telegram.ext import Updater, MessageHandler, Filters
  5. from download_utils import APK, BadPackageNameException
  6. logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
  7. logger = logging.getLogger(__name__)
  8. def error_callback(update, context):
  9. logger.warning('Update "%s" caused error "%s"', update, context.error)
  10. def get_package(update, context):
  11. logger.info("from {}: {}".format(update.message.chat_id, update.message.text)) # "history"
  12. if update.message.text == '/start':
  13. update.message.reply_text("To start downloading APK file send me a PlayStore link ok a package name. :)")
  14. return
  15. apk = APK(update.message.text, conf=CONF, conf_file=CONF_FILE)
  16. msg = context.bot.send_message(text=f"Downloading {apk.package_name}...",
  17. chat_id=update.message.chat_id)
  18. try:
  19. apk.download()
  20. with apk.send() as files:
  21. for f in files:
  22. context.bot.send_document(chat_id=update.message.chat_id, document=open(f, 'rb'))
  23. except BadPackageNameException as e:
  24. # instead of editing the text message we delete and resend one so a new notification will trigger
  25. context.bot.send_message(text="Bad package name: {}".format(e),
  26. chat_id=update.message.chat_id)
  27. except CalledProcessError:
  28. context.bot.send_message(text="Failed to send APK file",
  29. chat_id=update.message.chat_id)
  30. context.bot.delete_message(chat_id=update.message.chat_id,
  31. message_id=msg.message_id)
  32. if os.environ.get('CONF_FOLDER') is None:
  33. logger.error("No conf folder available")
  34. exit(1)
  35. TOKEN = None
  36. with open(os.path.join(os.environ['CONF_FOLDER'], 'bot.token')) as f:
  37. TOKEN = f.read().strip()
  38. CONF = {
  39. 'yes': True,
  40. 'verbose': False,
  41. 'tokencachefile': os.path.join(os.environ['CONF_FOLDER'], 'token.cache'),
  42. }
  43. CONF_FILE = os.path.join(os.environ['CONF_FOLDER'], 'gplaycli.conf')
  44. updater = Updater(token=TOKEN)
  45. updater.dispatcher.add_handler(MessageHandler(Filters.text, get_package))
  46. updater.dispatcher.add_error_handler(error_callback)
  47. updater.start_polling()
  48. updater.idle()