Python telegram.ext.Filters.document() Examples

The following are 24 code examples of telegram.ext.Filters.document(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telegram.ext.Filters , or try the search function .
Example #1
Source File: bot.py    From Telegram-bot-Google-Drive with MIT License 9 votes vote down vote up
def file_handler(update, context):
  """handles the uploaded files"""

  file = context.bot.getFile(update.message.document.file_id)
  file.download(update.message.document.file_name)

  doc = update.message.document

  service = build('drive', 'v3', credentials=getCreds(),cache_discovery=False)
  filename = doc.file_name

  metadata = {'name': filename}
  media = MediaFileUpload(filename, chunksize=1024 * 1024, mimetype=doc.mime_type,  resumable=True)
  request = service.files().create(body=metadata,
                                media_body=media)

  response = None
  while response is None:
    status, response = request.next_chunk()
    if status:
       print( "Uploaded %d%%." % int(status.progress() * 100))

  context.bot.send_message(chat_id=update.effective_chat.id, text="✅ File uploaded!") 
Example #2
Source File: telegram.py    From platypush with MIT License 7 votes vote down vote up
def run(self):
        # noinspection PyPackageRequirements
        from telegram.ext import MessageHandler, Filters

        super().run()
        telegram = self._plugin.get_telegram()
        dispatcher = telegram.dispatcher

        dispatcher.add_handler(MessageHandler(Filters.group, self._group_hook()))
        dispatcher.add_handler(MessageHandler(Filters.text, self._msg_hook(TextMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.photo, self._msg_hook(PhotoMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.video, self._msg_hook(VideoMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.contact, self._msg_hook(ContactMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.location, self._msg_hook(LocationMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.document, self._msg_hook(DocumentMessageEvent)))
        dispatcher.add_handler(MessageHandler(Filters.command, self._command_hook()))

        self.logger.info('Initialized Telegram backend')
        telegram.start_polling()


# vim:sw=4:ts=4:et: 
Example #3
Source File: bot.py    From Awesome-Python-Scripts with MIT License 6 votes vote down vote up
def get(bot, update):
    """Send requested file."""
    username = update.message.from_user.username
    if(username not in username_list):
        update.message.reply_text("You are not Authorized.")
        return
    file = update.message.text.split(" ")[-1]
    if(file == "/send"):
        update.message.reply_text("Invalid File name.")
    else:
        reply = "Findind and Sending a requested file to you. Hold on..."
        update.message.reply_text(reply)
        path = os.getcwd()+'/'+file
        if (os.path.exists(path)):
            bot.send_document(chat_id=update.message.chat_id,document=open(path, 'rb'), timeout = 100)
        else:
            update.message.reply_text("File not Found.") 
Example #4
Source File: compiler.py    From superCodingBot with MIT License 6 votes vote down vote up
def __init__(self, api_key, fallback):
        self.compiler = HackerRankAPI(api_key=api_key)
        self.conv_handler = ConversationHandler(
            entry_points=[CommandHandler('compiler', self.compilers)],
            allow_reentry=True,
            states={
                LANG: [CallbackQueryHandler(self.lang, pass_user_data=True, pattern=r'\w*comp1\b')],
                CODE: [CallbackQueryHandler(self.code, pass_user_data=True, pattern=r'\w*so1\b')],
                DECODE: [MessageHandler(Filters.text, self.decode, pass_user_data=True)],
                TESTCASES: [MessageHandler(Filters.text, self.testcases, pass_user_data=True)],
                OTHER: [MessageHandler(Filters.text, self.other, pass_user_data=True)],
                FILE: [MessageHandler(Filters.document, self.filer, pass_user_data=True)],
                FILETEST: [MessageHandler(Filters.document, self.filetest, pass_user_data=True)]
            },
            fallbacks=[fallback]
        ) 
Example #5
Source File: compiler.py    From superCodingBot with MIT License 6 votes vote down vote up
def filetest(self, bot, update, user_data):
        file_id = update.message.document.file_id
        if ComHandler.check_file_size(update):
            return ConversationHandler.END
        newFile = bot.get_file(file_id)
        newFile.download('test.txt')
        with open('test.txt', 'rt') as f:
            source = f.read()
        s1 = (str(user_data['code'])).replace("«", "<<").replace("»", ">>")
        result = self.compiler.run({'source': s1,
                               'lang': user_data['lang'],
                               'testcases': [source]
                               })
        Utility.paginate(bot, update, result)
        user_data.clear()
        os.remove('test.txt')
        return ConversationHandler.END 
Example #6
Source File: admin.py    From superCodingBot with MIT License 6 votes vote down vote up
def __init__(self, mount_point, admin_list, fallback):
        self.admin_list = admin_list
        self.mount_point = mount_point
        self.utility = Utility(mount_point)
        self.conv_handler1 = ConversationHandler(
            entry_points=[CommandHandler('broadcast', self.broadcast)],
            allow_reentry=True,
            states={
                BDC: [MessageHandler(Filters.text, self.broadcast_message)]
            },
            fallbacks=[fallback]
        )
        self.conv_handler2 = ConversationHandler(
            entry_points=[CommandHandler('senddb', self.getDb)],
            allow_reentry=True,
            states={
                DB: [MessageHandler(Filters.document, self.db)]
            },
            fallbacks=[fallback]
        )

    # START OF ADMIN CONVERSATION HANDLER TO BROADCAST MESSAGE 
Example #7
Source File: telegrambot.py    From OpenCryptoBot with GNU Affero General Public License v3.0 6 votes vote down vote up
def _download(self, bot, update):
        # Check if in a private chat
        if bot.get_chat(update.message.chat_id).type != Chat.PRIVATE:
            return

        # Check if user that triggered the command is allowed to execute it
        if update.effective_user.id not in Cfg.get("admin_id"):
            return

        name = update.message.effective_attachment.file_name
        file = bot.getFile(update.message.document.file_id)
        file.download(os.path.join(con.SRC_DIR, con.PLG_DIR, name))

        try:
            self.reload_plugin(name.replace(".py", ""))
            update.message.reply_text(f"{emo.CHECK} Plugin loaded successfully")
        except Exception as ex:
            update.message.reply_text(f"{emo.ERROR} {ex}") 
Example #8
Source File: telegram.py    From platypush with MIT License 6 votes vote down vote up
def _group_hook(self):
        # noinspection PyUnusedLocal
        def hook(update, context):
            msg = update.effective_message
            if msg.group_chat_created:
                self.bus.post(GroupChatCreatedEvent(chat_id=update.effective_chat.id,
                                                    message=self._plugin.parse_msg(msg).output,
                                                    user=self._plugin.parse_user(update.effective_user).output))
            elif msg.photo:
                self._msg_hook(PhotoMessageEvent)(update, context)
            elif msg.video:
                self._msg_hook(VideoMessageEvent)(update, context)
            elif msg.contact:
                self._msg_hook(ContactMessageEvent)(update, context)
            elif msg.location:
                self._msg_hook(LocationMessageEvent)(update, context)
            elif msg.document:
                self._msg_hook(DocumentMessageEvent)(update, context)
            elif msg.text:
                if msg.text.startswith('/'):
                    self._command_hook()(update, context)
                else:
                    self._msg_hook(TextMessageEvent)(update, context)

        return hook 
Example #9
Source File: handlers_messages.py    From TranscriberBot with GNU General Public License v3.0 6 votes vote down vote up
def document(bot, update):
  chat_id = get_chat_id(update)
  voice_enabled = TBDB.get_chat_voice_enabled(chat_id)

  m = update.message or update.channel_post
  file_name = m.document.file_name
  _, file_ext = os.path.splitext(file_name)

  if file_ext[1:] not in config.get_config_prop("app")["audio_ext"]:
    logger.info('extension %s not recognized', file_ext)
    return

  if voice_enabled == 0:
    return

  if voice_enabled == 2:
    pass
  else:
    TranscriberBot.get().voice_thread_pool.submit(
      process_media_voice, bot, update, m.document, 'audio_document'
    ) 
Example #10
Source File: admin.py    From superCodingBot with MIT License 5 votes vote down vote up
def adminhandle(self, bot, update):
        if self.not_admin(update):
            return
        conn = sqlite3.connect(self.mount_point + 'coders1.db')
        c = conn.cursor()
        mysel = c.execute("SELECT * FROM handles")
        self.utility.xlsx_creator(mysel, "admin.xlsx")
        bot.send_document(chat_id=update.message.chat_id, document=open('admin.xlsx', 'rb'))
        os.remove('admin.xlsx')
        conn.close() 
Example #11
Source File: locks.py    From tgbot with GNU General Public License v3.0 5 votes vote down vote up
def build_lock_message(chat_id):
    locks = sql.get_locks(chat_id)
    restr = sql.get_restr(chat_id)
    if not (locks or restr):
        res = "There are no current locks in this chat."
    else:
        res = "These are the locks in this chat:"
        if locks:
            res += "\n - sticker = `{}`" \
                   "\n - audio = `{}`" \
                   "\n - voice = `{}`" \
                   "\n - document = `{}`" \
                   "\n - video = `{}`" \
                   "\n - videonote = `{}`" \
                   "\n - contact = `{}`" \
                   "\n - photo = `{}`" \
                   "\n - gif = `{}`" \
                   "\n - url = `{}`" \
                   "\n - bots = `{}`" \
                   "\n - forward = `{}`" \
                   "\n - game = `{}`" \
                   "\n - location = `{}`".format(locks.sticker, locks.audio, locks.voice, locks.document,
                                                 locks.video, locks.videonote, locks.contact, locks.photo, locks.gif, locks.url,
                                                 locks.bots, locks.forward, locks.game, locks.location)
        if restr:
            res += "\n - messages = `{}`" \
                   "\n - media = `{}`" \
                   "\n - other = `{}`" \
                   "\n - previews = `{}`" \
                   "\n - all = `{}`".format(restr.messages, restr.media, restr.other, restr.preview,
                                            all([restr.messages, restr.media, restr.other, restr.preview]))
    return res 
Example #12
Source File: bot.py    From Awesome-Python-Scripts with MIT License 5 votes vote down vote up
def main():
    """Start the bot."""
    # Create the EventHandler and pass it your bot's token.
    TOKEN = os.environ['TOKEN']
    updater = Updater(TOKEN)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))
    dp.add_handler(CommandHandler("get", get))
    dp.add_handler(CommandHandler("ls", ls))
    dp.add_handler(CommandHandler("put", put))
    dp.add_handler(CommandHandler("mkdir", mkdir))

    #admin functionalities
    dp.add_handler(CommandHandler("adduser", add_user))
    dp.add_handler(CommandHandler("showuser", show_user))
    dp.add_handler(CommandHandler("removeUser", remove_user))
    dp.add_handler(CommandHandler("remove", remove))
    dp.add_handler(CommandHandler("rmdir", rmdir))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.document, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle() 
Example #13
Source File: bot.py    From Awesome-Python-Scripts with MIT License 5 votes vote down vote up
def echo(bot, update):
    """Echo the user message."""
    if update.message.document:
        file_id = update.message.document.file_id
        f = open(str(os.getcwd())+"/file", "w")
        f.write(file_id)
        f.close
        update.message.reply_text("Received.Now send file name and location to store. using /put command")
    else:
        reply = "Invalid Input."
        update.message.reply_text(reply) 
Example #14
Source File: locks.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def build_lock_message(chat_id):
    locks = sql.get_locks(chat_id)
    restr = sql.get_restr(chat_id)
    if not (locks or restr):
        res = "There are no current locks in this chat."
    else:
        res = "These are the locks in this chat:"
        if locks:
            res += "\n - sticker = `{}`" \
                   "\n - audio = `{}`" \
                   "\n - voice = `{}`" \
                   "\n - document = `{}`" \
                   "\n - video = `{}`" \
                   "\n - contact = `{}`" \
                   "\n - photo = `{}`" \
                   "\n - gif = `{}`" \
                   "\n - url = `{}`" \
                   "\n - bots = `{}`" \
                   "\n - forward = `{}`" \
                   "\n - game = `{}`" \
                   "\n - location = `{}`".format(locks.sticker, locks.audio, locks.voice, locks.document,
                                                 locks.video, locks.contact, locks.photo, locks.gif, locks.url,
                                                 locks.bots, locks.forward, locks.game, locks.location)
        if restr:
            res += "\n - messages = `{}`" \
                   "\n - media = `{}`" \
                   "\n - other = `{}`" \
                   "\n - previews = `{}`" \
                   "\n - all = `{}`".format(restr.messages, restr.media, restr.other, restr.preview,
                                            all([restr.messages, restr.media, restr.other, restr.preview]))
    return res 
Example #15
Source File: admin.py    From superCodingBot with MIT License 5 votes vote down vote up
def getcfjson(self, bot, update):
        if self.not_admin(update):
            return
        bot.send_document(chat_id=update.message.chat_id, document=open(self.mount_point + 'codeforces.json', 'rb'))

    # ADMIN COMMAND HANDLER FUNCTION TO GET THE DETAILS OF HANDLES OF ALL THE USERS IN DATABASE 
Example #16
Source File: admin.py    From superCodingBot with MIT License 5 votes vote down vote up
def givememydb(self, bot, update):
        if self.not_admin(update):
            return
        bot.send_document(chat_id=update.message.chat_id, document=open(self.mount_point + 'coders1.db', 'rb'))

    # ADMIN COMMAND HANDLER FOR GETTING THE CODEFORCES JSON 
Example #17
Source File: admin.py    From superCodingBot with MIT License 5 votes vote down vote up
def db(self, bot, update):
        file_id = update.message.document.file_id
        newFile = bot.get_file(file_id)
        newFile.download(self.mount_point + 'coders1.db')
        update.message.reply_text("saved")
        return ConversationHandler.END

    # END OF ADMIN CONVERSATION HANDLER TO REPLACE THE DATABASE 
Example #18
Source File: compiler.py    From superCodingBot with MIT License 5 votes vote down vote up
def check_file_size(update):
        file_size = update.message.document.file_size
        if file_size > 2097152:
            update.message.reply_text("FILE SIZE GREATER THAN 2 MB")
            return True
        return False

    # FUNCTION TO DOWNLOAD THE FILE SENT AND EXTRACT ITS CONTENTS 
Example #19
Source File: app.py    From superCodingBot with MIT License 5 votes vote down vote up
def receive_cf(self, bot, update):
        file_id = update.message.document.file_id
        newFile = bot.get_file(file_id)
        newFile.download(self.mount_point + 'codeforces.json')
        update.message.reply_text("saved")
        with open(self.mount_point + 'codeforces.json', 'r') as code_json:
            self.cf.change_cf(json.load(code_json))
        return ConversationHandler.END

    # END OF ADMIN CONVERSATION HANDLER TO REPLACE THE CODEFORCES JSON 
Example #20
Source File: locks.py    From SkittBot with GNU General Public License v3.0 5 votes vote down vote up
def build_lock_message(chat_id):
    locks = sql.get_locks(chat_id)
    restr = sql.get_restr(chat_id)
    if not (locks or restr):
        res = "There are no current locks in this chat."
    else:
        res = "These are the locks in this chat:"
        if locks:
            res += "\n - sticker = `{}`" \
                   "\n - audio = `{}`" \
                   "\n - voice = `{}`" \
                   "\n - document = `{}`" \
                   "\n - video = `{}`" \
                   "\n - videonote = `{}`" \
                   "\n - contact = `{}`" \
                   "\n - photo = `{}`" \
                   "\n - gif = `{}`" \
                   "\n - url = `{}`" \
                   "\n - bots = `{}`" \
                   "\n - forward = `{}`" \
                   "\n - game = `{}`" \
                   "\n - location = `{}`".format(locks.sticker, locks.audio, locks.voice, locks.document,
                                                 locks.video, locks.videonote, locks.contact, locks.photo, locks.gif, locks.url,
                                                 locks.bots, locks.forward, locks.game, locks.location)
        if restr:
            res += "\n - messages = `{}`" \
                   "\n - media = `{}`" \
                   "\n - other = `{}`" \
                   "\n - previews = `{}`" \
                   "\n - all = `{}`".format(restr.messages, restr.media, restr.other, restr.preview,
                                            all([restr.messages, restr.media, restr.other, restr.preview]))
    return res 
Example #21
Source File: bot.py    From Telegram-bot-Google-Drive with MIT License 5 votes vote down vote up
def main():
  updater = Updater(token=config.TOKEN,use_context=True)
  dispatcher = updater.dispatcher
  updater.dispatcher.add_handler(CommandHandler('start', start))
  dispatcher.add_handler(MessageHandler(Filters.document,file_handler))
  updater.start_polling() 
Example #22
Source File: locks.py    From EmiliaHikari with GNU General Public License v3.0 4 votes vote down vote up
def build_lock_message(chat_id):
	locks = sql.get_locks(chat_id)
	res = ""
	locklist = []
	permslist = []
	if locks:
		res += "*" + tl(chat_id, "Ini adalah kunci dalam obrolan ini:") + "*"
		if locks:
			locklist.append("sticker = `{}`".format(locks.sticker))
			locklist.append("audio = `{}`".format(locks.audio))
			locklist.append("voice = `{}`".format(locks.voice))
			locklist.append("document = `{}`".format(locks.document))
			locklist.append("video = `{}`".format(locks.video))
			locklist.append("contact = `{}`".format(locks.contact))
			locklist.append("photo = `{}`".format(locks.photo))
			locklist.append("gif = `{}`".format(locks.gif))
			locklist.append("url = `{}`".format(locks.url))
			locklist.append("bots = `{}`".format(locks.bots))
			locklist.append("forward = `{}`".format(locks.forward))
			locklist.append("game = `{}`".format(locks.game))
			locklist.append("location = `{}`".format(locks.location))
			locklist.append("rtl = `{}`".format(locks.rtl))
			locklist.append("button = `{}`".format(locks.button))
	permissions = dispatcher.bot.get_chat(chat_id).permissions
	permslist.append("messages = `{}`".format(permissions.can_send_messages))
	permslist.append("media = `{}`".format(permissions.can_send_media_messages))
	permslist.append("poll = `{}`".format(permissions.can_send_polls))
	permslist.append("other = `{}`".format(permissions.can_send_other_messages))
	permslist.append("previews = `{}`".format(permissions.can_add_web_page_previews))
	permslist.append("info = `{}`".format(permissions.can_change_info))
	permslist.append("invite = `{}`".format(permissions.can_invite_users))
	permslist.append("pin = `{}`".format(permissions.can_pin_messages))

	if locklist:
		# Ordering lock list
		locklist.sort()
		# Building lock list string
		for x in locklist:
			res += "\n - {}".format(x)
	res += "\n\n*" + tl(chat_id, "Ini adalah izin dalam obrolan ini:") + "*"
	for x in permslist:
		res += "\n - {}".format(x)
	return res 
Example #23
Source File: telegrambot.py    From OpenCryptoBot with GNU Affero General Public License v3.0 4 votes vote down vote up
def __init__(self, bot_token, bot_db):
        self.db = bot_db
        self.token = bot_token

        read_timeout = Cfg.get("telegram", "read_timeout")
        connect_timeout = Cfg.get("telegram", "connect_timeout")

        kwargs = dict()
        if read_timeout:
            kwargs["read_timeout"] = read_timeout
        if connect_timeout:
            kwargs["connect_timeout"] = connect_timeout

        try:
            self.updater = Updater(bot_token, request_kwargs=kwargs)
        except InvalidToken as e:
            cls_name = f"Class: {type(self).__name__}"
            logging.error(f"{repr(e)} - {cls_name}")
            exit("ERROR: Bot token not valid")

        self.job_queue = self.updater.job_queue
        self.dispatcher = self.updater.dispatcher

        # Load classes in folder 'plugins'
        self._load_plugins()

        # Handler for files downloads (plugins)
        mh = MessageHandler(Filters.document, self._download)
        self.dispatcher.add_handler(mh)

        # Handler for command-links
        self._add_link_handler()

        # Handler for inline-mode
        inline_handler = InlineQueryHandler(self._inline)
        self.dispatcher.add_handler(inline_handler)

        # Handle all Telegram related errors
        self.dispatcher.add_error_handler(self._handle_tg_errors)

        # Refresh cache periodically
        self._refresh_cache()

        # Check for updates periodically
        self._update_check()

    # Start the bot 
Example #24
Source File: app.py    From superCodingBot with MIT License 4 votes vote down vote up
def __init__(self):
        logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                            level=logging.INFO)
        self.CF = 20000
        self.db = "coders1.db"
        self.logger = logging.getLogger(__name__)
        self.config = ConfigParser()
        self.config.read("config.ini")
        self.bot_token = self.config.get('telegram', 'bot_token')
        self.hr_api_key = self.config.get('hackerrank', 'api_key')
        self.clist_user_name = self.config.get('clist', 'username')
        self.clist_api_key = self.config.get('clist', 'api_key')
        self.mount_point = self.config.get('openshift', 'persistent_mount_point')
        self.utility = Utility(self.mount_point)
        self.compiler = helper.HackerRankAPI(api_key=self.hr_api_key)
        self.admin_list = str(self.config.get('telegram', 'admin_chat_id')).split(',')
        self.fallback = CommandHandler('cancel', self.cancel, pass_user_data=True)
        self.cf = codeforces.CfHandler(mount_point=self.mount_point, fallback=self.fallback)
        self.bot = Bot(self.bot_token)
        self.cc_questions = {"easy": None,
                             "hard": None,
                             "medium": None,
                             "school": None,
                             "challenge": None,
                             "peer": None}
        self.init_db()
        self.cc = codechef.CcHandler(cc_dict=self.cc_questions, fallback=self.fallback)
        self.register = register.RegHandler(mount_point=self.mount_point, fallback=self.fallback)
        self.compiler = compiler.ComHandler(api_key=self.hr_api_key, fallback=self.fallback)
        self.competitions = competitions.Competitions(clist_api_key=self.clist_api_key,
                                                      clist_user_name=self.clist_user_name,
                                                      mount_point=self.mount_point, bot=self.bot,
                                                      fallback=self.fallback)
        self.unregister = unregister.UnregHandler(mount_point=self.mount_point, fallback=self.fallback)
        self.ques_of_the_day = ques_of_the_day.QuesHandler(mount_point=self.mount_point, fallback=self.fallback)
        self.ranklist = ranklist.RankListHandler(mount_point=self.mount_point, fallback=self.fallback)
        self.update = update_rank_list.UpdateHandler(mount_point=self.mount_point, fallback=self.fallback)
        self.geeks_for_geeks = geeks_for_geeks.GeeksForGeeksHandler(fallback=self.fallback)
        self.admin = admin.AdminHandle(mount_point=self.mount_point, admin_list=self.admin_list, fallback=self.fallback)
        self.update_fun()
        self.update_fun("codechef")
        self.conv_handler = ConversationHandler(
            entry_points=[CommandHandler('sendcf', self.getCf)],
            allow_reentry=True,
            states={
                self.CF: [MessageHandler(Filters.document, self.receive_cf)]
            },
            fallbacks=[self.fallback]
        )