Python telegram.error.TelegramError() Examples

The following are 30 code examples of telegram.error.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.error , or try the search function .
Example #1
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 6 votes vote down vote up
def delete_webhook(self, timeout=None, **kwargs):
        """
        Use this method to remove webhook integration if you decide to switch back to
        getUpdates. Requires no parameters.

        Args:
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.

        Returns:
            :obj:`bool` On success, ``True`` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/deleteWebhook'.format(self.base_url)

        data = kwargs

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #2
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 6 votes vote down vote up
def get_me(self, timeout=None, **kwargs):
        """A simple method for testing your bot's auth token. Requires no parameters.

        Args:
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).

        Returns:
            :class:`telegram.User`: A :class:`telegram.User` instance representing that bot if the
            credentials are valid, :obj:`None` otherwise.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/getMe'.format(self.base_url)

        result = self._request.get(url, timeout=timeout)

        self.bot = User.de_json(result, self)

        return self.bot 
Example #3
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 #4
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 6 votes vote down vote up
def delete_sticker_from_set(self, sticker, timeout=None, **kwargs):
        """Use this method to delete a sticker from a set created by the bot.

        Args:
            sticker (:obj:`str`): File identifier of the sticker.
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during
                creation of the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.

        Returns:
            :obj:`bool`: On success, ``True`` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/deleteStickerFromSet'.format(self.base_url)

        data = {'sticker': sticker}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #5
Source File: ezstickerbot.py    From ez-sticker-bot with MIT License 6 votes vote down vote up
def file_id_query_received(update: Update, context: CallbackContext):
    # get query
    query = update.inline_query
    user_id = query.from_user.id
    results = None

    try:
        file = bot.get_file(query.query)

        _id = uuid.uuid4()
        title = get_message(user_id, "your_sticker")
        desc = get_message(user_id, "forward_desc")
        caption = "@EzStickerBot"
        results = [InlineQueryResultCachedDocument(_id, title, file.file_id, description=desc, caption=caption)]

        query.answer(results=results, cache_time=5, is_personal=True)
    # if file_id wasn't found show share option
    except TelegramError:
        share_query_received(update, context) 
Example #6
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 #7
Source File: global_kick.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def gkick(bot: Bot, update: Update, args: List[str]):
    message = update.effective_message
    user_id = extract_user(message, args)
    try:
        user_chat = bot.get_chat(user_id)
    except BadRequest as excp:
        if excp.message in GKICK_ERRORS:
            pass
        else:
            message.reply_text("User cannot be Globally kicked because: {}".format(excp.message))
            return
    except TelegramError:
            pass

    if not user_id:
        message.reply_text("You do not seems to be referring to a user")
        return
    if int(user_id) in SUDO_USERS or int(user_id) in SUPPORT_USERS:
        message.reply_text("OHHH! Someone's trying to gkick a sudo/support user! *Grabs popcorn*")
        return
    if int(user_id) == OWNER_ID:
        message.reply_text("Wow! Someone's so noob that he want to gkick my owner! *Grabs Potato Chips*")
        return
    if int(user_id) == bot.id:
        message.reply_text("OHH... Let me kick myself.. No way... ")
        return
    chats = get_all_chats()
    message.reply_text("Globally kicking user @{}".format(user_chat.username))
    for chat in chats:
        try:
             bot.unban_chat_member(chat.chat_id, user_id)  # Unban_member = kick (and not ban)
        except BadRequest as excp:
            if excp.message in GKICK_ERRORS:
                pass
            else:
                message.reply_text("User cannot be Globally kicked because: {}".format(excp.message))
                return
        except TelegramError:
            pass 
Example #8
Source File: ezstickerbot.py    From ez-sticker-bot with MIT License 5 votes vote down vote up
def sticker_received(update: Update, context: CallbackContext):
    message = update.message
    user_id = message.from_user.id

    # check spam filter
    cooldown_info = user_on_cooldown(user_id)
    if cooldown_info[0]:
        minutes = int(config['spam_interval'] / 60)
        message_text = get_message(user_id, 'spam_limit_reached').format(config['spam_max'], minutes, cooldown_info[1],
                                                                         cooldown_info[2])
        message.reply_markdown(message_text)
        return

    # check if sticker is animated
    if message.sticker.is_animated:
        animated_sticker_received(update, context)
        return

    sticker_id = message.sticker.file_id

    # feedback to show bot is processing
    bot.send_chat_action(user_id, 'upload_document')

    try:
        download_path = download_file(sticker_id)

        image = Image.open(download_path)
        create_sticker_file(message, image, context)

        # delete local file
        os.remove(download_path)
    except Unauthorized:
        pass
    except TelegramError:
        message.reply_text(get_message(user_id, "send_timeout"))
    except FileNotFoundError:
        # if file does not exist ignore
        pass 
Example #9
Source File: misc.py    From tgbot with GNU General Public License v3.0 5 votes vote down vote up
def send_to_list(bot: Bot, send_to: list, message: str, markdown=False, html=False) -> None:
    if html and markdown:
        raise Exception("Can only send with either markdown or HTML!")
    for user_id in set(send_to):
        try:
            if markdown:
                bot.send_message(user_id, message, parse_mode=ParseMode.MARKDOWN)
            elif html:
                bot.send_message(user_id, message, parse_mode=ParseMode.HTML)
            else:
                bot.send_message(user_id, message)
        except TelegramError:
            pass  # ignore users who fail 
Example #10
Source File: __main__.py    From tgbot with GNU General Public License v3.0 5 votes vote down vote up
def error_callback(bot, update, error):
    try:
        raise error
    except Unauthorized:
        print("no nono1")
        print(error)
        # remove update.message.chat_id from conversation list
    except BadRequest:
        print("no nono2")
        print("BadRequest caught")
        print(error)

        # handle malformed requests - read more below!
    except TimedOut:
        print("no nono3")
        # handle slow connection problems
    except NetworkError:
        print("no nono4")
        # handle other connection problems
    except ChatMigrated as err:
        print("no nono5")
        print(err)
        # the chat_id of a group has changed, use e.new_chat_id instead
    except TelegramError:
        print(error)
        # handle all other telegram related errors 
Example #11
Source File: main.py    From simple-forwarder-bot with MIT License 5 votes vote down vote up
def unban_user(bot, update):
    global Blacklist, admin
    cmd = update.message.text
    user = update.message.from_user.id
    if user == admin:
        try:
            para = int(cmd.split()[1])
        except IndexError:
            bot.send_message(chat_id=user, text='请指定要封禁用户的ID号!')
        except ValueError:
            bot.send_message(chat_id=user, text='请输入合法的数字!')
        else:
            if para in Blacklist:
                try:
                    bot.send_message(
                        user,
                        '用户`' + str(para) + '`已经解除封禁',
                        parse_mode='Markdown')
                except TelegramError:
                    pass
                Blacklist.remove(para)
                write_config()
            else:
                bot.send_message(
                    user,
                    '用户`' + str(para) + '`并不在黑名单里!',
                    parse_mode='Markdown') 
Example #12
Source File: ezstickerbot.py    From ez-sticker-bot with MIT License 5 votes vote down vote up
def change_lang_callback(update: Update, context: CallbackContext):
    query = update.callback_query
    lang_code = query.data.split(':')[-1]
    user_id = str(query.from_user.id)

    global users
    users[user_id]['lang'] = lang_code

    # replace instances of $userid with username or name if no username
    message = get_message(user_id, "lang_set").split(' ')
    for i in range(len(message)):
        word = message[i]
        if word[0] == '$':
            try:
                _id = int(''.join(c for c in word if c.isdigit()))
                user = bot.get_chat(_id)
                message[i] = '<a href="tg://user?id={}">{}{}</a>'.format(_id, user.first_name,
                                                                         ' ' + user.last_name if user.last_name else '')
            except ValueError:
                message[i] = 'UNKNOWN_USER_ID'
                continue
            except TelegramError:
                message[i] = 'INVALID_USER_ID'
                continue
    message = ' '.join(message)

    # set icon_warned to false
    users[user_id]['icon_warned'] = False

    query.edit_message_text(text=message, reply_markup=None, parse_mode='HTML')
    query.answer() 
Example #13
Source File: __main__.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def error_callback(bot, update, error):
    try:
        raise error
    except Unauthorized:
        print("no nono1")
        print(error)
        # remove update.message.chat_id from conversation list
    except BadRequest:
        print("no nono2")
        print("BadRequest caught")
        print(error)

        # handle malformed requests - read more below!
    except TimedOut:
        print("no nono3")
        # handle slow connection problems
    except NetworkError:
        print("no nono4")
        # handle other connection problems
    except ChatMigrated as err:
        print("no nono5")
        print(err)
        # the chat_id of a group has changed, use e.new_chat_id instead
    except TelegramError:
        print(error)
        # handle all other telegram related errors 
Example #14
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def set_sticker_position_in_set(self, sticker, position, timeout=None, **kwargs):
        """Use this method to move a sticker in a set created by the bot to a specific position.

        Args:
            sticker (:obj:`str`): File identifier of the sticker.
            position (:obj:`int`): New sticker position in the set, zero-based.
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during
                creation of the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.

        Returns:
            :obj:`bool`: On success, ``True`` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/setStickerPositionInSet'.format(self.base_url)

        data = {'sticker': sticker, 'position': position}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #15
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def get_chat_member(self, chat_id, user_id, timeout=None, **kwargs):
        """Use this method to get information about a member of a chat.

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            user_id (:obj:`int`): Unique identifier of the target user.
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.

        Returns:
            :class:`telegram.ChatMember`

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/getChatMember'.format(self.base_url)

        data = {'chat_id': chat_id, 'user_id': user_id}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return ChatMember.de_json(result, self) 
Example #16
Source File: ezstickerbot.py    From ez-sticker-bot with MIT License 5 votes vote down vote up
def animated_sticker_received(update: Update, context: CallbackContext):
    message = update.message
    user_id = message.from_user.id

    # feedback to show bot is processing
    bot.send_chat_action(user_id, 'upload_document')

    sticker_id = message.sticker.file_id

    # download sticker and send as document
    try:
        download_path = download_file(sticker_id)

        document = open(download_path, 'rb')
        sticker_message = message.reply_document(document=document)
        sent_message = sticker_message.reply_markdown(get_message(user_id, "forward_animated_sticker"), quote=True)

        # add a keyboard with a forward button to the document
        file_id = sticker_message.sticker.file_id
        markup = InlineKeyboardMarkup(
            [[InlineKeyboardButton(get_message(user_id, "forward"), switch_inline_query=file_id)]])
        sent_message.edit_reply_markup(reply_markup=markup)

        # delete local file
        os.remove(download_path)
    except TelegramError:
        message.reply_text(get_message(user_id, "send_timeout"))
    except FileNotFoundError:
        # if file does not exist ignore
        pass

    # record use in spam filter
    record_use(user_id, context)

    # increase total uses count by one
    global config
    config['uses'] += 1
    global users
    users[str(user_id)]['uses'] += 1

    donate_suggest(user_id) 
Example #17
Source File: misc.py    From Marie-2.0-English with GNU General Public License v3.0 5 votes vote down vote up
def send_to_list(bot: Bot, send_to: list, message: str, markdown=False, html=False) -> None:
    if html and markdown:
        raise Exception("Can only send with either markdown or HTML!")
    for user_id in set(send_to):
        try:
            if markdown:
                bot.send_message(user_id, message, parse_mode=ParseMode.MARKDOWN)
            elif html:
                bot.send_message(user_id, message, parse_mode=ParseMode.HTML)
            else:
                bot.send_message(user_id, message)
        except TelegramError:
            pass  # ignore users who fail 
Example #18
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def get_sticker_set(self, name, timeout=None, **kwargs):
        """Use this method to get a sticker set.

        Args:
            name (:obj:`str`): Short name of the sticker set that is used in t.me/addstickers/
                URLs (e.g., animals)
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during
                creation of the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.

        Returns:
            :class:`telegram.StickerSet`

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/getStickerSet'.format(self.base_url)

        data = {'name': name}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return StickerSet.de_json(result, self) 
Example #19
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def unpin_chat_message(self, chat_id, timeout=None, **kwargs):
        """
        Use this method to unpin a message in a supergroup. The bot must be an administrator in the
        chat for this to work and must have the appropriate admin rights.

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments

        Returns:
            :obj:`bool`: Returns ``True`` on success.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/unpinChatMessage'.format(self.base_url)

        data = {'chat_id': chat_id}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #20
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def pin_chat_message(self, chat_id, message_id, disable_notification=None, timeout=None,
                         **kwargs):
        """
        Use this method to pin a message in a supergroup. The bot must be an administrator in the
        chat for this to work and must have the appropriate admin rights.

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            message_id (:obj:`int`): Identifier of a message to pin.
            disable_notification (:obj:`bool`, optional): Pass True, if it is not necessary to send
                a notification to all group members about the new pinned message.
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments

        Returns:
            :obj:`bool`: Returns ``True`` on success.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/pinChatMessage'.format(self.base_url)

        data = {'chat_id': chat_id, 'message_id': message_id}

        if disable_notification is not None:
            data['disable_notification'] = disable_notification
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #21
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def set_chat_title(self, chat_id, title, timeout=None, **kwargs):
        """
        Use this method to change the title of a chat. Titles can't be changed for private chats.
        The bot must be an administrator in the chat for this to work and must have the appropriate
        admin rights.

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            title (:obj:`str`): New chat title, 1-255 characters.
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments

        Note:
            In regular groups (non-supergroups), this method will only work if the
            'All Members Are Admins' setting is off in the target group.

        Returns:
            :obj:`bool`: Returns ``True`` on success.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/setChatTitle'.format(self.base_url)

        data = {'chat_id': chat_id, 'title': title}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #22
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def delete_chat_photo(self, chat_id, timeout=None, **kwargs):
        """
        Use this method to delete a chat photo. Photos can't be changed for private chats. The bot
        must be an administrator in the chat for this to work and must have the appropriate admin
        rights.

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments

        Note:
            In regular groups (non-supergroups), this method will only work if the
            'All Members Are Admins' setting is off in the target group.

        Returns:
            :obj:`bool`: Returns ``True`` on success.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/deleteChatPhoto'.format(self.base_url)

        data = {'chat_id': chat_id}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #23
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def set_chat_photo(self, chat_id, photo, timeout=None, **kwargs):
        """Use this method to set a new profile photo for the chat.

        Photos can't be changed for private chats. The bot must be an administrator in the chat
        for this to work and must have the appropriate admin rights.

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            photo (`telegram.InputFile`): New chat photo.
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments

        Note:
            In regular groups (non-supergroups), this method will only work if the
            'All Members Are Admins' setting is off in the target group.

        Returns:
            :obj:`bool`: Returns True on success.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/setChatPhoto'.format(self.base_url)

        data = {'chat_id': chat_id, 'photo': photo}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #24
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def export_chat_invite_link(self, chat_id, timeout=None, **kwargs):
        """
        Use this method to export an invite link to a supergroup or a channel. The bot must be an
        administrator in the chat for this to work and must have the appropriate admin rights.

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments

        Returns:
            :obj:`str`: Exported invite link on success.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/exportChatInviteLink'.format(self.base_url)

        data = {'chat_id': chat_id}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #25
Source File: __main__.py    From SkittBot with GNU General Public License v3.0 5 votes vote down vote up
def error_callback(bot, update, error):
    try:
        raise error
    except Unauthorized:
        print("no nono1")
        print(error)
        # remove update.message.chat_id from conversation list
    except BadRequest:
        print("no nono2")
        print("BadRequest caught")
        print(error)

        # handle malformed requests - read more below!
    except TimedOut:
        print("no nono3")
        # handle slow connection problems
    except NetworkError:
        print("no nono4")
        # handle other connection problems
    except ChatMigrated as err:
        print("no nono5")
        print(err)
        # the chat_id of a group has changed, use e.new_chat_id instead
    except TelegramError:
        print(error)
        # handle all other telegram related errors 
Example #26
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def get_chat_members_count(self, chat_id, timeout=None, **kwargs):
        """Use this method to get the number of members in a chat

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.

        Returns:
            int: Number of members in the chat.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/getChatMembersCount'.format(self.base_url)

        data = {'chat_id': chat_id}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #27
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def get_chat(self, chat_id, timeout=None, **kwargs):
        """
        Use this method to get up to date information about the chat (current name of the user for
        one-on-one conversations, current username of a user, group or channel, etc.).

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.

        Returns:
            :class:`telegram.Chat`

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/getChat'.format(self.base_url)

        data = {'chat_id': chat_id}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return Chat.de_json(result, self) 
Example #28
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def leave_chat(self, chat_id, timeout=None, **kwargs):
        """Use this method for your bot to leave a group, supergroup or channel.

        Args:
            chat_id (:obj:`int` | :obj:`str`): Unique identifier for the target chat or username
                of the target`channel (in the format @channelusername).
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during creation of
                the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.

        Returns:
            :obj:`bool` On success, ``True`` is returned.

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/leaveChat'.format(self.base_url)

        data = {'chat_id': chat_id}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return result 
Example #29
Source File: ezstickerbot.py    From ez-sticker-bot with MIT License 5 votes vote down vote up
def broadcast_thread(context: CallbackContext):
    # check that message was included with the job obj
    if context.job.context is None:
        print("Broadcast thread created without message stored in job context")
        return

    global config
    index = 0
    for user_id in list(users):
        # check if user is opted in
        opt_in = get_user_config(user_id, "opt_in")

        # catch any errors thrown by users who have stopped bot
        try:
            if opt_in and not config['override_opt_out']:
                bot.send_message(chat_id=int(user_id), text=context.job.context, parse_mode='HTML',
                                 disable_web_page_preview=True)
                # send opt out message
                if config['send_opt_out_message']:
                    bot.send_message(chat_id=int(user_id), text=get_message(user_id, "opt_out_info"))
        except Unauthorized:
            pass
        except TelegramError as e:
            logger.warning("Error '{}' when broadcasting message to {}".format(e.message, user_id))

        index += 1
        if index >= config['broadcast_batch_size']:
            time.sleep(config['broadcast_batch_interval'])
            index = 0 
Example #30
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def upload_sticker_file(self, user_id, png_sticker, timeout=None, **kwargs):
        """
        Use this method to upload a .png file with a sticker for later use in
        :attr:`create_new_sticker_set` and :attr:`add_sticker_to_set` methods (can be used multiple
        times).

        Note:
            The png_sticker argument can be either a file_id, an URL or a file from disk
            ``open(filename, 'rb')``

        Args:
            user_id (:obj:`int`): User identifier of sticker file owner.
            png_sticker (:obj:`str` | `filelike object`): Png image with the sticker,
                must be up to 512 kilobytes in size, dimensions must not exceed 512px,
                and either width or height must be exactly 512px.
            timeout (:obj:`int` | :obj:`float`, optional): If this value is specified, use it as
                the read timeout from the server (instead of the one specified during
                creation of the connection pool).
            **kwargs (:obj:`dict`): Arbitrary keyword arguments.

        Returns:
            :class:`telegram.File`: The uploaded File

        Raises:
            :class:`telegram.TelegramError`

        """
        url = '{0}/uploadStickerFile'.format(self.base_url)

        data = {'user_id': user_id, 'png_sticker': png_sticker}
        data.update(kwargs)

        result = self._request.post(url, data, timeout=timeout)

        return File.de_json(result, self)