Python telegram.TelegramError() Examples

The following are 30 code examples of telegram.TelegramError(). 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 , or try the search function .
Example #1
Source File: utils.py    From UnivaqBot with MIT License 7 votes vote down vote up
def botupdated_message(bot, job):
    """
    Defining a command to notify the user and tell them what updates have been released
    It is called at every execution ONLY if there are documents in a specific db collection
    """

    messages = list(DATABASE.messages.find())
    DATABASE.messages.remove()

    invalid_chatid = []

    for message in messages:
        for chat_id in USERS['telegramID']:
            try:
                bot.sendMessage(chat_id, parse_mode='HTML',
                                text=message['text'])
            except TelegramError:
                invalid_chatid.append(chat_id)

    for chat_id in invalid_chatid:
        USERS['telegramID'].remove(chat_id)
        unsubscribe_user(chat_id, 'telegramID') 
Example #2
Source File: stickers.py    From SkittBot with GNU General Public License v3.0 7 votes vote down vote up
def makepack_internal(msg, user, png_sticker, emoji, bot, packname, packnum):
    name = user.first_name
    name = name[:50]
    try:
        extra_version = ""
        if packnum > 0:
            extra_version = " " + str(packnum)
        success = bot.create_new_sticker_set(user.id, packname, f"{name}s kang pack" + extra_version,
                                             png_sticker=png_sticker,
                                             emojis=emoji)
    except TelegramError as e:
        print(e)
        if e.message == "Sticker set name is already occupied":
            msg.reply_text("Your pack can be found [here](t.me/addstickers/%s)" % packname,
                           parse_mode=ParseMode.MARKDOWN)
        elif e.message == "Peer_id_invalid":
            msg.reply_text("Contact me in PM first.", reply_markup=InlineKeyboardMarkup([[InlineKeyboardButton(
                text="Start", url=f"t.me/{bot.username}")]]))
        elif e.message == "Internal Server Error: created sticker set not found (500)":
                msg.reply_text("Sticker pack successfully created. Get it [here](t.me/addstickers/%s)" % packname,
                       parse_mode=ParseMode.MARKDOWN)
        return

    if success:
        msg.reply_text("Sticker pack successfully created. Get it [here](t.me/addstickers/%s)" % packname,
                       parse_mode=ParseMode.MARKDOWN)
    else:
        msg.reply_text("Failed to create sticker pack. Possibly due to blek mejik.") 
Example #3
Source File: MessageQueryResponseDispatcher.py    From InLaTeXbot with GNU General Public License v3.0 7 votes vote down vote up
def respondToMessageQuery(self, message):
        senderId = message.from_user.id
        chatId = message.chat.id
        messageId = message.message_id
        expression = message.text
        
        errorMessage = None
        try:
            imageStream, pdfStream = self._latexConverter.convertExpressionToPng(expression, senderId, str(messageId)+str(senderId), returnPdf=True)
            self._bot.sendDocument(chatId, pdfStream, filename="expression.pdf")
            self._bot.sendPhoto(chatId, imageStream)
        except ValueError as err:
            errorMessage = self.getWrongSyntaxResult(expression, err.args[0])
        except TelegramError as err:
            errorMessage = self._resourceManager.getString("telegram_error")+str(err)
            self.logger.warn(errorMessage)
        finally:
            if not errorMessage is None:
                self._bot.sendMessage(chatId, errorMessage)
            self.logger.debug("Answered to message from %d, chatId %d, expression: %s", 
                                                        senderId, chatId, expression) 
Example #4
Source File: bismillah.py    From BismillahBot with GNU Affero General Public License v3.0 6 votes vote down vote up
def main():
    global update_id
    bot = telegram.Bot(token=TOKEN)

    try:
        update_id = bot.get_updates()[0].update_id
    except IndexError:
        update_id = None

    interface = telegram.ReplyKeyboardMarkup(
        [["Arabic", "Audio", "English", "Tafsir"],
         ["Previous", "Random", "Next"]],
        resize_keyboard=True)

    data = {
        "english": Quran("translation"),
        "tafsir": Quran("tafsir"),
        "index": make_index(),
        "interface": interface
    }
    data["default_query_results"] = get_default_query_results(data["english"])

    while True:
        try:
            serve(bot, data)
        except NetworkError:
            sleep(1)
        except Unauthorized:  # user has removed or blocked the bot
            update_id += 1
        except TelegramError as e:
            if "Invalid server response" in str(e):
                sleep(3)
            else:
                raise e 
Example #5
Source File: bot.py    From welcomebot with GNU General Public License v2.0 6 votes vote down vote up
def error(update, context, **kwargs):
    """ Error handling """
    error = context.error

    try:
        if isinstance(error, TelegramError) and (
            error.message == "Unauthorized"
            or error.message == "Have no rights to send a message"
            or "PEER_ID_INVALID" in error.message
        ):
            chats = db.get("chats")
            chats.remove(update.message.chat_id)
            db.set("chats", chats)
            logger.info("Removed chat_id %s from chat list" % update.message.chat_id)
        else:
            logger.error("An error (%s) occurred: %s" % (type(error), error.message))
    except:
        pass 
Example #6
Source File: updater.py    From telegram-robot-rss with Mozilla Public License 2.0 6 votes vote down vote up
def _check_ssl_cert(self, cert, key):
        # Check SSL-Certificate with openssl, if possible
        try:
            exit_code = subprocess.call(
                ["openssl", "x509", "-text", "-noout", "-in", cert],
                stdout=open(os.devnull, 'wb'),
                stderr=subprocess.STDOUT)
        except OSError:
            exit_code = 0
        if exit_code is 0:
            try:
                self.httpd.socket = ssl.wrap_socket(
                    self.httpd.socket, certfile=cert, keyfile=key, server_side=True)
            except ssl.SSLError as error:
                self.logger.exception('Failed to init SSL socket')
                raise TelegramError(str(error))
        else:
            raise TelegramError('SSL Certificate invalid') 
Example #7
Source File: locks.py    From tgbot with GNU General Public License v3.0 5 votes vote down vote up
def unrestr_members(bot, chat_id, members, messages=True, media=True, other=True, previews=True):
    for mem in members:
        try:
            bot.restrict_chat_member(chat_id, mem.user,
                                     can_send_messages=messages,
                                     can_send_media_messages=media,
                                     can_send_other_messages=other,
                                     can_add_web_page_previews=previews)
        except TelegramError:
            pass 
Example #8
Source File: locks.py    From tgbot with GNU General Public License v3.0 5 votes vote down vote up
def restr_members(bot, chat_id, members, messages=False, media=False, other=False, previews=False):
    for mem in members:
        if mem.user in SUDO_USERS:
            pass
        try:
            bot.restrict_chat_member(chat_id, mem.user,
                                     can_send_messages=messages,
                                     can_send_media_messages=media,
                                     can_send_other_messages=other,
                                     can_add_web_page_previews=previews)
        except TelegramError:
            pass


# NOT ASYNC 
Example #9
Source File: users.py    From tgbot with GNU General Public License v3.0 5 votes vote down vote up
def broadcast(bot: Bot, update: Update):
    to_send = update.effective_message.text.split(None, 1)
    if len(to_send) >= 2:
        chats = sql.get_all_chats() or []
        failed = 0
        for chat in chats:
            try:
                bot.sendMessage(int(chat.chat_id), to_send[1])
                sleep(0.1)
            except TelegramError:
                failed += 1
                LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name))

        update.effective_message.reply_text("Broadcast complete. {} groups failed to receive the message, probably "
                                            "due to being kicked.".format(failed)) 
Example #10
Source File: bismillah.py    From BismillahBot with GNU Affero General Public License v3.0 5 votes vote down vote up
def send_file(bot, filename, quran_type, **kwargs):
    """Tries to send file from Telegram's cache, only uploads from disk if necessary.
    Always saves the Telegram cache file_id in Redis and returns it.
    """

    def upload(f):
        if quran_type == "arabic":
            v = bot.send_photo(photo=f, **kwargs)["photo"][-1]["file_id"]
        elif quran_type == "audio":
            v = bot.send_audio(audio=f, **kwargs)["audio"]["file_id"]
        save_file(filename, v)
        return v

    def upload_from_disk():
        with open(filename, "rb") as f:
            return upload(f)

    f = get_file(filename)
    if f is not None:
        try:
            return upload(f)
        except telegram.TelegramError as e:
            if "file_id" in e.message:
                return upload_from_disk()
            else:
                raise e
    else:
        return upload_from_disk() 
Example #11
Source File: special.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def snipe(bot: Bot, update: Update, args: List[str]):
    try:
        chat_id = str(args[0])
        del args[0]
    except TypeError as excp:
        update.effective_message.reply_text("Please give me a chat to echo to!")
    to_send = " ".join(args)
    if len(to_send) >= 2:
        try:
            bot.sendMessage(int(chat_id), str(to_send))
        except TelegramError:
            LOGGER.warning("Couldn't send to group %s", str(chat_id))
            update.effective_message.reply_text("Couldn't send the message. Perhaps I'm not part of that group?") 
Example #12
Source File: locks.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def unrestr_members(bot, chat_id, members, messages=True, media=True, other=True, previews=True):
    for mem in members:
        try:
            bot.restrict_chat_member(chat_id, mem.user,
                                     can_send_messages=messages,
                                     can_send_media_messages=media,
                                     can_send_other_messages=other,
                                     can_add_web_page_previews=previews)
        except TelegramError:
            pass 
Example #13
Source File: locks.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def restr_members(bot, chat_id, members, messages=False, media=False, other=False, previews=False):
    for mem in members:
        if mem.user in SUDO_USERS:
            pass
        try:
            bot.restrict_chat_member(chat_id, mem.user,
                                     can_send_messages=messages,
                                     can_send_media_messages=media,
                                     can_send_other_messages=other,
                                     can_add_web_page_previews=previews)
        except TelegramError:
            pass


# NOT ASYNC 
Example #14
Source File: users.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def broadcast(bot: Bot, update: Update):
    to_send = update.effective_message.text.split(None, 1)
    if len(to_send) >= 2:
        chats = sql.get_all_chats() or []
        failed = 0
        for chat in chats:
            try:
                bot.sendMessage(int(chat.chat_id), to_send[1])
                sleep(0.1)
            except TelegramError:
                failed += 1
                LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name))

        update.effective_message.reply_text("Broadcast complete. {} groups failed to receive the message, probably "
                                            "due to being kicked.".format(failed)) 
Example #15
Source File: updater.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def _bootstrap(self, max_retries, clean, webhook_url, allowed_updates, cert=None):
        retries = 0
        while 1:

            try:
                if clean:
                    # Disable webhook for cleaning
                    self.bot.delete_webhook()
                    self._clean_updates()
                    sleep(1)

                self.bot.set_webhook(
                    url=webhook_url, certificate=cert, allowed_updates=allowed_updates)
            except (Unauthorized, InvalidToken):
                raise
            except TelegramError:
                msg = 'error in bootstrap phase; try={0} max_retries={1}'.format(retries,
                                                                                 max_retries)
                if max_retries < 0 or retries < max_retries:
                    self.logger.warning(msg)
                    retries += 1
                else:
                    self.logger.exception(msg)
                    raise
            else:
                break
            sleep(1) 
Example #16
Source File: dispatcher.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def add_error_handler(self, callback):
        """Registers an error handler in the Dispatcher.

        Args:
            callback (:obj:`callable`): A function that takes ``Bot, Update, TelegramError`` as
                arguments.

        """
        self.error_handlers.append(callback) 
Example #17
Source File: dispatcher.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def start(self):
        """Thread target of thread 'dispatcher'.

        Runs in background and processes the update queue.

        """
        if self.running:
            self.logger.warning('already running')
            return

        if self.__exception_event.is_set():
            msg = 'reusing dispatcher after exception event is forbidden'
            self.logger.error(msg)
            raise TelegramError(msg)

        self._init_async_threads(uuid4(), self.workers)
        self.running = True
        self.logger.debug('Dispatcher started')

        while 1:
            try:
                # Pop update from update queue.
                update = self.update_queue.get(True, 1)
            except Empty:
                if self.__stop_event.is_set():
                    self.logger.debug('orderly stopping')
                    break
                elif self.__exception_event.is_set():
                    self.logger.critical('stopping due to exception in another thread')
                    break
                continue

            self.logger.debug('Processing Update: %s' % update)
            self.process_update(update)

        self.running = False
        self.logger.debug('Dispatcher thread stopped') 
Example #18
Source File: inputfile.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def is_image(stream):
        """Check if the content file is an image by analyzing its headers.

        Args:
            stream (:obj:`str`): A str representing the content of a file.

        Returns:
            :obj:`str`: The str mime-type of an image.

        """
        image = imghdr.what(None, stream)
        if image:
            return 'image/%s' % image

        raise TelegramError('Could not parse file content') 
Example #19
Source File: inputfile.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, data):
        self.data = data
        self.boundary = choose_boundary()

        for t in FILE_TYPES:
            if t in data:
                self.input_name = t
                self.input_file = data.pop(t)
                break
        else:
            raise TelegramError('Unknown inputfile type')

        if hasattr(self.input_file, 'read'):
            self.filename = None
            self.input_file_content = self.input_file.read()
            if 'filename' in data:
                self.filename = self.data.pop('filename')
            elif hasattr(self.input_file, 'name'):
                # on py2.7, pylint fails to understand this properly
                # pylint: disable=E1101
                self.filename = os.path.basename(self.input_file.name)

            try:
                self.mimetype = self.is_image(self.input_file_content)
                if not self.filename or '.' not in self.filename:
                    self.filename = self.mimetype.replace('/', '.')
            except TelegramError:
                if self.filename:
                    self.mimetype = mimetypes.guess_type(
                        self.filename)[0] or DEFAULT_MIME_TYPE
                else:
                    self.mimetype = DEFAULT_MIME_TYPE 
Example #20
Source File: locks.py    From EmiliaHikari with GNU General Public License v3.0 5 votes vote down vote up
def unrestr_members(bot, chat_id, members, messages=True, media=True, other=True, previews=True):
	for mem in members:
		try:
			bot.restrict_chat_member(chat_id, mem.user,
									 can_send_messages=messages,
									 can_send_media_messages=media,
									 can_send_other_messages=other,
									 can_add_web_page_previews=previews)
		except TelegramError:
			pass 
Example #21
Source File: locks.py    From EmiliaHikari with GNU General Public License v3.0 5 votes vote down vote up
def restr_members(bot, chat_id, members, messages=False, media=False, other=False, previews=False):
	for mem in members:
		if mem.user in SUDO_USERS:
			pass
		try:
			bot.restrict_chat_member(chat_id, mem.user,
									 can_send_messages=messages,
									 can_send_media_messages=media,
									 can_send_other_messages=other,
									 can_add_web_page_previews=previews)
		except TelegramError:
			pass


# NOT ASYNC 
Example #22
Source File: users.py    From EmiliaHikari with GNU General Public License v3.0 5 votes vote down vote up
def broadcast(update, context):
    to_send = update.effective_message.text.split(None, 1)
    if len(to_send) >= 2:
        chats = sql.get_all_chats() or []
        failed = 0
        for chat in chats:
            try:
                context.bot.sendMessage(int(chat.chat_id), to_send[1])
                sleep(0.1)
            except TelegramError:
                failed += 1
                LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name))

        send_message(update.effective_message, "Siaran selesai. {} grup gagal menerima pesan, mungkin "
                                            "karena ditendang.".format(failed)) 
Example #23
Source File: util.py    From BotListBot with MIT License 5 votes vote down vote up
def restricted(func=None, strict=False, silent=False):
    if func is None:
        # If called without method, we've been called with optional arguments.
        # We return a decorator with the optional arguments filled in.
        return partial(restricted, strict=strict, silent=silent)

    @wraps(func)
    def wrapped(bot, update, *args, **kwargs):
        chat_id = update.effective_user.id

        if chat_id not in settings.MODERATORS:
            try:
                print("Unauthorized access denied for {}.".format(chat_id))
                if not silent:
                    bot.sendPhoto(chat_id, open(appglobals.ROOT_DIR + '/assets/img/go_away_noob.png', 'rb'),
                                  caption="Moderator Area. Unauthorized.")
                return
            except (TelegramError, AttributeError):
                return

        if strict and chat_id not in settings.ADMINS:
            if not silent:
                bot.sendMessage(chat_id, "This function is restricted to the channel creator.")
            return

        return func(bot, update, *args, **kwargs)

    return wrapped 
Example #24
Source File: special.py    From SkittBot with GNU General Public License v3.0 5 votes vote down vote up
def snipe(bot: Bot, update: Update, args: List[str]):
    try:
        chat_id = str(args[0])
        del args[0]
    except TypeError as excp:
        update.effective_message.reply_text("Please give me a chat to echo to!")
    to_send = " ".join(args)
    if len(to_send) >= 2:
        try:
            bot.sendMessage(int(chat_id), str(to_send))
        except TelegramError:
            LOGGER.warning("Couldn't send to group %s", str(chat_id))
            update.effective_message.reply_text("Couldn't send the message. Perhaps I'm not part of that group?") 
Example #25
Source File: locks.py    From SkittBot with GNU General Public License v3.0 5 votes vote down vote up
def unrestr_members(bot, chat_id, members, messages=True, media=True, other=True, previews=True):
    for mem in members:
        try:
            bot.restrict_chat_member(chat_id, mem.user,
                                     can_send_messages=messages,
                                     can_send_media_messages=media,
                                     can_send_other_messages=other,
                                     can_add_web_page_previews=previews)
        except TelegramError:
            pass 
Example #26
Source File: locks.py    From SkittBot with GNU General Public License v3.0 5 votes vote down vote up
def restr_members(bot, chat_id, members, messages=False, media=False, other=False, previews=False):
    for mem in members:
        if mem.user in SUDO_USERS:
            pass
        try:
            bot.restrict_chat_member(chat_id, mem.user,
                                     can_send_messages=messages,
                                     can_send_media_messages=media,
                                     can_send_other_messages=other,
                                     can_add_web_page_previews=previews)
        except TelegramError:
            pass


# NOT ASYNC 
Example #27
Source File: users.py    From SkittBot with GNU General Public License v3.0 5 votes vote down vote up
def broadcast(bot: Bot, update: Update):
    to_send = update.effective_message.text.split(None, 1)
    if len(to_send) >= 2:
        chats = sql.get_all_chats() or []
        failed = 0
        for chat in chats:
            try:
                bot.sendMessage(int(chat.chat_id), to_send[1])
                sleep(0.1)
            except TelegramError:
                failed += 1
                LOGGER.warning("Couldn't send broadcast to %s, group name %s", str(chat.chat_id), str(chat.chat_name))

        update.effective_message.reply_text("Broadcast complete. {} groups failed to receive the message, probably "
                                            "due to being kicked.".format(failed)) 
Example #28
Source File: dispatcher.py    From telegram-robot-rss with Mozilla Public License 2.0 4 votes vote down vote up
def process_update(self, update):
        """Processes a single update.

        Args:
            update (:obj:`str` | :class:`telegram.Update` | :class:`telegram.TelegramError`):
                The update to process.

        """
        # An error happened while polling
        if isinstance(update, TelegramError):
            try:
                self.dispatch_error(None, update)
            except Exception:
                self.logger.exception('An uncaught error was raised while handling the error')
            return

        for group in self.groups:
            try:
                for handler in (x for x in self.handlers[group] if x.check_update(update)):
                    handler.handle_update(update, self)
                    break

            # Stop processing with any other handler.
            except DispatcherHandlerStop:
                self.logger.debug('Stopping further handlers due to DispatcherHandlerStop')
                break

            # Dispatch any error.
            except TelegramError as te:
                self.logger.warning('A TelegramError was raised while processing the Update')

                try:
                    self.dispatch_error(update, te)
                except DispatcherHandlerStop:
                    self.logger.debug('Error handler stopped further handlers')
                    break
                except Exception:
                    self.logger.exception('An uncaught error was raised while handling the error')

            # Errors should not stop the thread.
            except Exception:
                self.logger.exception('An uncaught error was raised while processing the update') 
Example #29
Source File: updater.py    From telegram-robot-rss with Mozilla Public License 2.0 4 votes vote down vote up
def _start_polling(self, poll_interval, timeout, read_latency, bootstrap_retries, clean,
                       allowed_updates):  # pragma: no cover
        # """
        # Thread target of thread 'updater'. Runs in background, pulls
        # updates from Telegram and inserts them in the update queue of the
        # Dispatcher.
        # """

        cur_interval = poll_interval
        self.logger.debug('Updater thread started')

        self._bootstrap(bootstrap_retries, clean=clean, webhook_url='', allowed_updates=None)

        while self.running:
            try:
                updates = self.bot.get_updates(
                    self.last_update_id,
                    timeout=timeout,
                    read_latency=read_latency,
                    allowed_updates=allowed_updates)
            except RetryAfter as e:
                self.logger.info(str(e))
                cur_interval = 0.5 + e.retry_after
            except TelegramError as te:
                self.logger.error("Error while getting Updates: {0}".format(te))

                # Put the error into the update queue and let the Dispatcher
                # broadcast it
                self.update_queue.put(te)

                cur_interval = self._increase_poll_interval(cur_interval)
            else:
                if not self.running:
                    if len(updates) > 0:
                        self.logger.debug('Updates ignored and will be pulled '
                                          'again on restart.')
                    break

                if updates:
                    for update in updates:
                        self.update_queue.put(update)
                    self.last_update_id = updates[-1].update_id + 1

                cur_interval = poll_interval

            sleep(cur_interval) 
Example #30
Source File: news.py    From UnivaqBot with MIT License 4 votes vote down vote up
def notify_news(bot, job):
    """Defining method that will be repeated over and over"""

    translation = {
        'disim': 'Disim',
        'univaq': 'Univaq',
        'discab_general': 'Discab',
        'discab_biotechnology': 'Biotecnologie',
        'discab_medical': 'Discab Medicina',
        'discab_motor_science': 'Scienze Motorie',
        'discab_psychology': 'Psicologia',
        'mesva_general': 'Mesva',
        'mesva_medical': 'Mesva Medicina',
        'mesva_environmental_science': 'Scienze Ambientali',
        'mesva_biological_science': 'Scienze Biologiche'
    }

    checked = check_news()
    unread_news = checked['unread_news']
    pulled_news = checked['pulled_news']
    invalid_chatid = []

    for section in unread_news:
        if unread_news[section]:
            news_to_string = "<b>"+translation[section]+"</b>\n\n"

            utils.NEWS = pulled_news
            utils.store_news(pulled_news)

            for item in unread_news[section]:
                news_to_string += ('- <a href="{link}">{title}</a>\n'
                                   '\t<i>{description}</i>\n\n').format(**item)

            for chat_id in utils.USERS[section]:
                try:
                    bot.sendMessage(chat_id, parse_mode='HTML', disable_web_page_preview=True,
                                    text=news_to_string)
                except TelegramError:
                    invalid_chatid.append(chat_id)

            for chat_id in invalid_chatid:
                utils.USERS[section].remove(chat_id)
                utils.unsubscribe_user(chat_id, section)