Example #1
0
def test_parse_illegal_callback_data():
    """
    Clients can send arbitrary bytes in callback data.
    Make sure the correct error is raised in this case.
    """
    server_response = b'{"invalid utf-8": "\x80"}'

    with pytest.raises(TelegramError, match='Server response could not be decoded using UTF-8'):
        Request._parse(server_response)
    def __init__(self, token=None, base_url=None, workers=4, bot=None):
        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        if bot is not None:
            self.bot = bot
        else:
            # we need a connection pool the size of:
            # * for each of the workers
            # * 1 for Dispatcher
            # * 1 for polling Updater (even if webhook is used, we can spare a connection)
            # * 1 for JobQueue
            # * 1 for main thread
            self._request = Request(con_pool_size=workers + 4)
            self.bot = Bot(token, base_url, request=self._request)
        self.update_queue = Queue()
        self.job_queue = JobQueue(self.bot)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(
            self.bot,
            self.update_queue,
            job_queue=self.job_queue,
            workers=workers,
            exception_event=self.__exception_event)
        self.last_update_id = 0
        self.logger = logging.getLogger(__name__)
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []
        """:type: list[Thread]"""
Example #3
0
    def __init__(self,
                 token=None,
                 base_url=None,
                 workers=4,
                 bot=None,
                 user_sig_handler=None,
                 request_kwargs=None):

        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        self.logger = logging.getLogger(__name__)

        con_pool_size = workers + 4

        if bot is not None:
            self.bot = bot
            if bot.request.con_pool_size < con_pool_size:
                self.logger.warning(
                    'Connection pool of Request object is smaller than optimal value (%s)',
                    con_pool_size)
        else:
            # we need a connection pool the size of:
            # * for each of the workers
            # * 1 for Dispatcher
            # * 1 for polling Updater (even if webhook is used, we can spare a connection)
            # * 1 for JobQueue
            # * 1 for main thread
            if request_kwargs is None:
                request_kwargs = {}
            if 'con_pool_size' not in request_kwargs:
                request_kwargs['con_pool_size'] = con_pool_size
            self._request = Request(**request_kwargs)
            self.bot = Bot(token, base_url, request=self._request)
        self.user_sig_handler = user_sig_handler
        self.update_queue = Queue()
        self.job_queue = JobQueue(self.bot)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(
            self.bot,
            self.update_queue,
            job_queue=self.job_queue,
            workers=workers,
            exception_event=self.__exception_event)
        self.last_update_id = 0
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []
Example #4
0
def main():
    token = os.environ['TG_TOKEN']

    req = Request(
        connect_timeout=0.5,
        read_timeout=1.0,
    )
    bot = Bot(
        token=token,
        request=req,
        base_url=TG_API_URL,
    )
    updater = Updater(
        bot=bot,
        use_context=True,
    )
    print('Бот запускается...')

    start_handler = CommandHandler('start', do_start)
    go_main_handler = MessageHandler(Filters.regex('^(На главную📌)$'),
                                     btn_go_main)
    contacts_handler = MessageHandler(Filters.regex('^(Адрес и контакты👤)$'),
                                      btn_adress)
    conditions_handler = MessageHandler(
        Filters.regex('^(Условия оплаты💳 и получения📦)$'), btn_conditions)
    links_handler = MessageHandler(
        Filters.regex('^(Наша группа в 𝕍𝕂 и профиль в 𝕀𝕟𝕤𝕥𝕒𝕘𝕣𝕒𝕞)$'), btn_links)
    feedback_handler = MessageHandler(
        Filters.regex('^(О нас и обратная связь✉)$'), feedback)
    goods_handler = MessageHandler(Filters.regex('^(Товары🎁)$'), goods)
    back_to_goods_handler = MessageHandler(Filters.regex('^(Назад🔙)$'), goods)

    goods_1_handler = MessageHandler(Filters.regex('^(Сувениры🔮)$'),
                                     goods_suveniry)
    goods_2_handler = MessageHandler(Filters.regex('^(Текстиль🎀)$'),
                                     goods_textil)
    goods_3_handler = MessageHandler(Filters.regex('^(Мужская одежда👕)$'),
                                     goods_muzhskaya_odezhda)
    goods_4_handler = MessageHandler(Filters.regex('^(Женская одежда👚)$'),
                                     goods_zhenskaya_odezhda)
    goods_5_handler = MessageHandler(Filters.regex('^(Детская одежда🧣)$'),
                                     goods_detskaya_odezhda)
    goods_6_handler = MessageHandler(
        Filters.regex('^(Аксессуары для телефона📲)$'), goods_aksessuary)

    do_feedback_handler = MessageHandler(Filters.all, do_feedback)

    dp = updater.dispatcher.add_handler

    dp(start_handler)
    dp(go_main_handler)
    dp(contacts_handler)
    dp(conditions_handler)
    dp(links_handler)
    dp(feedback_handler)
    dp(goods_handler)
    dp(back_to_goods_handler)

    dp(goods_1_handler)
    dp(goods_2_handler)
    dp(goods_3_handler)
    dp(goods_4_handler)
    dp(goods_5_handler)
    dp(goods_6_handler)

    dp(do_feedback_handler)

    updater.start_polling()
    print('Бот запущен!')
    updater.idle()
Example #5
0
    def __init__(
        self,
        token: str = None,
        base_url: str = None,
        workers: int = 4,
        bot: Bot = None,
        private_key: bytes = None,
        private_key_password: bytes = None,
        user_sig_handler: Callable = None,
        request_kwargs: Dict[str, Any] = None,
        persistence: 'BasePersistence' = None,
        defaults: 'Defaults' = None,
        use_context: bool = True,
        dispatcher: Dispatcher = None,
        base_file_url: str = None,
    ):

        if defaults and bot:
            warnings.warn(
                'Passing defaults to an Updater has no effect when a Bot is passed '
                'as well. Pass them to the Bot instead.',
                TelegramDeprecationWarning,
                stacklevel=2,
            )

        if dispatcher is None:
            if (token is None) and (bot is None):
                raise ValueError('`token` or `bot` must be passed')
            if (token is not None) and (bot is not None):
                raise ValueError('`token` and `bot` are mutually exclusive')
            if (private_key is not None) and (bot is not None):
                raise ValueError(
                    '`bot` and `private_key` are mutually exclusive')
        else:
            if bot is not None:
                raise ValueError(
                    '`dispatcher` and `bot` are mutually exclusive')
            if persistence is not None:
                raise ValueError(
                    '`dispatcher` and `persistence` are mutually exclusive')
            if workers is not None:
                raise ValueError(
                    '`dispatcher` and `workers` are mutually exclusive')
            if use_context != dispatcher.use_context:
                raise ValueError(
                    '`dispatcher` and `use_context` are mutually exclusive')

        self.logger = logging.getLogger(__name__)

        if dispatcher is None:
            con_pool_size = workers + 4

            if bot is not None:
                self.bot = bot
                if bot.request.con_pool_size < con_pool_size:
                    self.logger.warning(
                        'Connection pool of Request object is smaller than optimal value (%s)',
                        con_pool_size,
                    )
            else:
                # we need a connection pool the size of:
                # * for each of the workers
                # * 1 for Dispatcher
                # * 1 for polling Updater (even if webhook is used, we can spare a connection)
                # * 1 for JobQueue
                # * 1 for main thread
                if request_kwargs is None:
                    request_kwargs = {}
                if 'con_pool_size' not in request_kwargs:
                    request_kwargs['con_pool_size'] = con_pool_size
                self._request = Request(**request_kwargs)
                self.bot = Bot(
                    token,  # type: ignore[arg-type]
                    base_url,
                    base_file_url=base_file_url,
                    request=self._request,
                    private_key=private_key,
                    private_key_password=private_key_password,
                    defaults=defaults,
                )
            self.update_queue: Queue = Queue()
            self.job_queue = JobQueue()
            self.__exception_event = Event()
            self.persistence = persistence
            self.dispatcher = Dispatcher(
                self.bot,
                self.update_queue,
                job_queue=self.job_queue,
                workers=workers,
                exception_event=self.__exception_event,
                persistence=persistence,
                use_context=use_context,
            )
            self.job_queue.set_dispatcher(self.dispatcher)
        else:
            con_pool_size = dispatcher.workers + 4

            self.bot = dispatcher.bot
            if self.bot.request.con_pool_size < con_pool_size:
                self.logger.warning(
                    'Connection pool of Request object is smaller than optimal value (%s)',
                    con_pool_size,
                )
            self.update_queue = dispatcher.update_queue
            self.__exception_event = dispatcher.exception_event
            self.persistence = dispatcher.persistence
            self.job_queue = dispatcher.job_queue
            self.dispatcher = dispatcher

        self.user_sig_handler = user_sig_handler
        self.last_update_id = 0
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads: List[Thread] = []
Example #6
0
def get_bot():
    # Default size from the library, 4 workers + 4 additional
    request = Request(con_pool_size=8)
    return Bot(token=os.getenv("TG_TOKEN"), request=request)
Example #7
0
class Updater(object):
    """
    This class, which employs the :class:`telegram.ext.Dispatcher`, provides a frontend to
    :class:`telegram.Bot` to the programmer, so they can focus on coding the bot. Its purpose is to
    receive the updates from Telegram and to deliver them to said dispatcher. It also runs in a
    separate thread, so the user can interact with the bot, for example on the command line. The
    dispatcher supports handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types. The updater can be started as a polling service or, for
    production, use a webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:
        bot (:class:`telegram.Bot`): The bot used with this Updater.
        user_sig_handler (:obj:`signal`): signals the updater will respond to.
        update_queue (:obj:`Queue`): Queue for the updates.
        job_queue (:class:`telegram.ext.JobQueue`): Jobqueue for the updater.
        dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that handles the updates and
            dispatches them to the handlers.
        running (:obj:`bool`): Indicates if the updater is running.
        persistence (:class:`telegram.ext.BasePersistence`): Optional. The persistence class to
            store data that should be persistent over restarts.
        use_context (:obj:`bool`, optional): ``True`` if using context based callbacks.

    Args:
        token (:obj:`str`, optional): The bot's token given by the @BotFather.
        base_url (:obj:`str`, optional): Base_url for the bot.
        base_file_url (:obj:`str`, optional): Base_file_url for the bot.
        workers (:obj:`int`, optional): Amount of threads in the thread pool for functions
            decorated with ``@run_async`` (ignored if `dispatcher` argument is used).
        bot (:class:`telegram.Bot`, optional): A pre-initialized bot instance (ignored if
            `dispatcher` argument is used). If a pre-initialized bot is used, it is the user's
            responsibility to create it using a `Request` instance with a large enough connection
            pool.
        dispatcher (:class:`telegram.ext.Dispatcher`, optional): A pre-initialized dispatcher
            instance. If a pre-initialized dispatcher is used, it is the user's responsibility to
            create it with proper arguments.
        private_key (:obj:`bytes`, optional): Private key for decryption of telegram passport data.
        private_key_password (:obj:`bytes`, optional): Password for above private key.
        user_sig_handler (:obj:`function`, optional): Takes ``signum, frame`` as positional
            arguments. This will be called when a signal is received, defaults are (SIGINT,
            SIGTERM, SIGABRT) setable with :attr:`idle`.
        request_kwargs (:obj:`dict`, optional): Keyword args to control the creation of a
            `telegram.utils.request.Request` object (ignored if `bot` or `dispatcher` argument is
            used). The request_kwargs are very useful for the advanced users who would like to
            control the default timeouts and/or control the proxy used for http communication.
        use_context (:obj:`bool`, optional): If set to ``True`` Use the context based callback API
            (ignored if `dispatcher` argument is used). During the deprecation period of the old
            API the default is ``False``. **New users**: set this to ``True``.
        persistence (:class:`telegram.ext.BasePersistence`, optional): The persistence class to
            store data that should be persistent over restarts (ignored if `dispatcher` argument is
            used).

    Note:
        You must supply either a :attr:`bot` or a :attr:`token` argument.

    Raises:
        ValueError: If both :attr:`token` and :attr:`bot` are passed or none of them.

    """

    _request = None

    def __init__(self,
                 token=None,
                 base_url=None,
                 workers=4,
                 bot=None,
                 private_key=None,
                 private_key_password=None,
                 user_sig_handler=None,
                 request_kwargs=None,
                 persistence=None,
                 use_context=False,
                 dispatcher=None,
                 base_file_url=None):

        if dispatcher is None:
            if (token is None) and (bot is None):
                raise ValueError('`token` or `bot` must be passed')
            if (token is not None) and (bot is not None):
                raise ValueError('`token` and `bot` are mutually exclusive')
            if (private_key is not None) and (bot is not None):
                raise ValueError('`bot` and `private_key` are mutually exclusive')
        else:
            if bot is not None:
                raise ValueError('`dispatcher` and `bot` are mutually exclusive')
            if persistence is not None:
                raise ValueError('`dispatcher` and `persistence` are mutually exclusive')
            if workers is not None:
                raise ValueError('`dispatcher` and `workers` are mutually exclusive')
            if use_context != dispatcher.use_context:
                raise ValueError('`dispatcher` and `use_context` are mutually exclusive')

        self.logger = logging.getLogger(__name__)

        if dispatcher is None:
            con_pool_size = workers + 4

            if bot is not None:
                self.bot = bot
                if bot.request.con_pool_size < con_pool_size:
                    self.logger.warning(
                        'Connection pool of Request object is smaller than optimal value (%s)',
                        con_pool_size)
            else:
                # we need a connection pool the size of:
                # * for each of the workers
                # * 1 for Dispatcher
                # * 1 for polling Updater (even if webhook is used, we can spare a connection)
                # * 1 for JobQueue
                # * 1 for main thread
                if request_kwargs is None:
                    request_kwargs = {}
                if 'con_pool_size' not in request_kwargs:
                    request_kwargs['con_pool_size'] = con_pool_size
                self._request = Request(**request_kwargs)
                self.bot = Bot(token,
                               base_url,
                               base_file_url=base_file_url,
                               request=self._request,
                               private_key=private_key,
                               private_key_password=private_key_password)
            self.update_queue = Queue()
            self.job_queue = JobQueue()
            self.__exception_event = Event()
            self.persistence = persistence
            self.dispatcher = Dispatcher(self.bot,
                                         self.update_queue,
                                         job_queue=self.job_queue,
                                         workers=workers,
                                         exception_event=self.__exception_event,
                                         persistence=persistence,
                                         use_context=use_context)
            self.job_queue.set_dispatcher(self.dispatcher)
        else:
            con_pool_size = dispatcher.workers + 4

            self.bot = dispatcher.bot
            if self.bot.request.con_pool_size < con_pool_size:
                self.logger.warning(
                    'Connection pool of Request object is smaller than optimal value (%s)',
                    con_pool_size)
            self.update_queue = dispatcher.update_queue
            self.__exception_event = dispatcher.exception_event
            self.persistence = dispatcher.persistence
            self.job_queue = dispatcher.job_queue
            self.dispatcher = dispatcher

        self.user_sig_handler = user_sig_handler
        self.last_update_id = 0
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper,
                     name="Bot:{}:{}".format(self.bot.id, name),
                     args=(target,) + args,
                     kwargs=kwargs)
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target, *args, **kwargs):
        thr_name = current_thread().name
        self.logger.debug('{0} - started'.format(thr_name))
        try:
            target(*args, **kwargs)
        except Exception:
            self.__exception_event.set()
            self.logger.exception('unhandled exception in %s', thr_name)
            raise
        self.logger.debug('{0} - ended'.format(thr_name))

    def start_polling(self,
                      poll_interval=0.0,
                      timeout=10,
                      clean=False,
                      bootstrap_retries=-1,
                      read_latency=2.,
                      allowed_updates=None):
        """Starts polling updates from Telegram.

        Args:
            poll_interval (:obj:`float`, optional): Time to wait between polling updates from
                Telegram in seconds. Default is 0.0.
            timeout (:obj:`float`, optional): Passed to :attr:`telegram.Bot.get_updates`.
            clean (:obj:`bool`, optional): Whether to clean any pending updates on Telegram servers
                before actually starting to poll. Default is False.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                `Updater` will retry on failures on the Telegram server.

                * < 0 - retry indefinitely (default)
                *   0 - no retries
                * > 0 - retry up to X times

            allowed_updates (List[:obj:`str`], optional): Passed to
                :attr:`telegram.Bot.get_updates`.
            read_latency (:obj:`float` | :obj:`int`, optional): Grace time in seconds for receiving
                the reply from server. Will be added to the `timeout` value and used as the read
                timeout from server (Default: 2).

        Returns:
            :obj:`Queue`: The update queue that can be filled from the main thread.

        """
        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self.job_queue.start()
                dispatcher_ready = Event()
                self._init_thread(self.dispatcher.start, "dispatcher", ready=dispatcher_ready)
                self._init_thread(self._start_polling, "updater", poll_interval, timeout,
                                  read_latency, bootstrap_retries, clean, allowed_updates)

                dispatcher_ready.wait()

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def start_webhook(self,
                      listen='127.0.0.1',
                      port=80,
                      url_path='',
                      cert=None,
                      key=None,
                      clean=False,
                      bootstrap_retries=0,
                      webhook_url=None,
                      allowed_updates=None):
        """
        Starts a small http server to listen for updates via webhook. If cert
        and key are not provided, the webhook will be started directly on
        http://listen:port/url_path, so SSL can be handled by another
        application. Else, the webhook will be started on
        https://listen:port/url_path

        Args:
            listen (:obj:`str`, optional): IP-Address to listen on. Default ``127.0.0.1``.
            port (:obj:`int`, optional): Port the bot should be listening on. Default ``80``.
            url_path (:obj:`str`, optional): Path inside url.
            cert (:obj:`str`, optional): Path to the SSL certificate file.
            key (:obj:`str`, optional): Path to the SSL key file.
            clean (:obj:`bool`, optional): Whether to clean any pending updates on Telegram servers
                before actually starting the webhook. Default is ``False``.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                `Updater` will retry on failures on the Telegram server.

                * < 0 - retry indefinitely (default)
                *   0 - no retries
                * > 0 - retry up to X times

            webhook_url (:obj:`str`, optional): Explicitly specify the webhook url. Useful behind
                NAT, reverse proxy, etc. Default is derived from `listen`, `port` & `url_path`.
            allowed_updates (List[:obj:`str`], optional): Passed to
                :attr:`telegram.Bot.set_webhook`.

        Returns:
            :obj:`Queue`: The update queue that can be filled from the main thread.

        """
        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self.job_queue.start()
                self._init_thread(self.dispatcher.start, "dispatcher"),
                self._init_thread(self._start_webhook, "updater", listen, port, url_path, cert,
                                  key, bootstrap_retries, clean, webhook_url, allowed_updates)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    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.

        self.logger.debug('Updater thread started (polling)')

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

        self.logger.debug('Bootstrap done')

        def polling_action_cb():
            updates = self.bot.get_updates(self.last_update_id,
                                           timeout=timeout,
                                           read_latency=read_latency,
                                           allowed_updates=allowed_updates)

            if updates:
                if not self.running:
                    self.logger.debug('Updates ignored and will be pulled again on restart')
                else:
                    for update in updates:
                        self.update_queue.put(update)
                    self.last_update_id = updates[-1].update_id + 1

            return True

        def polling_onerr_cb(exc):
            # Put the error into the update queue and let the Dispatcher
            # broadcast it
            self.update_queue.put(exc)

        self._network_loop_retry(polling_action_cb, polling_onerr_cb, 'getting Updates',
                                 poll_interval)

    def _network_loop_retry(self, action_cb, onerr_cb, description, interval):
        """Perform a loop calling `action_cb`, retrying after network errors.

        Stop condition for loop: `self.running` evaluates False or return value of `action_cb`
        evaluates False.

        Args:
            action_cb (:obj:`callable`): Network oriented callback function to call.
            onerr_cb (:obj:`callable`): Callback to call when TelegramError is caught. Receives the
                exception object as a parameter.
            description (:obj:`str`): Description text to use for logs and exception raised.
            interval (:obj:`float` | :obj:`int`): Interval to sleep between each call to
                `action_cb`.

        """
        self.logger.debug('Start network loop retry %s', description)
        cur_interval = interval
        while self.running:
            try:
                if not action_cb():
                    break
            except RetryAfter as e:
                self.logger.info('%s', e)
                cur_interval = 0.5 + e.retry_after
            except TimedOut as toe:
                self.logger.debug('Timed out %s: %s', description, toe)
                # If failure is due to timeout, we should retry asap.
                cur_interval = 0
            except InvalidToken as pex:
                self.logger.error('Invalid token; aborting')
                raise pex
            except TelegramError as te:
                self.logger.error('Error while %s: %s', description, te)
                onerr_cb(te)
                cur_interval = self._increase_poll_interval(cur_interval)
            else:
                cur_interval = interval

            if cur_interval:
                sleep(cur_interval)

    @staticmethod
    def _increase_poll_interval(current_interval):
        # increase waiting times on subsequent errors up to 30secs
        if current_interval == 0:
            current_interval = 1
        elif current_interval < 30:
            current_interval += current_interval / 2
        elif current_interval > 30:
            current_interval = 30
        return current_interval

    def _start_webhook(self, listen, port, url_path, cert, key, bootstrap_retries, clean,
                       webhook_url, allowed_updates):
        self.logger.debug('Updater thread started (webhook)')
        use_ssl = cert is not None and key is not None
        if not url_path.startswith('/'):
            url_path = '/{0}'.format(url_path)

        # Create Tornado app instance
        app = WebhookAppClass(url_path, self.bot, self.update_queue)

        # Form SSL Context
        # An SSLError is raised if the private key does not match with the certificate
        if use_ssl:
            try:
                ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
                ssl_ctx.load_cert_chain(cert, key)
            except ssl.SSLError:
                raise TelegramError('Invalid SSL Certificate')
        else:
            ssl_ctx = None

        # Create and start server
        self.httpd = WebhookServer(listen, port, app, ssl_ctx)

        if use_ssl:
            # DO NOT CHANGE: Only set webhook if SSL is handled by library
            if not webhook_url:
                webhook_url = self._gen_webhook_url(listen, port, url_path)

            self._bootstrap(max_retries=bootstrap_retries,
                            clean=clean,
                            webhook_url=webhook_url,
                            cert=open(cert, 'rb'),
                            allowed_updates=allowed_updates)
        elif clean:
            self.logger.warning("cleaning updates is not supported if "
                                "SSL-termination happens elsewhere; skipping")

        self.httpd.serve_forever()

    @staticmethod
    def _gen_webhook_url(listen, port, url_path):
        return 'https://{listen}:{port}{path}'.format(listen=listen, port=port, path=url_path)

    def _bootstrap(self,
                   max_retries,
                   clean,
                   webhook_url,
                   allowed_updates,
                   cert=None,
                   bootstrap_interval=5):
        retries = [0]

        def bootstrap_del_webhook():
            self.bot.delete_webhook()
            return False

        def bootstrap_clean_updates():
            self.logger.debug('Cleaning updates from Telegram server')
            updates = self.bot.get_updates()
            while updates:
                updates = self.bot.get_updates(updates[-1].update_id + 1)
            return False

        def bootstrap_set_webhook():
            self.bot.set_webhook(url=webhook_url,
                                 certificate=cert,
                                 allowed_updates=allowed_updates)
            return False

        def bootstrap_onerr_cb(exc):
            if not isinstance(exc, Unauthorized) and (max_retries < 0 or retries[0] < max_retries):
                retries[0] += 1
                self.logger.warning('Failed bootstrap phase; try=%s max_retries=%s', retries[0],
                                    max_retries)
            else:
                self.logger.error('Failed bootstrap phase after %s retries (%s)', retries[0], exc)
                raise exc

        # Cleaning pending messages is done by polling for them - so we need to delete webhook if
        # one is configured.
        # We also take this chance to delete pre-configured webhook if this is a polling Updater.
        # NOTE: We don't know ahead if a webhook is configured, so we just delete.
        if clean or not webhook_url:
            self._network_loop_retry(bootstrap_del_webhook, bootstrap_onerr_cb,
                                     'bootstrap del webhook', bootstrap_interval)
            retries[0] = 0

        # Clean pending messages, if requested.
        if clean:
            self._network_loop_retry(bootstrap_clean_updates, bootstrap_onerr_cb,
                                     'bootstrap clean updates', bootstrap_interval)
            retries[0] = 0
            sleep(1)

        # Restore/set webhook settings, if needed. Again, we don't know ahead if a webhook is set,
        # so we set it anyhow.
        if webhook_url:
            self._network_loop_retry(bootstrap_set_webhook, bootstrap_onerr_cb,
                                     'bootstrap set webhook', bootstrap_interval)

    def stop(self):
        """Stops the polling/webhook thread, the dispatcher and the job queue."""

        self.job_queue.stop()
        with self.__lock:
            if self.running or self.dispatcher.has_running_threads:
                self.logger.debug('Stopping Updater and Dispatcher...')

                self.running = False

                self._stop_httpd()
                self._stop_dispatcher()
                self._join_threads()

                # Stop the Request instance only if it was created by the Updater
                if self._request:
                    self._request.stop()

    def _stop_httpd(self):
        if self.httpd:
            self.logger.debug('Waiting for current webhook connection to be '
                              'closed... Send a Telegram message to the bot to exit '
                              'immediately.')
            self.httpd.shutdown()
            self.httpd = None

    def _stop_dispatcher(self):
        self.logger.debug('Requesting Dispatcher to stop...')
        self.dispatcher.stop()

    def _join_threads(self):
        for thr in self.__threads:
            self.logger.debug('Waiting for {0} thread to end'.format(thr.name))
            thr.join()
            self.logger.debug('{0} thread has ended'.format(thr.name))
        self.__threads = []

    def signal_handler(self, signum, frame):
        self.is_idle = False
        if self.running:
            self.logger.info('Received signal {} ({}), stopping...'.format(
                signum, get_signal_name(signum)))
            if self.persistence:
                # Update user_data and chat_data before flushing
                self.dispatcher.update_persistence()
                self.persistence.flush()
            self.stop()
            if self.user_sig_handler:
                self.user_sig_handler(signum, frame)
        else:
            self.logger.warning('Exiting immediately!')
            import os
            os._exit(1)

    def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
        """Blocks until one of the signals are received and stops the updater.

        Args:
            stop_signals (:obj:`iterable`): Iterable containing signals from the signal module that
                should be subscribed to. Updater.stop() will be called on receiving one of those
                signals. Defaults to (``SIGINT``, ``SIGTERM``, ``SIGABRT``).

        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
Example #8
0
    raise


@send_typing_action
def start(update: Update, context):
    """ /start command handler """
    context.bot.send_message(chat_id=update.effective_chat.id,
                             text="Hello there",
                             isgroup=False)


mq = MessageQueue(all_burst_limit=29,
                  all_time_limit_ms=1020,
                  group_burst_limit=10,
                  group_time_limit_ms=40000)
request = Request(con_pool_size=1)
bot_worker = MQBot(Config.TOKEN, request=request, mqueue=mq)
updater = Updater(bot=bot_worker, use_context=True)
dispatcher = updater.dispatcher

dispatcher.add_handler(CommandHandler('start', start))
dispatcher.add_error_handler(error_callback)


def run():
    db_handle.start()
    updater.start_polling()
    updater.idle()


def stop():
Example #9
0
def main():

    init_message_config = f"Booting up using {os.environ.get('PPB_ENV')} version"
    logger.info(init_message_config)

    SearchConfigs.init_data()

    client = SpreakerAPIClient(config["SECRET"].get("api_token"))
    power_pizza = Show(config["POWER_PIZZA"].get("SHOW_ID"))

    TOKEN_BOT = config["SECRET"].get("bot_token")
    q = mq.MessageQueue(all_burst_limit=29, all_time_limit_ms=1017)
    request = Request(con_pool_size=8)
    testbot = MQBot(TOKEN_BOT, request=request, mqueue=q)
    updater = extUpdater(bot=testbot, use_context=True)

    for admin in LIST_OF_ADMINS:
        updater.bot.send_message(chat_id=admin, text=init_message_config)

    episode_handler = EpisodeHandler(client, power_pizza, WordCounter())
    episode_handler.add_episodes_to_show()

    facade_bot = FacadeBot(episode_handler)

    dp = updater.dispatcher
    dp.add_handler(CommandHandler("s", facade_bot.search))
    dp.add_handler(CommandHandler("top", facade_bot.set_top_results))
    dp.add_handler(CommandHandler("last", facade_bot.get_last_ep))
    dp.add_handler(CommandHandler("get", facade_bot.get_ep))
    dp.add_handler(CommandHandler("random", facade_bot.get_ep_random))
    dp.add_handler(CommandHandler("host", facade_bot.get_eps_host))
    dp.add_handler(CommandHandler("hostf", facade_bot.get_eps_host))
    dp.add_handler(CommandHandler("hosta", facade_bot.get_eps_host))
    dp.add_handler(
        CommandHandler("dump",
                       facade_bot.dump_data,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))

    # analytics commands
    dp.add_handler(
        CommandHandler("nu",
                       facade_bot.get_users_total_n,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))
    dp.add_handler(
        CommandHandler("ncw",
                       facade_bot.get_most_common_words,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))
    dp.add_handler(
        CommandHandler("neps",
                       facade_bot.get_episodes_total_n,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))
    dp.add_handler(
        CommandHandler("qry",
                       facade_bot.get_daily_logs,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))

    dp.add_handler(
        CommandHandler("memo",
                       facade_bot.memo,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))

    dp.add_handler(CommandHandler("start", facade_bot.start))
    dp.add_handler(CommandHandler("help", facade_bot.help))

    dp.add_error_handler(error_callback)

    facade_bot.schedule_jobs(dp.job_queue)

    def stop_and_restart():
        logger.info("Stop and restarting bot...")
        updater.stop()
        os.execl(sys.executable, sys.executable, *sys.argv)

    def kill_bot():
        logger.info("Shutting down bot...")
        updater.stop()

    @restricted
    def restart(update, context):
        result_dump = facade_bot.dump_data(update, context)

        for res_dump, name_dump in result_dump:
            update.message.reply_text(f"{name_dump} save " +
                                      "success." if res_dump else "fail.")

        update.message.reply_text("Bot is restarting...")
        Thread(target=stop_and_restart).start()

    @restricted
    def kill(update, context):
        result_dump = facade_bot.dump_data(update, context)

        for res_dump, name_dump in result_dump:
            update.message.reply_text(f"{name_dump} save " +
                                      "success." if res_dump else "fail.")

        update.message.reply_text("See you, space cowboy...")
        Thread(target=kill_bot).start()

    # handler restarter
    dp.add_handler(
        CommandHandler("restart",
                       restart,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))
    dp.add_handler(
        CommandHandler("killme",
                       kill,
                       filters=Filters.user(username=CREATOR_TELEGRAM_ID)))

    updater.start_polling()

    updater.idle()
Example #10
0
class Updater(object):
    """
    This class, which employs the Dispatcher class, provides a frontend to
    telegram.Bot to the programmer, so they can focus on coding the bot. Its
    purpose is to receive the updates from Telegram and to deliver them to said
    dispatcher. It also runs in a separate thread, so the user can interact
    with the bot, for example on the command line. The dispatcher supports
    handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types.
    The updater can be started as a polling service or, for production, use a
    webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:

    Args:
        token (Optional[str]): The bot's token given by the @BotFather
        base_url (Optional[str]):
        workers (Optional[int]): Amount of threads in the thread pool for
            functions decorated with @run_async
        bot (Optional[Bot]): A pre-initialized bot instance. If a pre-initizlied bot is used, it is
            the user's responsibility to create it using a `Request` instance with a large enough
            connection pool.
        job_queue_tick_interval(Optional[float]): The interval the queue should
            be checked for new tasks. Defaults to 1.0

    Raises:
        ValueError: If both `token` and `bot` are passed or none of them.

    """
    _request = None

    def __init__(self, token=None, base_url=None, workers=4, bot=None):
        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        if bot is not None:
            self.bot = bot
        else:
            # we need a connection pool the size of:
            # * for each of the workers
            # * 1 for Dispatcher
            # * 1 for polling Updater (even if webhook is used, we can spare a connection)
            # * 1 for JobQueue
            # * 1 for main thread
            self._request = Request(con_pool_size=workers + 4)
            self.bot = Bot(token, base_url, request=self._request)
        self.update_queue = Queue()
        self.job_queue = JobQueue(self.bot)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(
            self.bot,
            self.update_queue,
            job_queue=self.job_queue,
            workers=workers,
            exception_event=self.__exception_event)
        self.last_update_id = 0
        self.logger = logging.getLogger(__name__)
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []
        """:type: list[Thread]"""

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper, name=name, args=(target,) + args, kwargs=kwargs)
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target, *args, **kwargs):
        thr_name = current_thread().name
        self.logger.debug('{0} - started'.format(thr_name))
        try:
            target(*args, **kwargs)
        except Exception:
            self.__exception_event.set()
            self.logger.exception('unhandled exception')
            raise
        self.logger.debug('{0} - ended'.format(thr_name))

    def start_polling(self,
                      poll_interval=0.0,
                      timeout=10,
                      network_delay=5.,
                      clean=False,
                      bootstrap_retries=0):
        """
        Starts polling updates from Telegram.

        Args:
            poll_interval (Optional[float]): Time to wait between polling updates from Telegram in
            seconds. Default is 0.0

            timeout (Optional[float]): Passed to Bot.getUpdates

            network_delay (Optional[float]): Passed to Bot.getUpdates

            clean (Optional[bool]): Whether to clean any pending updates on Telegram servers before
              actually starting to poll. Default is False.

            bootstrap_retries (Optional[int]): Whether the bootstrapping phase of the `Updater`
              will retry on failures on the Telegram server.

                |   < 0 - retry indefinitely
                |   0 - no retries (default)
                |   > 0 - retry up to X times

        Returns:
            Queue: The update queue that can be filled from the main thread

        """
        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self._init_thread(self.dispatcher.start, "dispatcher")
                self._init_thread(self._start_polling, "updater", poll_interval, timeout,
                                  network_delay, bootstrap_retries, clean)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def start_webhook(self,
                      listen='127.0.0.1',
                      port=80,
                      url_path='',
                      cert=None,
                      key=None,
                      clean=False,
                      bootstrap_retries=0,
                      webhook_url=None):
        """
        Starts a small http server to listen for updates via webhook. If cert
        and key are not provided, the webhook will be started directly on
        http://listen:port/url_path, so SSL can be handled by another
        application. Else, the webhook will be started on
        https://listen:port/url_path

        Args:
            listen (Optional[str]): IP-Address to listen on
            port (Optional[int]): Port the bot should be listening on
            url_path (Optional[str]): Path inside url
            cert (Optional[str]): Path to the SSL certificate file
            key (Optional[str]): Path to the SSL key file
            clean (Optional[bool]): Whether to clean any pending updates on
                Telegram servers before actually starting the webhook. Default
                is False.
            bootstrap_retries (Optional[int[): Whether the bootstrapping phase
                of the `Updater` will retry on failures on the Telegram server.

                |   < 0 - retry indefinitely
                |   0 - no retries (default)
                |   > 0 - retry up to X times
            webhook_url (Optional[str]): Explicitly specifiy the webhook url.
                Useful behind NAT, reverse proxy, etc. Default is derived from
                `listen`, `port` & `url_path`.

        Returns:
            Queue: The update queue that can be filled from the main thread

        """
        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self._init_thread(self.dispatcher.start, "dispatcher"),
                self._init_thread(self._start_webhook, "updater", listen, port, url_path, cert,
                                  key, bootstrap_retries, clean, webhook_url)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def _start_polling(self, poll_interval, timeout, network_delay, bootstrap_retries, clean):
        """
        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='')

        while self.running:
            try:
                updates = self.bot.getUpdates(
                    self.last_update_id, timeout=timeout, network_delay=network_delay)
            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)

    @staticmethod
    def _increase_poll_interval(current_interval):
        # increase waiting times on subsequent errors up to 30secs
        if current_interval == 0:
            current_interval = 1
        elif current_interval < 30:
            current_interval += current_interval / 2
        elif current_interval > 30:
            current_interval = 30
        return current_interval

    def _start_webhook(self, listen, port, url_path, cert, key, bootstrap_retries, clean,
                       webhook_url):
        self.logger.debug('Updater thread started')
        use_ssl = cert is not None and key is not None
        if not url_path.startswith('/'):
            url_path = '/{0}'.format(url_path)

        # Create and start server
        self.httpd = WebhookServer((listen, port), WebhookHandler, self.update_queue, url_path,
                                   self.bot)

        if use_ssl:
            self._check_ssl_cert(cert, key)

            # DO NOT CHANGE: Only set webhook if SSL is handled by library
            if not webhook_url:
                webhook_url = self._gen_webhook_url(listen, port, url_path)

            self._bootstrap(
                max_retries=bootstrap_retries,
                clean=clean,
                webhook_url=webhook_url,
                cert=open(cert, 'rb'))
        elif clean:
            self.logger.warning("cleaning updates is not supported if "
                                "SSL-termination happens elsewhere; skipping")

        self.httpd.serve_forever(poll_interval=1)

    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')

    @staticmethod
    def _gen_webhook_url(listen, port, url_path):
        return 'https://{listen}:{port}{path}'.format(listen=listen, port=port, path=url_path)

    def _bootstrap(self, max_retries, clean, webhook_url, cert=None):
        retries = 0
        while 1:

            try:
                if clean:
                    # Disable webhook for cleaning
                    self.bot.setWebhook(webhook_url='')
                    self._clean_updates()

                self.bot.setWebhook(webhook_url=webhook_url, certificate=cert)
            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)

    def _clean_updates(self):
        self.logger.debug('Cleaning updates from Telegram server')
        updates = self.bot.getUpdates()
        while updates:
            updates = self.bot.getUpdates(updates[-1].update_id + 1)

    def stop(self):
        """
        Stops the polling/webhook thread, the dispatcher and the job queue
        """

        self.job_queue.stop()
        with self.__lock:
            if self.running or self.dispatcher.has_running_threads:
                self.logger.debug('Stopping Updater and Dispatcher...')

                self.running = False

                self._stop_httpd()
                self._stop_dispatcher()
                self._join_threads()

                # Stop the Request instance only if it was created by the Updater
                if self._request:
                    self._request.stop()

    def _stop_httpd(self):
        if self.httpd:
            self.logger.debug('Waiting for current webhook connection to be '
                              'closed... Send a Telegram message to the bot to exit '
                              'immediately.')
            self.httpd.shutdown()
            self.httpd = None

    def _stop_dispatcher(self):
        self.logger.debug('Requesting Dispatcher to stop...')
        self.dispatcher.stop()

    def _join_threads(self):
        for thr in self.__threads:
            self.logger.debug('Waiting for {0} thread to end'.format(thr.name))
            thr.join()
            self.logger.debug('{0} thread has ended'.format(thr.name))
        self.__threads = []

    def signal_handler(self, signum, frame):
        self.is_idle = False
        if self.running:
            self.stop()
        else:
            self.logger.warning('Exiting immediately!')
            import os
            os._exit(1)

    def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
        """
        Blocks until one of the signals are received and stops the updater

        Args:
            stop_signals: Iterable containing signals from the signal module
                that should be subscribed to. Updater.stop() will be called on
                receiving one of those signals. Defaults to (SIGINT, SIGTERM,
                SIGABRT)
        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
def main():
    parser = argparse.ArgumentParser()
    # Оба аргумента опциональные, поэтому они начинаются с --
    parser.add_argument("--image",
                        help="Отправить сообщение с картинкой",
                        action="store_true")
    parser.add_argument("--text",
                        help="Отправить сообщение с текстом",
                        action="store_true")
    args = parser.parse_args()

    # Нельзя указать оба сразу
    if args.image and args.text:
        logger.error("Нельзя указать одновременно `--image` и `--text`")
        sys.exit(1)

    # Если ничего не указано, то считаем что это --text
    if not any([args.image, args.text]):
        args.text = True

    config = load_config()

    client = BittrexClient()

    try:
        current_price = client.get_last_price(pair=config.NOTIFY_PAIR)
        message = "{} = {}".format(config.NOTIFY_PAIR, current_price)
    except BittrexError:
        logger.error("BittrexError")
        current_price = None
        message = "Произошла ошибка"

    config = load_config()

    # Подключиться к API
    req = Request(
        connect_timeout=0.5,
        read_timeout=1.0,
    )
    bot = Bot(
        token=config.TG_TOKEN,
        request=req,
        base_url=config.TG_API_URL,
    )

    # Проверить что бот корректно подключился к Telegram API
    info = bot.get_me()
    logger.info(f'Bot info: {info}')

    # Отправить сообщение
    bot.send_message(
        chat_id=config.NOTIFY_USER_ID,
        text=message,
    )
    logger.info('Success: %s', message)

    if args.text:
        bot.send_message(
            chat_id=config.NOTIFY_USER_ID,
            text=message,
        )
        logger.info("текстовое сообщение отправлено")
    if args.image:
        if current_price:
            text = [config.NOTIFY_PAIR, current_price]
        else:
            text = [config.NOTIFY_PAIR, message]

        img = drawer(text=text)
        photo = save_image(img=img)
        bot.send_photo(
            chat_id=config.NOTIFY_USER_ID,
            photo=photo,
            caption='Подпись под фото',
        )
        logger.info("картинка отправлена")
Example #12
0
def main():
    q = mq.MessageQueue(all_burst_limit=29, all_time_limit_ms=1017)
    # set connection pool size for bot
    request = Request(con_pool_size=8)
    delivery_bot = MQBot(config.BOT_TOKEN, request=request, mqueue=q)
    persistence = PicklePersistence(filename='conversation')
    updater = Updater(
        bot=delivery_bot,
        persistence=persistence,
        use_context=True)

    dp = updater.dispatcher

    conv_handler = ConversationHandler(

        entry_points=[CommandHandler('start', start)],

        states={
            INITIAL: [
                MessageHandler(
                    Filters.regex(config.text['cart']),
                    cart_handler),
                MessageHandler(
                    Filters.regex(config.text['btn_settings']),
                    settings_handler),
                MessageHandler(
                    Filters.text, start)
                ],
            NAME: [MessageHandler(
                Filters.text,
                user_name_handler)],
            PHONE: [MessageHandler(
                Filters.text | Filters.contact,
                user_phone_handler)],
            BIRTHDAY: [
                MessageHandler(
                    Filters.regex(config.text['skip']), start),
                MessageHandler(
                    Filters.text, user_birthday_handler)
                ],
            CHOOSING_CATEGORY: [
                MessageHandler(
                    Filters.regex(config.text['back']), start),
                MessageHandler(
                    Filters.regex(config.text['cart']), cart_handler),
                MessageHandler(
                    Filters.regex(config.text['btn_settings']),
                    settings_handler),
                MessageHandler(
                    Filters.text, select_category)
                ],
            CHOOSING_PRODUCT: [
                MessageHandler(
                    Filters.regex(config.text['back']), start),
                MessageHandler(
                    Filters.text & (
                        ~ Filters.regex(config.text['back']) |
                        ~ Filters.regex(config.text['cart'])),
                    show_product)
                ],
            TYPING_QUONTITY: [
                MessageHandler(
                    Filters.regex(config.text['back']), start),
                MessageHandler(
                    Filters.text & (~ Filters.regex(config.text['cart'])),
                    add_to_cart_handler)
                ],
            EDITING_CART: [
                MessageHandler(
                    Filters.text & Filters.regex('^❌\s.*'),
                    delete_item_handler),
                MessageHandler(
                    Filters.text & Filters.regex(config.text['clear']),
                    clear_cart_handler),
                MessageHandler(
                    Filters.text & Filters.regex(config.text['order']),
                    order_handler)
            ],
            ORDERING: [
                MessageHandler(
                    Filters.regex(config.text['delivery']),
                    delivery_handler),
                MessageHandler(
                    Filters.regex(config.text['self_pick']),
                    self_pick_handler),
                MessageHandler(
                    Filters.regex(config.text['terminal']),
                    order_confirmation_handler),
                MessageHandler(
                    Filters.regex(config.text['cash']),
                    order_confirmation_handler),
                MessageHandler(
                    Filters.regex(config.text['confirm']),
                    submit_order_handler),
                MessageHandler(
                    Filters.regex(config.text['cancel']),
                    cancel_order_handler),
                MessageHandler(
                    Filters.regex(config.text['back']),
                    cart_handler),
                MessageHandler(
                    Filters.text | Filters.location, location_handler)
            ],
            SETTINGS: [
                MessageHandler(
                    Filters.regex(config.text['btn_change_phone']),
                    update_user_phone_handler),
                MessageHandler(
                    Filters.regex(config.text['btn_change_name']),
                    update_user_name_handler),
                MessageHandler(
                    Filters.regex(config.text['btn_change_birth']),
                    user_birthday_handler),
                MessageHandler(
                    Filters.regex(config.text['btn_back']),
                    start
                )
            ],
            SETTINGS_ENTERING_PHONE: [
                MessageHandler(
                    Filters.text | Filters.contact,
                    update_user_phone_validator)
            ],
            SETTINGS_ENTERING_NAME: [
                MessageHandler(
                    Filters.text,
                    update_user_name_validator)
            ],
            ConversationHandler.TIMEOUT: [
                MessageHandler(
                    Filters.text, done, pass_user_data=True)
                    ]
        },

        fallbacks=[
            MessageHandler(
                    Filters.text & Filters.regex(config.text['order']),
                    order_handler),
            MessageHandler(Filters.regex(config.text['back']), start),
            MessageHandler(Filters.regex(config.text['cart']), cart_handler),
            MessageHandler(Filters.regex('^❌\s.*'), delete_item_handler),
            CallbackQueryHandler(
                    delivery_time_handler,
                    pattern='^.*delivery_time.*$',
                    pass_user_data=True),
            CallbackQueryHandler(
                    order_confirm_handler,
                    pattern='^.*order_confirm.*$'),
            CallbackQueryHandler(
                    order_cancel_handler,
                    pattern='^.*order_cancel.*$'),
            ],
        name="my_conversation",
        persistent=True,
        allow_reentry=True
    )

    def stop_and_restart():
        """
        Gracefully stop the Updater
        and replace the current process with a new one
        """
        logging.info('stop_and_restart function fired')
        updater.stop()
        os.execl(sys.executable, sys.executable, *sys.argv)

    def restart(update, context):
        update.message.reply_text('Bot is restarting...')
        Thread(target=stop_and_restart).start()

    dp.add_handler(conv_handler)
    dp.add_handler(CommandHandler('start', start))
    dp.add_handler(CommandHandler('getlogs', get_logs_handler))
    dp.add_handler(CommandHandler('getdb', get_db_handler))
    dp.add_handler(CommandHandler('getreport', get_report_handler))
    dp.add_handler(CommandHandler(
        'r', restart, filters=Filters.user(config.admins)))
    dp.add_handler(CommandHandler('reply', reply_handler))
    dp.add_handler(CommandHandler('replyall', reply_all_handler))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    updater.idle()
Example #13
0
    def ready(self):
        if DjangoTelegramBot.ready_run:
            return
        DjangoTelegramBot.ready_run = True

        self.mode = WEBHOOK_MODE
        if settings.DJANGO_TELEGRAMBOT.get('MODE', 'WEBHOOK') == 'POLLING':
            self.mode = POLLING_MODE

        modes = ['WEBHOOK', 'POLLING']
        logger.info('Django Telegram Bot <{} mode>'.format(modes[self.mode]))

        bots_list = settings.DJANGO_TELEGRAMBOT.get('BOTS', [])

        if self.mode == WEBHOOK_MODE:
            webhook_site = settings.DJANGO_TELEGRAMBOT.get(
                'WEBHOOK_SITE', None)
            if not webhook_site:
                logger.warn(
                    'Required TELEGRAM_WEBHOOK_SITE missing in settings')
                return
            if webhook_site.endswith("/"):
                webhook_site = webhook_site[:-1]

            webhook_base = settings.DJANGO_TELEGRAMBOT.get(
                'WEBHOOK_PREFIX', '/')
            if webhook_base.startswith("/"):
                webhook_base = webhook_base[1:]
            if webhook_base.endswith("/"):
                webhook_base = webhook_base[:-1]

            cert = settings.DJANGO_TELEGRAMBOT.get('WEBHOOK_CERTIFICATE', None)
            certificate = None
            if cert and os.path.exists(cert):
                logger.info('WEBHOOK_CERTIFICATE found in {}'.format(cert))
                certificate = open(cert, 'rb')
            elif cert:
                logger.error(
                    'WEBHOOK_CERTIFICATE not found in {} '.format(cert))

        for b in bots_list:
            token = b.get('TOKEN', None)
            context = b.get('CONTEXT', False)
            if not token:
                break

            allowed_updates = b.get('ALLOWED_UPDATES', None)
            timeout = b.get('TIMEOUT', None)
            proxy = b.get('PROXY', None)

            if self.mode == WEBHOOK_MODE:
                try:
                    if b.get('MESSAGEQUEUE_ENABLED', False):
                        q = mq.MessageQueue(
                            all_burst_limit=b.get(
                                'MESSAGEQUEUE_ALL_BURST_LIMIT', 29),
                            all_time_limit_ms=b.get(
                                'MESSAGEQUEUE_ALL_TIME_LIMIT_MS', 1024))
                        if proxy:
                            request = Request(
                                proxy_url=proxy['proxy_url'],
                                urllib3_proxy_kwargs=proxy[
                                    'urllib3_proxy_kwargs'],
                                con_pool_size=b.get(
                                    'MESSAGEQUEUE_REQUEST_CON_POOL_SIZE', 8))
                        else:
                            request = Request(con_pool_size=b.get(
                                'MESSAGEQUEUE_REQUEST_CON_POOL_SIZE', 8))
                        bot = MQBot(token, request=request, mqueue=q)
                    else:
                        request = None
                        if proxy:
                            request = Request(proxy_url=proxy['proxy_url'],
                                              urllib3_proxy_kwargs=proxy[
                                                  'urllib3_proxy_kwargs'])
                        bot = telegram.Bot(token=token, request=request)

                    DjangoTelegramBot.dispatchers.append(
                        Dispatcher(bot, None, workers=0, use_context=context))
                    hookurl = '{}/{}/{}/'.format(webhook_site, webhook_base,
                                                 token)
                    max_connections = b.get('WEBHOOK_MAX_CONNECTIONS', 40)
                    setted = bot.setWebhook(hookurl,
                                            certificate=certificate,
                                            timeout=timeout,
                                            max_connections=max_connections,
                                            allowed_updates=allowed_updates)
                    webhook_info = bot.getWebhookInfo()
                    real_allowed = webhook_info.allowed_updates if webhook_info.allowed_updates else [
                        "ALL"
                    ]

                    bot.more_info = webhook_info
                    logger.info(
                        'Telegram Bot <{}> setting webhook [ {} ] max connections:{} allowed updates:{} pending updates:{} : {}'
                        .format(bot.username, webhook_info.url,
                                webhook_info.max_connections, real_allowed,
                                webhook_info.pending_update_count, setted))

                except InvalidToken:
                    logger.error('Invalid Token : {}'.format(token))
                    return
                except RetryAfter as er:
                    logger.debug(
                        'Error: "{}". Will retry in {} seconds'.format(
                            er.message, er.retry_after))
                    sleep(er.retry_after)
                    self.ready()
                except TelegramError as er:
                    logger.error('Error: "{}"'.format(er.message))
                    return

            else:
                try:
                    updater = Updater(token=token,
                                      request_kwargs=proxy,
                                      use_context=context)
                    bot = updater.bot
                    bot.delete_webhook()
                    DjangoTelegramBot.updaters.append(updater)
                    DjangoTelegramBot.dispatchers.append(updater.dispatcher)
                    DjangoTelegramBot.__used_tokens.add(token)
                except InvalidToken:
                    logger.error('Invalid Token : {}'.format(token))
                    return
                except RetryAfter as er:
                    logger.debug(
                        'Error: "{}". Will retry in {} seconds'.format(
                            er.message, er.retry_after))
                    sleep(er.retry_after)
                    self.ready()
                except TelegramError as er:
                    logger.error('Error: "{}"'.format(er.message))
                    return

            DjangoTelegramBot.bots.append(bot)
            DjangoTelegramBot.bot_tokens.append(token)
            DjangoTelegramBot.bot_usernames.append(bot.username)

        logger.debug('Telegram Bot <{}> set as default bot'.format(
            DjangoTelegramBot.bots[0].username))

        def module_imported(module_name, method_name, execute):
            try:
                m = importlib.import_module(module_name)
                if execute and hasattr(m, method_name):
                    logger.debug('Run {}.{}()'.format(module_name,
                                                      method_name))
                    getattr(m, method_name)()
                else:
                    logger.debug('Run {}'.format(module_name))

            except ImportError as er:
                if settings.DJANGO_TELEGRAMBOT.get('STRICT_INIT'):
                    raise er
                else:
                    logger.error('{} : {}'.format(module_name, repr(er)))
                    return False

            return True

        # import telegram bot handlers for all INSTALLED_APPS
        for app_config in apps.get_app_configs():
            if module_has_submodule(app_config.module,
                                    TELEGRAM_BOT_MODULE_NAME):
                module_name = '%s.%s' % (app_config.name,
                                         TELEGRAM_BOT_MODULE_NAME)
                if module_imported(module_name, 'main', True):
                    logger.info('Loaded {}'.format(module_name))

        num_bots = len(DjangoTelegramBot.__used_tokens)
        if self.mode == POLLING_MODE and num_bots > 0:
            logger.info(
                'Please manually start polling update for {0} bot{1}. Run command{1}:'
                .format(num_bots, 's' if num_bots > 1 else ''))
            for token in DjangoTelegramBot.__used_tokens:
                updater = DjangoTelegramBot.get_updater(bot_id=token)
                logger.info('python manage.py botpolling --username={}'.format(
                    updater.bot.username))
Example #14
0
 def __init__(self, bot_token, proxy=None):
     if proxy:
         self.__bot = Bot(bot_token, request=Request(proxy_url=proxy))
     else:
         self.__bot = Bot(bot_token)
Example #15
0
    def __init__(self):
        from telegram.utils.request import Request

        self.my_database = db.MyDatabase(Conf.database_url)

        self.ldap_access = ldap.LdapAccess(Conf.ldap_server, Conf.ldap_user,
                                           Conf.ldap_password,
                                           Conf.ldap_base_group_filter)

        # recommended values for production: 29/1017
        q = mq.MessageQueue(all_burst_limit=29, all_time_limit_ms=1017)
        # set connection pool size for bot
        request = Request(con_pool_size=8)
        mqbot = MQBot(token=Conf.bot_token,
                      request=request,
                      mqueue=q,
                      keyboard_message_queue=self.keyboard_message_queue)
        updater = telegram.ext.updater.Updater(bot=mqbot, use_context=True)
        dispatcher = updater.dispatcher

        send_cancel_handler = CommandHandler('cancel', self.cancel_send)

        with warnings.catch_warnings():
            # We filter out a certain warning message by python-telegram-bot here
            warnings.filterwarnings(
                'ignore',
                "If 'per_message=False', 'CallbackQueryHandler' will not be "
                "tracked for every message.")
            conversation_handler = ConversationHandler(
                entry_points=[
                    CommandHandler('start', self.cmd_start),
                    CommandHandler('stop', self.cmd_stop),
                    CommandHandler('help', self.cmd_help),
                    CommandHandler('impressum', self.cmd_impressum),
                    CommandHandler('admin', self.cmd_admin),
                    CommandHandler('register', self.cmd_register),
                    CommandHandler('unregister', self.cmd_unregister),
                    CommandHandler('send', self.cmd_send),
                    CommandHandler('subscribe', self.cmd_subscribe),
                    CommandHandler('unsubscribe', self.cmd_unsubscribe)
                ],
                states={
                    SEND_CHANNEL: [
                        CallbackQueryHandler(pattern=CB_CHANNEL_REGEX,
                                             callback=self.answer_channel),
                        CallbackQueryHandler(pattern=CB_SEND_CANCEL,
                                             callback=self.cancel_send),
                        send_cancel_handler,
                        MessageHandler(Filters.text, self.answer_channel)
                    ],
                    SEND_MESSAGE: [
                        CallbackQueryHandler(pattern=CB_SEND_DONE,
                                             callback=self.answer_done),
                        CallbackQueryHandler(pattern=CB_SEND_CANCEL,
                                             callback=self.cancel_send),
                        CommandHandler('done', self.answer_done),
                        send_cancel_handler,
                        MessageHandler(Filters.all & (~Filters.command),
                                       self.answer_message)
                    ],
                    SEND_CONFIRMATION: [
                        CallbackQueryHandler(pattern=CB_SEND_CONFIRM,
                                             callback=self.answer_confirm),
                        CallbackQueryHandler(pattern=CB_SEND_CANCEL,
                                             callback=self.cancel_send),
                        CommandHandler('confirm', self.answer_confirm),
                        send_cancel_handler
                    ],
                    SUBSCRIBE_CHANNEL: [
                        CallbackQueryHandler(
                            pattern=CB_CHANNEL_REGEX,
                            callback=self.answer_subscribe_channel),
                        CallbackQueryHandler(pattern=CB_SUBSCRIBE_CANCEL,
                                             callback=self.cancel_subscribe),
                        CommandHandler('cancel', self.cancel_subscribe),
                        MessageHandler(Filters.text,
                                       self.answer_subscribe_channel)
                    ],
                    UNSUBSCRIBE_CHANNEL: [
                        CallbackQueryHandler(
                            pattern=CB_CHANNEL_REGEX,
                            callback=self.answer_unsubscribe_channel),
                        CallbackQueryHandler(pattern=CB_UNSUBSCRIBE_CANCEL,
                                             callback=self.cancel_unsubscribe),
                        CommandHandler('cancel', self.cancel_unsubscribe),
                        MessageHandler(Filters.text,
                                       self.answer_unsubscribe_channel)
                    ]
                },
                fallbacks=[])
        dispatcher.add_handler(conversation_handler)

        fallback_cancel_handler = CommandHandler(
            'cancel', TelegramShoutoutBot.answer_invalid_cancel)
        fallback_cmd_handler = MessageHandler(
            Filters.command, TelegramShoutoutBot.answer_invalid_cmd)
        fallback_msg_handler = MessageHandler(
            Filters.all, TelegramShoutoutBot.answer_invalid_msg)
        dispatcher.add_handler(fallback_cancel_handler)
        dispatcher.add_handler(fallback_cmd_handler)
        dispatcher.add_handler(fallback_msg_handler)

        # log all errors
        dispatcher.add_error_handler(TelegramShoutoutBot.error)

        updater.start_polling()
        updater.idle()
Example #16
0
import telegram
from telegram.utils.request import Request
from config import Config
settings = Config.load()
bot = telegram.Bot(
    token='706594478:AAFjQFtuHgiR_DoB1HO9MJdPwoI_IpmkMzw',
    request=Request(
        proxy_url='http://127.0.0.1:1087' if settings.enable_proxy else None))
Example #17
0
def main():
    # Setup logging
    logging.getLogger("pdfminer").setLevel(logging.WARNING)
    logging.getLogger("ocrmypdf").setLevel(logging.WARNING)
    redirect_logging()
    format_string = "{record.level_name}: {record.message}"
    StreamHandler(sys.stdout, format_string=format_string,
                  level="INFO").push_application()
    log = Logger()

    q = mq.MessageQueue(all_burst_limit=3, all_time_limit_ms=3000)
    request = Request(con_pool_size=8)
    pdf_bot = MQBot(TELE_TOKEN, request=request, mqueue=q)

    # Create the EventHandler and pass it your bot's token.
    updater = Updater(
        bot=pdf_bot,
        use_context=True,
        request_kwargs={
            "connect_timeout": TIMEOUT,
            "read_timeout": TIMEOUT
        },
    )

    def stop_and_restart():
        updater.stop()
        os.execl(sys.executable, sys.executable, *sys.argv)

    def restart(_):
        Thread(target=stop_and_restart).start()

    job_queue = updater.job_queue
    job_queue.run_repeating(restart, interval=dt.timedelta(minutes=30))

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

    # General commands handlers
    dispatcher.add_handler(CommandHandler("start", start_msg, run_async=True))
    dispatcher.add_handler(CommandHandler("help", help_msg, run_async=True))
    dispatcher.add_handler(CommandHandler("setlang", send_lang,
                                          run_async=True))
    dispatcher.add_handler(
        CommandHandler("support", send_support_options, run_async=True))
    dispatcher.add_handler(
        CommandHandler("send", send_msg, Filters.user(DEV_TELE_ID)))
    dispatcher.add_handler(
        CommandHandler("stats", get_stats, Filters.user(DEV_TELE_ID)))

    # Callback query handler
    dispatcher.add_handler(
        CallbackQueryHandler(process_callback_query, run_async=True))

    # Payment handlers
    dispatcher.add_handler(
        MessageHandler(Filters.reply & TEXT_FILTER,
                       receive_custom_amount,
                       run_async=True))
    dispatcher.add_handler(
        PreCheckoutQueryHandler(precheckout_check, run_async=True))
    dispatcher.add_handler(
        MessageHandler(Filters.successful_payment,
                       successful_payment,
                       run_async=True))

    # URL handler
    dispatcher.add_handler(
        MessageHandler(Filters.entity(MessageEntity.URL),
                       url_to_pdf,
                       run_async=True))

    # PDF commands handlers
    dispatcher.add_handler(compare_cov_handler())
    dispatcher.add_handler(merge_cov_handler())
    dispatcher.add_handler(photo_cov_handler())
    dispatcher.add_handler(text_cov_handler())
    dispatcher.add_handler(watermark_cov_handler())

    # PDF file handler
    dispatcher.add_handler(file_cov_handler())

    # Feedback handler
    dispatcher.add_handler(feedback_cov_handler())

    # Log all errors
    dispatcher.add_error_handler(error_callback)

    # Start the Bot
    if APP_URL is not None:
        updater.start_webhook(
            listen="0.0.0.0",
            port=PORT,
            url_path=TELE_TOKEN,
            webhook_url=APP_URL + TELE_TOKEN,
        )
        log.notice("Bot started webhook")
    else:
        updater.start_polling()
        log.notice("Bot started polling")

    # Run the bot until the you presses 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 #18
0
import configparser

cache_directory = '.cache'
log.add('./logs/bot_log_{time}.log', retention=timedelta(days=2))

# Чтение конфигурации бота из файла config.ini
config = configparser.ConfigParser()
config.read_file(open('./config.ini', 'r', encoding='utf-8'))
# Инициализация Telegram бота
bot_token = config.get('global', 'bot_token')
# Указан ли прокси в конфиге
if config.get('global', 'proxy_url'):
    log.warning(
        'Бот будет работать через прокси. Возможны перебои в работе бота.')
    request = Request(proxy_url=config.get('global', 'proxy_url'),
                      connect_timeout=15.0,
                      read_timeout=15.0)
else:
    request = None
bot = Bot(bot_token, request=request)
# Чтение из конфига логина и пароля ВК
vk_login = config.get('global', 'login')
vk_pass = config.get('global', 'pass')
# Инициализация ВК сессии
session = VkApi(login=vk_login,
                password=vk_pass,
                auth_handler=auth_handler,
                captcha_handler=captcha_handler)
session.auth()
api_vk = session.get_api()
Example #19
0
def main():
    print("starting bot...")

    # *** boilerplate start
    from pathlib import Path
    token_file = Path('token.txt')

    token = os.environ.get('TOKEN') or open(token_file).read().strip()
    # None (simile a null in Java)
    print(f"len(token) = {len(token)}")

    # @user2837467823642_bot

    # https://github.com/python-telegram-bot/python-telegram-bot/wiki/Avoiding-flood-limits
    q = mq.MessageQueue(
        all_burst_limit=29,
        all_time_limit_ms=1017)  # 5% safety margin in messaging flood limits
    # set connection pool size for bot
    request = Request(con_pool_size=8)
    my_bot = MQBot(token, request=request, mqueue=q)

    global global_bot_instance
    global_bot_instance = my_bot

    updater = Updater(bot=my_bot, use_context=True)
    dp = updater.dispatcher

    job_queue = updater.job_queue
    # *** boilerplate end

    conv_handler = ConversationHandler(
        entry_points=[
            CommandHandler('info', info_command_handler),
        ],
        states={
            CALLBACK_NAME: [MessageHandler(Filters.text, callback_name)],
            CALLBACK_SURNAME: [MessageHandler(Filters.text, callback_surname)],
            CALLBACK_AGE: [MessageHandler(Filters.text, callback_age)],
        },
        fallbacks=[MessageHandler(Filters.all, fallback_conversation_handler)])

    dp.add_handler(conv_handler)

    dp.add_handler(CommandHandler('start', start_command_handler))
    dp.add_handler(CommandHandler('help', help_command_handler))

    dp.add_handler(CommandHandler('ora', get_time_command_handler))

    dp.add_handler(MessageHandler(Filters.text, generic_message_handler))

    # *** boilerplate start
    # start updater
    updater.start_polling()

    # Stop the bot if you have pressed Ctrl + C or the process has received SIGINT, SIGTERM or SIGABRT
    updater.idle()

    print("terminating bot")

    try:
        request.stop()
        q.stop()
        my_bot.__del__()
    except Exception as e:
        print(e)

    # https://stackoverflow.com/a/40525942/974287
    print("before os._exit")
    os._exit(0)
def launch():
    msg_queue = mqueue.MessageQueue(all_burst_limit=29, all_time_limit_ms=1017)
    request = Request(con_pool_size=4 + local_config.WORKERS_NUM)
    bot = ArbitrageBot(local_config.TOKEN,
                       request=request,
                       msg_queue=msg_queue)
    updater = Updater(bot=bot, workers=local_config.WORKERS_NUM)
    dispatcher = updater.dispatcher

    available_commands = [
        CommandHandler('start',
                       commands.start,
                       pass_args=True,
                       pass_job_queue=True,
                       pass_chat_data=True),
        CommandHandler('switch_on',
                       commands.switch_on,
                       pass_job_queue=True,
                       pass_chat_data=True),
        CommandHandler('switch_off',
                       commands.switch_off,
                       pass_job_queue=True,
                       pass_chat_data=True),
        CommandHandler('set_interval',
                       commands.set_interval,
                       pass_args=True,
                       pass_job_queue=True,
                       pass_chat_data=True),
        CommandHandler('set_threshold', commands.set_threshold,
                       pass_args=True),
        CommandHandler('add_coin', commands.add_coin, pass_args=True),
        CommandHandler('remove_coin', commands.remove_coin, pass_args=True),
        CommandHandler('show_coins', commands.show_your_coins),
        CommandHandler('add_exchange', commands.add_exchange, pass_args=True),
        CommandHandler('remove_exchange',
                       commands.remove_exchange,
                       pass_args=True),
        CommandHandler('show_exchanges', commands.show_your_exchanges),
        RegexHandler('(?!⬅Back)', commands.default_response)
    ]

    # Menus constructor
    conv_handler = ConversationHandler(
        entry_points=[
            CommandHandler('start',
                           commands.start,
                           pass_args=True,
                           pass_job_queue=True,
                           pass_chat_data=True)
        ],
        states={
            core.MAIN_MENU: [
                RegexHandler('^(🤖Settings)$', helpers.settings),
                RegexHandler('^(🔬FAQ)$', helpers.faq),
                RegexHandler('^(📱Contacts)$', helpers.contacts),
                RegexHandler('^(👾About)$', helpers.about)
            ] + available_commands,
            core.SETTINGS_MENU: [
                RegexHandler('^(🎚Set threshold)$', settings.threshold),
                RegexHandler('^(⏱Set interval)$', settings.interval),
                RegexHandler('^(🎛Alerts settings)$', settings.alerts_settings),
                RegexHandler('^(🔊Turn off/on notification)$',
                             settings.switch,
                             pass_job_queue=True,
                             pass_chat_data=True)
            ] + available_commands,
            core.ALERTS_MENU: [
                RegexHandler('^(💎Add/remove coins)$', alerts.add_remove_coin),
                RegexHandler('^(⚖️Add/remove exchanges)$',
                             alerts.add_remove_exchange),
                RegexHandler('^(⚙️Show my settings)$', alerts.show_settings),
                RegexHandler('^(⬅Back)$', settings.back_to_settings)
            ] + available_commands,
            core.SET_INTERVAL: [
                RegexHandler('^([0-9]+)$',
                             settings.set_interval_dialog,
                             pass_chat_data=True,
                             pass_job_queue=True),
                RegexHandler('^(⬅Back)$', settings.back_to_settings),
                CommandHandler('start',
                               commands.start,
                               pass_args=True,
                               pass_job_queue=True,
                               pass_chat_data=True),
                RegexHandler('\w*', settings.interval_help)
            ],
            core.SET_THRESHOLD: [
                RegexHandler('^([0-9]+(\.[0-9]*){0,1})$',
                             settings.set_threshold_dialog),
                RegexHandler('^(⬅Back)$', settings.back_to_settings),
                CommandHandler('start',
                               commands.start,
                               pass_args=True,
                               pass_job_queue=True,
                               pass_chat_data=True),
                RegexHandler('\w*', settings.threshold_help)
            ],
            core.ADD_RM_COINS: [
                RegexHandler(
                    '^([aA][dD][dD][ \t\n\r]+[A-Za-z]{3}/[A-Za-z]{3})$',
                    alerts.add_coin_dialog),
                RegexHandler('^([rR][mM][ \t\n\r]+[A-Za-z]{3}/[A-Za-z]{3})$',
                             alerts.remove_coin_dialog),
                RegexHandler('^([aA][lL][lL])$', alerts.show_all_coins),
                RegexHandler('^(⬅Back)$', alerts.back_to_alerts),
                CommandHandler('start',
                               commands.start,
                               pass_args=True,
                               pass_job_queue=True,
                               pass_chat_data=True),
                RegexHandler('\w*', alerts.coins_help)
            ],
            core.ADD_RM_EX: [
                RegexHandler('^([aA][dD][dD][ \t\n\r]+[-\w]+)$',
                             alerts.add_exchange_dialog),
                RegexHandler('^([rR][mM][ \t\n\r]+[-\w]+)$',
                             alerts.remove_exchange_dialog),
                RegexHandler('^([aA][lL][lL])$', alerts.show_all_exchanges),
                RegexHandler('^(⬅Back)$', alerts.back_to_alerts),
                CommandHandler('start',
                               commands.start,
                               pass_args=True,
                               pass_job_queue=True,
                               pass_chat_data=True),
                RegexHandler('\w*', alerts.ex_help)
            ],
            core.BLACK_HOLE: [
                CommandHandler('start',
                               commands.start,
                               pass_args=True,
                               pass_job_queue=True,
                               pass_chat_data=True),
                RegexHandler('\w*', commands.get_registration)
            ]
        },
        fallbacks=[RegexHandler('⬅Back', helpers.back)])

    dispatcher.add_handler(conv_handler)
    # Log all errors
    dispatcher.add_error_handler(commands.error)
    # Restart users notifications
    core.restart_jobs(dispatcher, mq.get_users())

    updater.start_webhook(listen='0.0.0.0',
                          port=local_config.PORT,
                          url_path=local_config.TOKEN,
                          key=local_config.WEBHOOK_PKEY,
                          cert=local_config.WEBHOOK_CERT,
                          webhook_url=local_config.URL + local_config.TOKEN)
    updater.idle()
Example #21
0
 def __init__(self, token=TEL_KEY, chat_id=TEL_CHAT):
     request = Request(
         con_pool_size=4 + 6
     )  # 4 - used by default threads, 6 - extra capacity == 10 (8 recommended)
     self._bot = telegram.Bot(token=token, request=request)
     self.default_msg_params = {"chat_id": chat_id}
# MIT License                                                          #
# Copyright (c) 2021 Michael Nikitenko                                 #
#                                                                      #
########################################################################

from datetime import datetime

from telegram import Bot
from telegram.ext import Updater
from telegram.utils.request import Request

from bot_config import API_TOKEN, CHAT_ID, ADMIN_ID
from weather_parser import get_weather
from compliments import generate_compliment

req = Request(connect_timeout=3)
bot = Bot(request=req, token=API_TOKEN)
updater = Updater(bot=bot, use_context=True)
dispatcher = updater.dispatcher


def log_error(f):
    """Отлавливание ошибок"""
    def inner(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except Exception as e:
            error = f'ERROR {e} in '
            print(error)
            update = args[0]
            if update and hasattr(update, 'message'):
Example #23
0
def lambda_handler(event, context):
    # Get params from event
    chat_id = event['chat_id']
    last_deleted_message_id = event['last_deleted_message_id']
    clear_message_interval = event['clear_message_interval']

    token = get_telegram_bot_token()  # Get telegram bot token

    # Return if no token found
    if not token:
        return

    # Init Request instance (For sending message)
    send_message_request = Request(connect_timeout=30, read_timeout=30)

    # Init Bot instance (For sending message)
    send_message_bot = Bot(token, request=send_message_request)

    # Init Request instance (For clearing message)
    request = Request(con_pool_size=10000, connect_timeout=2, read_timeout=2)

    # Init Bot instance (For clearing message)
    bot = Bot(token, request=request)

    # Get DynamoDB clients
    dynamodb_client = boto3.client('dynamodb')

    try:
        message = send_message_bot.send_message(chat_id=chat_id, text="正在刪除訊息")
    except ChatMigrated as e:  # Chat ID changed
        print("Chat ID: %s" % str(chat_id))
        print(e)

        new_chat_id = e.new_chat_id
        change_chat_id(dynamodb_client, chat_id, new_chat_id)
        chat_id = new_chat_id
        message = send_message_bot.send_message(chat_id=chat_id, text="正在刪除訊息")
    except Exception as e:
        print("Chat ID: %s" % str(chat_id))
        print(e)
        return

    if not message or not message.message_id:
        return

    message_id = message.message_id

    start_from = message_id - 5  # Retain latest messages

    # Saving latest deleted message ID
    latest_deleted_message_id = 1

    # Loop through message ID from last time deleted message ID to latest message ID
    message_id_list = list(range(last_deleted_message_id, start_from))

    # Split the list every 100 items
    splited_list = [
        message_id_list[x:x + 100] for x in range(0, len(message_id_list), 100)
    ]

    for current_message_id_list in splited_list:  # Run specific number of threads in a time
        thread_list = {}  # Reset thread list

        for i in current_message_id_list:
            thread = ReturnResultThread(target=bot.delete_message,
                                        args=(chat_id, i))
            thread.start()
            thread_list[i] = thread

        time.sleep(10)  # Wait for 10 seconds

        for i, thread in thread_list.items():
            if not thread.is_alive():  # Thread finished
                result = thread.join()
                if i > latest_deleted_message_id:
                    latest_deleted_message_id = i

        # Save latest deleted message into `Chat` table
        response = dynamodb_client.update_item(
            TableName='telegram-auto-clear-bot-chats',
            Key={'chat_id': {
                'S': str(chat_id)
            }},
            ExpressionAttributeValues={
                ":latest_deleted_message_id": {
                    "N": str(latest_deleted_message_id)
                }
            },
            UpdateExpression=
            'SET last_deleted_message_id = :latest_deleted_message_id')

    # Get next clear time
    now = datetime.datetime.now()
    next_clear_time = now + datetime.timedelta(
        minutes=clear_message_interval)  # certain minutes later
    next_clear_time_timestamp = int(next_clear_time.timestamp())

    # Save next clear time into `Chat` table
    response = dynamodb_client.update_item(
        TableName='telegram-auto-clear-bot-chats',
        Key={'chat_id': {
            'S': str(chat_id)
        }},
        ExpressionAttributeValues={
            ":next_clear_time_timestamp": {
                "N": str(next_clear_time_timestamp)
            }
        },
        UpdateExpression='SET next_clear_time = :next_clear_time_timestamp')

    return
Example #24
0
    def __init__(self,
                 token=None,
                 base_url=None,
                 workers=4,
                 bot=None,
                 private_key=None,
                 private_key_password=None,
                 user_sig_handler=None,
                 request_kwargs=None,
                 persistence=None,
                 use_context=False,
                 dispatcher=None,
                 base_file_url=None):

        if dispatcher is None:
            if (token is None) and (bot is None):
                raise ValueError('`token` or `bot` must be passed')
            if (token is not None) and (bot is not None):
                raise ValueError('`token` and `bot` are mutually exclusive')
            if (private_key is not None) and (bot is not None):
                raise ValueError('`bot` and `private_key` are mutually exclusive')
        else:
            if bot is not None:
                raise ValueError('`dispatcher` and `bot` are mutually exclusive')
            if persistence is not None:
                raise ValueError('`dispatcher` and `persistence` are mutually exclusive')
            if workers is not None:
                raise ValueError('`dispatcher` and `workers` are mutually exclusive')
            if use_context != dispatcher.use_context:
                raise ValueError('`dispatcher` and `use_context` are mutually exclusive')

        self.logger = logging.getLogger(__name__)

        if dispatcher is None:
            con_pool_size = workers + 4

            if bot is not None:
                self.bot = bot
                if bot.request.con_pool_size < con_pool_size:
                    self.logger.warning(
                        'Connection pool of Request object is smaller than optimal value (%s)',
                        con_pool_size)
            else:
                # we need a connection pool the size of:
                # * for each of the workers
                # * 1 for Dispatcher
                # * 1 for polling Updater (even if webhook is used, we can spare a connection)
                # * 1 for JobQueue
                # * 1 for main thread
                if request_kwargs is None:
                    request_kwargs = {}
                if 'con_pool_size' not in request_kwargs:
                    request_kwargs['con_pool_size'] = con_pool_size
                self._request = Request(**request_kwargs)
                self.bot = Bot(token,
                               base_url,
                               base_file_url=base_file_url,
                               request=self._request,
                               private_key=private_key,
                               private_key_password=private_key_password)
            self.update_queue = Queue()
            self.job_queue = JobQueue()
            self.__exception_event = Event()
            self.persistence = persistence
            self.dispatcher = Dispatcher(self.bot,
                                         self.update_queue,
                                         job_queue=self.job_queue,
                                         workers=workers,
                                         exception_event=self.__exception_event,
                                         persistence=persistence,
                                         use_context=use_context)
            self.job_queue.set_dispatcher(self.dispatcher)
        else:
            con_pool_size = dispatcher.workers + 4

            self.bot = dispatcher.bot
            if self.bot.request.con_pool_size < con_pool_size:
                self.logger.warning(
                    'Connection pool of Request object is smaller than optimal value (%s)',
                    con_pool_size)
            self.update_queue = dispatcher.update_queue
            self.__exception_event = dispatcher.exception_event
            self.persistence = dispatcher.persistence
            self.job_queue = dispatcher.job_queue
            self.dispatcher = dispatcher

        self.user_sig_handler = user_sig_handler
        self.last_update_id = 0
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []
Example #25
0
class Updater(object):
    """
    This class, which employs the Dispatcher class, provides a frontend to
    telegram.Bot to the programmer, so they can focus on coding the bot. Its
    purpose is to receive the updates from Telegram and to deliver them to said
    dispatcher. It also runs in a separate thread, so the user can interact
    with the bot, for example on the command line. The dispatcher supports
    handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types.
    The updater can be started as a polling service or, for production, use a
    webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:

    Args:
        token (Optional[str]): The bot's token given by the @BotFather
        base_url (Optional[str]):
        workers (Optional[int]): Amount of threads in the thread pool for
            functions decorated with @run_async
        bot (Optional[Bot]): A pre-initialized bot instance. If a pre-initizlied bot is used, it is
            the user's responsibility to create it using a `Request` instance with a large enough
            connection pool.
        job_queue_tick_interval(Optional[float]): The interval the queue should
            be checked for new tasks. Defaults to 1.0

    Raises:
        ValueError: If both `token` and `bot` are passed or none of them.

    """
    _request = None

    def __init__(self, token=None, base_url=None, workers=4, bot=None):
        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        if bot is not None:
            self.bot = bot
        else:
            # we need a connection pool the size of:
            # * for each of the workers
            # * 1 for Dispatcher
            # * 1 for polling Updater (even if webhook is used, we can spare a connection)
            # * 1 for JobQueue
            # * 1 for main thread
            self._request = Request(con_pool_size=workers + 4)
            self.bot = Bot(token, base_url, request=self._request)
        self.update_queue = Queue()
        self.job_queue = JobQueue(self.bot)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(self.bot,
                                     self.update_queue,
                                     job_queue=self.job_queue,
                                     workers=workers,
                                     exception_event=self.__exception_event)
        self.last_update_id = 0
        self.logger = logging.getLogger(__name__)
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []
        """:type: list[Thread]"""

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper,
                     name=name,
                     args=(target, ) + args,
                     kwargs=kwargs)
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target, *args, **kwargs):
        thr_name = current_thread().name
        self.logger.debug('{0} - started'.format(thr_name))
        try:
            target(*args, **kwargs)
        except Exception:
            self.__exception_event.set()
            self.logger.exception('unhandled exception')
            raise
        self.logger.debug('{0} - ended'.format(thr_name))

    def start_polling(self,
                      poll_interval=0.0,
                      timeout=10,
                      network_delay=5.,
                      clean=False,
                      bootstrap_retries=0):
        """
        Starts polling updates from Telegram.

        Args:
            poll_interval (Optional[float]): Time to wait between polling updates from Telegram in
            seconds. Default is 0.0

            timeout (Optional[float]): Passed to Bot.getUpdates

            network_delay (Optional[float]): Passed to Bot.getUpdates

            clean (Optional[bool]): Whether to clean any pending updates on Telegram servers before
              actually starting to poll. Default is False.

            bootstrap_retries (Optional[int]): Whether the bootstrapping phase of the `Updater`
              will retry on failures on the Telegram server.

                |   < 0 - retry indefinitely
                |   0 - no retries (default)
                |   > 0 - retry up to X times

        Returns:
            Queue: The update queue that can be filled from the main thread

        """
        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self.job_queue.start()
                self._init_thread(self.dispatcher.start, "dispatcher")
                self._init_thread(self._start_polling, "updater",
                                  poll_interval, timeout, network_delay,
                                  bootstrap_retries, clean)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def start_webhook(self,
                      listen='127.0.0.1',
                      port=80,
                      url_path='',
                      cert=None,
                      key=None,
                      clean=False,
                      bootstrap_retries=0,
                      webhook_url=None):
        """
        Starts a small http server to listen for updates via webhook. If cert
        and key are not provided, the webhook will be started directly on
        http://listen:port/url_path, so SSL can be handled by another
        application. Else, the webhook will be started on
        https://listen:port/url_path

        Args:
            listen (Optional[str]): IP-Address to listen on
            port (Optional[int]): Port the bot should be listening on
            url_path (Optional[str]): Path inside url
            cert (Optional[str]): Path to the SSL certificate file
            key (Optional[str]): Path to the SSL key file
            clean (Optional[bool]): Whether to clean any pending updates on
                Telegram servers before actually starting the webhook. Default
                is False.
            bootstrap_retries (Optional[int[): Whether the bootstrapping phase
                of the `Updater` will retry on failures on the Telegram server.

                |   < 0 - retry indefinitely
                |   0 - no retries (default)
                |   > 0 - retry up to X times
            webhook_url (Optional[str]): Explicitly specifiy the webhook url.
                Useful behind NAT, reverse proxy, etc. Default is derived from
                `listen`, `port` & `url_path`.

        Returns:
            Queue: The update queue that can be filled from the main thread

        """
        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self.job_queue.start()
                self._init_thread(self.dispatcher.start, "dispatcher"),
                self._init_thread(self._start_webhook, "updater", listen, port,
                                  url_path, cert, key, bootstrap_retries,
                                  clean, webhook_url)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def _start_polling(self, poll_interval, timeout, network_delay,
                       bootstrap_retries, clean):
        """
        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='')

        while self.running:
            try:
                updates = self.bot.getUpdates(self.last_update_id,
                                              timeout=timeout,
                                              network_delay=network_delay)
            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)

    @staticmethod
    def _increase_poll_interval(current_interval):
        # increase waiting times on subsequent errors up to 30secs
        if current_interval == 0:
            current_interval = 1
        elif current_interval < 30:
            current_interval += current_interval / 2
        elif current_interval > 30:
            current_interval = 30
        return current_interval

    def _start_webhook(self, listen, port, url_path, cert, key,
                       bootstrap_retries, clean, webhook_url):
        self.logger.debug('Updater thread started')
        use_ssl = cert is not None and key is not None
        if not url_path.startswith('/'):
            url_path = '/{0}'.format(url_path)

        # Create and start server
        self.httpd = WebhookServer((listen, port), WebhookHandler,
                                   self.update_queue, url_path, self.bot)

        if use_ssl:
            self._check_ssl_cert(cert, key)

            # DO NOT CHANGE: Only set webhook if SSL is handled by library
            if not webhook_url:
                webhook_url = self._gen_webhook_url(listen, port, url_path)

            self._bootstrap(max_retries=bootstrap_retries,
                            clean=clean,
                            webhook_url=webhook_url,
                            cert=open(cert, 'rb'))
        elif clean:
            self.logger.warning("cleaning updates is not supported if "
                                "SSL-termination happens elsewhere; skipping")

        self.httpd.serve_forever(poll_interval=1)

    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')

    @staticmethod
    def _gen_webhook_url(listen, port, url_path):
        return 'https://{listen}:{port}{path}'.format(listen=listen,
                                                      port=port,
                                                      path=url_path)

    def _bootstrap(self, max_retries, clean, webhook_url, cert=None):
        retries = 0
        while 1:

            try:
                if clean:
                    # Disable webhook for cleaning
                    self.bot.setWebhook(webhook_url='')
                    self._clean_updates()

                self.bot.setWebhook(webhook_url=webhook_url, certificate=cert)
            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)

    def _clean_updates(self):
        self.logger.debug('Cleaning updates from Telegram server')
        updates = self.bot.getUpdates()
        while updates:
            updates = self.bot.getUpdates(updates[-1].update_id + 1)

    def stop(self):
        """
        Stops the polling/webhook thread, the dispatcher and the job queue
        """

        self.job_queue.stop()
        with self.__lock:
            if self.running or self.dispatcher.has_running_threads:
                self.logger.debug('Stopping Updater and Dispatcher...')

                self.running = False

                self._stop_httpd()
                self._stop_dispatcher()
                self._join_threads()

                # Stop the Request instance only if it was created by the Updater
                if self._request:
                    self._request.stop()

    def _stop_httpd(self):
        if self.httpd:
            self.logger.debug(
                'Waiting for current webhook connection to be '
                'closed... Send a Telegram message to the bot to exit '
                'immediately.')
            self.httpd.shutdown()
            self.httpd = None

    def _stop_dispatcher(self):
        self.logger.debug('Requesting Dispatcher to stop...')
        self.dispatcher.stop()

    def _join_threads(self):
        for thr in self.__threads:
            self.logger.debug('Waiting for {0} thread to end'.format(thr.name))
            thr.join()
            self.logger.debug('{0} thread has ended'.format(thr.name))
        self.__threads = []

    def signal_handler(self, signum, frame):
        self.is_idle = False
        if self.running:
            self.stop()
        else:
            self.logger.warning('Exiting immediately!')
            import os
            os._exit(1)

    def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
        """
        Blocks until one of the signals are received and stops the updater

        Args:
            stop_signals: Iterable containing signals from the signal module
                that should be subscribed to. Updater.stop() will be called on
                receiving one of those signals. Defaults to (SIGINT, SIGTERM,
                SIGABRT)
        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
Example #26
0
class Updater(object):
    """
    This class, which employs the :class:`telegram.ext.Dispatcher`, provides a frontend to
    :class:`telegram.Bot` to the programmer, so they can focus on coding the bot. Its purpose is to
    receive the updates from Telegram and to deliver them to said dispatcher. It also runs in a
    separate thread, so the user can interact with the bot, for example on the command line. The
    dispatcher supports handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types. The updater can be started as a polling service or, for
    production, use a webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:
        bot (:class:`telegram.Bot`): The bot used with this Updater.
        user_sig_handler (:obj:`signal`): signals the updater will respond to.
        update_queue (:obj:`Queue`): Queue for the updates.
        job_queue (:class:`telegram.ext.JobQueue`): Jobqueue for the updater.
        dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that handles the updates and
            dispatches them to the handlers.
        running (:obj:`bool`): Indicates if the updater is running.

    Args:
        token (:obj:`str`, optional): The bot's token given by the @BotFather.
        base_url (:obj:`str`, optional): Base_url for the bot.
        workers (:obj:`int`, optional): Amount of threads in the thread pool for functions
            decorated with ``@run_async``.
        bot (:class:`telegram.Bot`, optional): A pre-initialized bot instance. If a pre-initialized
            bot is used, it is the user's responsibility to create it using a `Request`
            instance with a large enough connection pool.
        user_sig_handler (:obj:`function`, optional): Takes ``signum, frame`` as positional
            arguments. This will be called when a signal is received, defaults are (SIGINT,
            SIGTERM, SIGABRT) setable with :attr:`idle`.
        request_kwargs (:obj:`dict`, optional): Keyword args to control the creation of a
            `telegram.utils.request.Request` object (ignored if `bot` argument is used). The
            request_kwargs are very useful for the advanced users who would like to control the
            default timeouts and/or control the proxy used for http communication.

    Note:
        You must supply either a :attr:`bot` or a :attr:`token` argument.

    Raises:
        ValueError: If both :attr:`token` and :attr:`bot` are passed or none of them.

    """

    _request = None

    def __init__(self,
                 token=None,
                 base_url=None,
                 workers=4,
                 bot=None,
                 user_sig_handler=None,
                 request_kwargs=None):

        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        self.logger = logging.getLogger(__name__)

        con_pool_size = workers + 4

        if bot is not None:
            self.bot = bot
            if bot.request.con_pool_size < con_pool_size:
                self.logger.warning(
                    'Connection pool of Request object is smaller than optimal value (%s)',
                    con_pool_size)
        else:
            # we need a connection pool the size of:
            # * for each of the workers
            # * 1 for Dispatcher
            # * 1 for polling Updater (even if webhook is used, we can spare a connection)
            # * 1 for JobQueue
            # * 1 for main thread
            if request_kwargs is None:
                request_kwargs = {}
            if 'con_pool_size' not in request_kwargs:
                request_kwargs['con_pool_size'] = con_pool_size
            self._request = Request(**request_kwargs)
            self.bot = Bot(token, base_url, request=self._request)
        self.user_sig_handler = user_sig_handler
        self.update_queue = Queue()
        self.job_queue = JobQueue(self.bot)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(
            self.bot,
            self.update_queue,
            job_queue=self.job_queue,
            workers=workers,
            exception_event=self.__exception_event)
        self.last_update_id = 0
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper, name=name, args=(target,) + args, kwargs=kwargs)
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target, *args, **kwargs):
        thr_name = current_thread().name
        self.logger.debug('{0} - started'.format(thr_name))
        try:
            target(*args, **kwargs)
        except Exception:
            self.__exception_event.set()
            self.logger.exception('unhandled exception')
            raise
        self.logger.debug('{0} - ended'.format(thr_name))

    def start_polling(self,
                      poll_interval=0.0,
                      timeout=10,
                      network_delay=None,
                      clean=False,
                      bootstrap_retries=0,
                      read_latency=2.,
                      allowed_updates=None):
        """Starts polling updates from Telegram.

        Args:
            poll_interval (:obj:`float`, optional): Time to wait between polling updates from
                Telegram in seconds. Default is 0.0.
            timeout (:obj:`float`, optional): Passed to :attr:`telegram.Bot.get_updates`.
            clean (:obj:`bool`, optional): Whether to clean any pending updates on Telegram servers
                before actually starting to poll. Default is False.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                `Updater` will retry on failures on the Telegram server.

                * < 0 - retry indefinitely
                *   0 - no retries (default)
                * > 0 - retry up to X times

            allowed_updates (List[:obj:`str`], optional): Passed to
                :attr:`telegram.Bot.get_updates`.
            read_latency (:obj:`float` | :obj:`int`, optional): Grace time in seconds for receiving
                the reply from server. Will be added to the `timeout` value and used as the read
                timeout from server (Default: 2).
            network_delay: Deprecated. Will be honoured as :attr:`read_latency` for a while but
                will be removed in the future.

        Returns:
            :obj:`Queue`: The update queue that can be filled from the main thread.

        """

        if network_delay is not None:
            warnings.warn('network_delay is deprecated, use read_latency instead')
            read_latency = network_delay

        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self.job_queue.start()
                self._init_thread(self.dispatcher.start, "dispatcher")
                self._init_thread(self._start_polling, "updater", poll_interval, timeout,
                                  read_latency, bootstrap_retries, clean, allowed_updates)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def start_webhook(self,
                      listen='127.0.0.1',
                      port=80,
                      url_path='',
                      cert=None,
                      key=None,
                      clean=False,
                      bootstrap_retries=0,
                      webhook_url=None,
                      allowed_updates=None):
        """
        Starts a small http server to listen for updates via webhook. If cert
        and key are not provided, the webhook will be started directly on
        http://listen:port/url_path, so SSL can be handled by another
        application. Else, the webhook will be started on
        https://listen:port/url_path

        Args:
            listen (:obj:`str`, optional): IP-Address to listen on. Default ``127.0.0.1``.
            port (:obj:`int`, optional): Port the bot should be listening on. Default ``80``.
            url_path (:obj:`str`, optional): Path inside url.
            cert (:obj:`str`, optional): Path to the SSL certificate file.
            key (:obj:`str`, optional): Path to the SSL key file.
            clean (:obj:`bool`, optional): Whether to clean any pending updates on Telegram servers
                before actually starting the webhook. Default is ``False``.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                `Updater` will retry on failures on the Telegram server.

                * < 0 - retry indefinitely
                *   0 - no retries (default)
                * > 0 - retry up to X times

            webhook_url (:obj:`str`, optional): Explicitly specify the webhook url. Useful behind
                NAT, reverse proxy, etc. Default is derived from `listen`, `port` & `url_path`.
            allowed_updates (List[:obj:`str`], optional): Passed to
                :attr:`telegram.Bot.set_webhook`.

        Returns:
            :obj:`Queue`: The update queue that can be filled from the main thread.

        """

        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self.job_queue.start()
                self._init_thread(self.dispatcher.start, "dispatcher"),
                self._init_thread(self._start_webhook, "updater", listen, port, url_path, cert,
                                  key, bootstrap_retries, clean, webhook_url, allowed_updates)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    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)

    @staticmethod
    def _increase_poll_interval(current_interval):
        # increase waiting times on subsequent errors up to 30secs
        if current_interval == 0:
            current_interval = 1
        elif current_interval < 30:
            current_interval += current_interval / 2
        elif current_interval > 30:
            current_interval = 30
        return current_interval

    def _start_webhook(self, listen, port, url_path, cert, key, bootstrap_retries, clean,
                       webhook_url, allowed_updates):
        self.logger.debug('Updater thread started')
        use_ssl = cert is not None and key is not None
        if not url_path.startswith('/'):
            url_path = '/{0}'.format(url_path)

        # Create and start server
        self.httpd = WebhookServer((listen, port), WebhookHandler, self.update_queue, url_path,
                                   self.bot)

        if use_ssl:
            self._check_ssl_cert(cert, key)

            # DO NOT CHANGE: Only set webhook if SSL is handled by library
            if not webhook_url:
                webhook_url = self._gen_webhook_url(listen, port, url_path)

            self._bootstrap(
                max_retries=bootstrap_retries,
                clean=clean,
                webhook_url=webhook_url,
                cert=open(cert, 'rb'),
                allowed_updates=allowed_updates)
        elif clean:
            self.logger.warning("cleaning updates is not supported if "
                                "SSL-termination happens elsewhere; skipping")

        self.httpd.serve_forever(poll_interval=1)

    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')

    @staticmethod
    def _gen_webhook_url(listen, port, url_path):
        return 'https://{listen}:{port}{path}'.format(listen=listen, port=port, path=url_path)

    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)

    def _clean_updates(self):
        self.logger.debug('Cleaning updates from Telegram server')
        updates = self.bot.get_updates()
        while updates:
            updates = self.bot.get_updates(updates[-1].update_id + 1)

    def stop(self):
        """Stops the polling/webhook thread, the dispatcher and the job queue."""

        self.job_queue.stop()
        with self.__lock:
            if self.running or self.dispatcher.has_running_threads:
                self.logger.debug('Stopping Updater and Dispatcher...')

                self.running = False

                self._stop_httpd()
                self._stop_dispatcher()
                self._join_threads()

                # Stop the Request instance only if it was created by the Updater
                if self._request:
                    self._request.stop()

    def _stop_httpd(self):
        if self.httpd:
            self.logger.debug('Waiting for current webhook connection to be '
                              'closed... Send a Telegram message to the bot to exit '
                              'immediately.')
            self.httpd.shutdown()
            self.httpd = None

    def _stop_dispatcher(self):
        self.logger.debug('Requesting Dispatcher to stop...')
        self.dispatcher.stop()

    def _join_threads(self):
        for thr in self.__threads:
            self.logger.debug('Waiting for {0} thread to end'.format(thr.name))
            thr.join()
            self.logger.debug('{0} thread has ended'.format(thr.name))
        self.__threads = []

    def signal_handler(self, signum, frame):
        self.is_idle = False
        if self.running:
            self.stop()
            if self.user_sig_handler:
                self.user_sig_handler(signum, frame)
        else:
            self.logger.warning('Exiting immediately!')
            import os
            os._exit(1)

    def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
        """Blocks until one of the signals are received and stops the updater.

        Args:
            stop_signals (:obj:`iterable`): Iterable containing signals from the signal module that
                should be subscribed to. Updater.stop() will be called on receiving one of those
                signals. Defaults to (``SIGINT``, ``SIGTERM``, ``SIGABRT``).

        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
Example #27
0
class Updater(object):
    """
    This class, which employs the :class:`telegram.ext.Dispatcher`, provides a frontend to
    :class:`telegram.Bot` to the programmer, so they can focus on coding the bot. Its purpose is to
    receive the updates from Telegram and to deliver them to said dispatcher. It also runs in a
    separate thread, so the user can interact with the bot, for example on the command line. The
    dispatcher supports handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types. The updater can be started as a polling service or, for
    production, use a webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.


    Attributes:
        bot (:class:`telegram.Bot`): The bot used with this Updater.
        user_sig_handler (:obj:`signal`): signals the updater will respond to.
        update_queue (:obj:`Queue`): Queue for the updates.
        job_queue (:class:`telegram.ext.JobQueue`): Jobqueue for the updater.
        dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that handles the updates and
            dispatches them to the handlers.
        running (:obj:`bool`): Indicates if the updater is running.

    Args:
        token (:obj:`str`, optional): The bot's token given by the @BotFather.
        base_url (:obj:`str`, optional): Base_url for the bot.
        workers (:obj:`int`, optional): Amount of threads in the thread pool for functions
            decorated with ``@run_async``.
        bot (:class:`telegram.Bot`, optional): A pre-initialized bot instance. If a pre-initialized
            bot is used, it is the user's responsibility to create it using a `Request`
            instance with a large enough connection pool.
        user_sig_handler (:obj:`function`, optional): Takes ``signum, frame`` as positional
            arguments. This will be called when a signal is received, defaults are (SIGINT,
            SIGTERM, SIGABRT) setable with :attr:`idle`.
        request_kwargs (:obj:`dict`, optional): Keyword args to control the creation of a request
            object (ignored if `bot` argument is used).

    Note:
        You must supply either a :attr:`bot` or a :attr:`token` argument.

    Raises:
        ValueError: If both :attr:`token` and :attr:`bot` are passed or none of them.

    """

    _request = None

    def __init__(self,
                 token=None,
                 base_url=None,
                 workers=4,
                 bot=None,
                 user_sig_handler=None,
                 request_kwargs=None):

        if (token is None) and (bot is None):
            raise ValueError('`token` or `bot` must be passed')
        if (token is not None) and (bot is not None):
            raise ValueError('`token` and `bot` are mutually exclusive')

        self.logger = logging.getLogger(__name__)

        con_pool_size = workers + 4

        if bot is not None:
            self.bot = bot
            if bot.request.con_pool_size < con_pool_size:
                self.logger.warning(
                    'Connection pool of Request object is smaller than optimal value (%s)',
                    con_pool_size)
        else:
            # we need a connection pool the size of:
            # * for each of the workers
            # * 1 for Dispatcher
            # * 1 for polling Updater (even if webhook is used, we can spare a connection)
            # * 1 for JobQueue
            # * 1 for main thread
            if request_kwargs is None:
                request_kwargs = {}
            if 'con_pool_size' not in request_kwargs:
                request_kwargs['con_pool_size'] = con_pool_size
            self._request = Request(**request_kwargs)
            self.bot = Bot(token, base_url, request=self._request)
        self.user_sig_handler = user_sig_handler
        self.update_queue = Queue()
        self.job_queue = JobQueue(self.bot)
        self.__exception_event = Event()
        self.dispatcher = Dispatcher(
            self.bot,
            self.update_queue,
            job_queue=self.job_queue,
            workers=workers,
            exception_event=self.__exception_event)
        self.last_update_id = 0
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads = []

    def _init_thread(self, target, name, *args, **kwargs):
        thr = Thread(target=self._thread_wrapper, name=name, args=(target,) + args, kwargs=kwargs)
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target, *args, **kwargs):
        thr_name = current_thread().name
        self.logger.debug('{0} - started'.format(thr_name))
        try:
            target(*args, **kwargs)
        except Exception:
            self.__exception_event.set()
            self.logger.exception('unhandled exception')
            raise
        self.logger.debug('{0} - ended'.format(thr_name))

    def start_polling(self,
                      poll_interval=0.0,
                      timeout=10,
                      network_delay=None,
                      clean=False,
                      bootstrap_retries=0,
                      read_latency=2.,
                      allowed_updates=None):
        """Starts polling updates from Telegram.

        Args:
            poll_interval (:obj:`float`, optional): Time to wait between polling updates from
                Telegram in seconds. Default is 0.0.
            timeout (:obj:`float`, optional): Passed to :attr:`telegram.Bot.get_updates`.
            clean (:obj:`bool`, optional): Whether to clean any pending updates on Telegram servers
                before actually starting to poll. Default is False.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                `Updater` will retry on failures on the Telegram server.

                * < 0 - retry indefinitely
                *   0 - no retries (default)
                * > 0 - retry up to X times

            allowed_updates (List[:obj:`str`], optional): Passed to
                :attr:`telegram.Bot.get_updates`.
            read_latency (:obj:`float` | :obj:`int`, optional): Grace time in seconds for receiving
                the reply from server. Will be added to the `timeout` value and used as the read
                timeout from server (Default: 2).
            network_delay: Deprecated. Will be honoured as :attr:`read_latency` for a while but
                will be removed in the future.

        Returns:
            :obj:`Queue`: The update queue that can be filled from the main thread.

        """

        if network_delay is not None:
            warnings.warn('network_delay is deprecated, use read_latency instead')
            read_latency = network_delay

        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self.job_queue.start()
                self._init_thread(self.dispatcher.start, "dispatcher")
                self._init_thread(self._start_polling, "updater", poll_interval, timeout,
                                  read_latency, bootstrap_retries, clean, allowed_updates)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def start_webhook(self,
                      listen='127.0.0.1',
                      port=80,
                      url_path='',
                      cert=None,
                      key=None,
                      clean=False,
                      bootstrap_retries=0,
                      webhook_url=None,
                      allowed_updates=None):
        """
        Starts a small http server to listen for updates via webhook. If cert
        and key are not provided, the webhook will be started directly on
        http://listen:port/url_path, so SSL can be handled by another
        application. Else, the webhook will be started on
        https://listen:port/url_path

        Args:
            listen (:obj:`str`, optional): IP-Address to listen on. Default ``127.0.0.1``.
            port (:obj:`int`, optional): Port the bot should be listening on. Default ``80``.
            url_path (:obj:`str`, optional): Path inside url.
            cert (:obj:`str`, optional): Path to the SSL certificate file.
            key (:obj:`str`, optional): Path to the SSL key file.
            clean (:obj:`bool`, optional): Whether to clean any pending updates on Telegram servers
                before actually starting the webhook. Default is ``False``.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                `Updater` will retry on failures on the Telegram server.

                * < 0 - retry indefinitely
                *   0 - no retries (default)
                * > 0 - retry up to X times

            webhook_url (:obj:`str`, optional): Explicitly specify the webhook url. Useful behind
                NAT, reverse proxy, etc. Default is derived from `listen`, `port` & `url_path`.
            allowed_updates (List[:obj:`str`], optional): Passed to
                :attr:`telegram.Bot.set_webhook`.

        Returns:
            :obj:`Queue`: The update queue that can be filled from the main thread.

        """

        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self.job_queue.start()
                self._init_thread(self.dispatcher.start, "dispatcher"),
                self._init_thread(self._start_webhook, "updater", listen, port, url_path, cert,
                                  key, bootstrap_retries, clean, webhook_url, allowed_updates)

                # Return the update queue so the main thread can insert updates
                return self.update_queue

    def _start_polling(self, poll_interval, timeout, read_latency, bootstrap_retries, clean,
                       allowed_updates):
        # """
        # 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)

    @staticmethod
    def _increase_poll_interval(current_interval):
        # increase waiting times on subsequent errors up to 30secs
        if current_interval == 0:
            current_interval = 1
        elif current_interval < 30:
            current_interval += current_interval / 2
        elif current_interval > 30:
            current_interval = 30
        return current_interval

    def _start_webhook(self, listen, port, url_path, cert, key, bootstrap_retries, clean,
                       webhook_url, allowed_updates):
        self.logger.debug('Updater thread started')
        use_ssl = cert is not None and key is not None
        if not url_path.startswith('/'):
            url_path = '/{0}'.format(url_path)

        # Create and start server
        self.httpd = WebhookServer((listen, port), WebhookHandler, self.update_queue, url_path,
                                   self.bot)

        if use_ssl:
            self._check_ssl_cert(cert, key)

            # DO NOT CHANGE: Only set webhook if SSL is handled by library
            if not webhook_url:
                webhook_url = self._gen_webhook_url(listen, port, url_path)

            self._bootstrap(
                max_retries=bootstrap_retries,
                clean=clean,
                webhook_url=webhook_url,
                cert=open(cert, 'rb'),
                allowed_updates=allowed_updates)
        elif clean:
            self.logger.warning("cleaning updates is not supported if "
                                "SSL-termination happens elsewhere; skipping")

        self.httpd.serve_forever(poll_interval=1)

    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')

    @staticmethod
    def _gen_webhook_url(listen, port, url_path):
        return 'https://{listen}:{port}{path}'.format(listen=listen, port=port, path=url_path)

    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)

    def _clean_updates(self):
        self.logger.debug('Cleaning updates from Telegram server')
        updates = self.bot.get_updates()
        while updates:
            updates = self.bot.get_updates(updates[-1].update_id + 1)

    def stop(self):
        """Stops the polling/webhook thread, the dispatcher and the job queue."""

        self.job_queue.stop()
        with self.__lock:
            if self.running or self.dispatcher.has_running_threads:
                self.logger.debug('Stopping Updater and Dispatcher...')

                self.running = False

                self._stop_httpd()
                self._stop_dispatcher()
                self._join_threads()

                # Stop the Request instance only if it was created by the Updater
                if self._request:
                    self._request.stop()

    def _stop_httpd(self):
        if self.httpd:
            self.logger.debug('Waiting for current webhook connection to be '
                              'closed... Send a Telegram message to the bot to exit '
                              'immediately.')
            self.httpd.shutdown()
            self.httpd = None

    def _stop_dispatcher(self):
        self.logger.debug('Requesting Dispatcher to stop...')
        self.dispatcher.stop()

    def _join_threads(self):
        for thr in self.__threads:
            self.logger.debug('Waiting for {0} thread to end'.format(thr.name))
            thr.join()
            self.logger.debug('{0} thread has ended'.format(thr.name))
        self.__threads = []

    def signal_handler(self, signum, frame):
        self.is_idle = False
        if self.running:
            self.stop()
            if self.user_sig_handler:
                self.user_sig_handler(signum, frame)
        else:
            self.logger.warning('Exiting immediately!')
            import os
            os._exit(1)

    def idle(self, stop_signals=(SIGINT, SIGTERM, SIGABRT)):
        """Blocks until one of the signals are received and stops the updater.

        Args:
            stop_signals (:obj:`iterable`): Iterable containing signals from the signal module that
                should be subscribed to. Updater.stop() will be called on receiving one of those
                signals. Defaults to (``SIGINT``, ``SIGTERM``, ``SIGABRT``).

        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
Example #28
0
def main():
    '''Setting up all needed to launch bot'''
    logger.info('Started')

    req = Request(
        connect_timeout=30.0,
        read_timeout=1.0,
        con_pool_size=8,
    )
    bot = Bot(
        token=TOKEN,
        request=req,
    )
    updater = Updater(
        bot=bot,
        use_context=True,
    )

    # Проверить что бот корректно подключился к Telegram API
    info = bot.get_me()
    logger.info('Bot info: %s', info)

    # Навесить обработчики команд
    conv_handler = ConversationHandler(
        entry_points=[
            CommandHandler('start', start_buttons_handler),
        ],
        states={
            NAME: [
                CallbackQueryHandler(name_handler, pass_user_data=True),
            ],
            NICHE: [
                MessageHandler(Filters.all, niche_handler,
                               pass_user_data=True),
            ],
            VERTICAL: [
                CallbackQueryHandler(vertical_handler, pass_user_data=True),
            ],
            GEO: [
                CallbackQueryHandler(geo_handler, pass_user_data=True),
            ],
            SPEND: [
                CallbackQueryHandler(spend_handler, pass_user_data=True),
            ],
            CASES: [
                CallbackQueryHandler(cases_handler, pass_user_data=True),
            ],
            CASE_DETAILS: [
                CallbackQueryHandler(case_details_handler,
                                     pass_user_data=True),
            ],
            FINISH: [
                CallbackQueryHandler(finish_handler, pass_user_data=True),
                MessageHandler(Filters.all,
                               finish_handler,
                               pass_user_data=True),
            ]
        },
        fallbacks=[
            CommandHandler('cancel', cancel_handler),
        ],
    )
    updater.dispatcher.add_handler(conv_handler)
    updater.dispatcher.add_handler(MessageHandler(Filters.all, echo_handler))

    if MODE == "dev":
        updater.start_polling()
        updater.idle()
        logger.info('Stopped')
    elif MODE == "prod":
        updater.start_webhook(listen="0.0.0.0", port=PORT, url_path=TOKEN)
        updater.bot.set_webhook("https://{}.herokuapp.com/{}".format(
            HEROKU_APP_NAME, TOKEN))
Example #29
0
 def __init__(self, token, *, proxy_url, **kwargs):
     request = Request(proxy_url=proxy_url)
     self.bot = Bot(token, request=request)
Example #30
0
class Updater:
    """
    This class, which employs the :class:`telegram.ext.Dispatcher`, provides a frontend to
    :class:`telegram.Bot` to the programmer, so they can focus on coding the bot. Its purpose is to
    receive the updates from Telegram and to deliver them to said dispatcher. It also runs in a
    separate thread, so the user can interact with the bot, for example on the command line. The
    dispatcher supports handlers for different kinds of data: Updates from Telegram, basic text
    commands and even arbitrary types. The updater can be started as a polling service or, for
    production, use a webhook to receive updates. This is achieved using the WebhookServer and
    WebhookHandler classes.

    Note:
        * You must supply either a :attr:`bot` or a :attr:`token` argument.
        * If you supply a :attr:`bot`, you will need to pass :attr:`defaults` to *both* the bot and
          the :class:`telegram.ext.Updater`.

    Args:
        token (:obj:`str`, optional): The bot's token given by the @BotFather.
        base_url (:obj:`str`, optional): Base_url for the bot.
        base_file_url (:obj:`str`, optional): Base_file_url for the bot.
        workers (:obj:`int`, optional): Amount of threads in the thread pool for functions
            decorated with ``@run_async`` (ignored if `dispatcher` argument is used).
        bot (:class:`telegram.Bot`, optional): A pre-initialized bot instance (ignored if
            `dispatcher` argument is used). If a pre-initialized bot is used, it is the user's
            responsibility to create it using a `Request` instance with a large enough connection
            pool.
        dispatcher (:class:`telegram.ext.Dispatcher`, optional): A pre-initialized dispatcher
            instance. If a pre-initialized dispatcher is used, it is the user's responsibility to
            create it with proper arguments.
        private_key (:obj:`bytes`, optional): Private key for decryption of telegram passport data.
        private_key_password (:obj:`bytes`, optional): Password for above private key.
        user_sig_handler (:obj:`function`, optional): Takes ``signum, frame`` as positional
            arguments. This will be called when a signal is received, defaults are (SIGINT,
            SIGTERM, SIGABRT) settable with :attr:`idle`.
        request_kwargs (:obj:`dict`, optional): Keyword args to control the creation of a
            `telegram.utils.request.Request` object (ignored if `bot` or `dispatcher` argument is
            used). The request_kwargs are very useful for the advanced users who would like to
            control the default timeouts and/or control the proxy used for http communication.
        use_context (:obj:`bool`, optional): If set to :obj:`True` uses the context based callback
            API (ignored if `dispatcher` argument is used). Defaults to :obj:`True`.
            **New users**: set this to :obj:`True`.
        persistence (:class:`telegram.ext.BasePersistence`, optional): The persistence class to
            store data that should be persistent over restarts (ignored if `dispatcher` argument is
            used).
        defaults (:class:`telegram.ext.Defaults`, optional): An object containing default values to
            be used if not set explicitly in the bot methods.

    Raises:
        ValueError: If both :attr:`token` and :attr:`bot` are passed or none of them.


    Attributes:
        bot (:class:`telegram.Bot`): The bot used with this Updater.
        user_sig_handler (:obj:`function`): Optional. Function to be called when a signal is
            received.
        update_queue (:obj:`Queue`): Queue for the updates.
        job_queue (:class:`telegram.ext.JobQueue`): Jobqueue for the updater.
        dispatcher (:class:`telegram.ext.Dispatcher`): Dispatcher that handles the updates and
            dispatches them to the handlers.
        running (:obj:`bool`): Indicates if the updater is running.
        persistence (:class:`telegram.ext.BasePersistence`): Optional. The persistence class to
            store data that should be persistent over restarts.
        use_context (:obj:`bool`): Optional. :obj:`True` if using context based callbacks.

    """

    _request = None

    def __init__(
        self,
        token: str = None,
        base_url: str = None,
        workers: int = 4,
        bot: Bot = None,
        private_key: bytes = None,
        private_key_password: bytes = None,
        user_sig_handler: Callable = None,
        request_kwargs: Dict[str, Any] = None,
        persistence: 'BasePersistence' = None,
        defaults: 'Defaults' = None,
        use_context: bool = True,
        dispatcher: Dispatcher = None,
        base_file_url: str = None,
    ):

        if defaults and bot:
            warnings.warn(
                'Passing defaults to an Updater has no effect when a Bot is passed '
                'as well. Pass them to the Bot instead.',
                TelegramDeprecationWarning,
                stacklevel=2,
            )

        if dispatcher is None:
            if (token is None) and (bot is None):
                raise ValueError('`token` or `bot` must be passed')
            if (token is not None) and (bot is not None):
                raise ValueError('`token` and `bot` are mutually exclusive')
            if (private_key is not None) and (bot is not None):
                raise ValueError(
                    '`bot` and `private_key` are mutually exclusive')
        else:
            if bot is not None:
                raise ValueError(
                    '`dispatcher` and `bot` are mutually exclusive')
            if persistence is not None:
                raise ValueError(
                    '`dispatcher` and `persistence` are mutually exclusive')
            if workers is not None:
                raise ValueError(
                    '`dispatcher` and `workers` are mutually exclusive')
            if use_context != dispatcher.use_context:
                raise ValueError(
                    '`dispatcher` and `use_context` are mutually exclusive')

        self.logger = logging.getLogger(__name__)

        if dispatcher is None:
            con_pool_size = workers + 4

            if bot is not None:
                self.bot = bot
                if bot.request.con_pool_size < con_pool_size:
                    self.logger.warning(
                        'Connection pool of Request object is smaller than optimal value (%s)',
                        con_pool_size,
                    )
            else:
                # we need a connection pool the size of:
                # * for each of the workers
                # * 1 for Dispatcher
                # * 1 for polling Updater (even if webhook is used, we can spare a connection)
                # * 1 for JobQueue
                # * 1 for main thread
                if request_kwargs is None:
                    request_kwargs = {}
                if 'con_pool_size' not in request_kwargs:
                    request_kwargs['con_pool_size'] = con_pool_size
                self._request = Request(**request_kwargs)
                self.bot = Bot(
                    token,  # type: ignore[arg-type]
                    base_url,
                    base_file_url=base_file_url,
                    request=self._request,
                    private_key=private_key,
                    private_key_password=private_key_password,
                    defaults=defaults,
                )
            self.update_queue: Queue = Queue()
            self.job_queue = JobQueue()
            self.__exception_event = Event()
            self.persistence = persistence
            self.dispatcher = Dispatcher(
                self.bot,
                self.update_queue,
                job_queue=self.job_queue,
                workers=workers,
                exception_event=self.__exception_event,
                persistence=persistence,
                use_context=use_context,
            )
            self.job_queue.set_dispatcher(self.dispatcher)
        else:
            con_pool_size = dispatcher.workers + 4

            self.bot = dispatcher.bot
            if self.bot.request.con_pool_size < con_pool_size:
                self.logger.warning(
                    'Connection pool of Request object is smaller than optimal value (%s)',
                    con_pool_size,
                )
            self.update_queue = dispatcher.update_queue
            self.__exception_event = dispatcher.exception_event
            self.persistence = dispatcher.persistence
            self.job_queue = dispatcher.job_queue
            self.dispatcher = dispatcher

        self.user_sig_handler = user_sig_handler
        self.last_update_id = 0
        self.running = False
        self.is_idle = False
        self.httpd = None
        self.__lock = Lock()
        self.__threads: List[Thread] = []

    def _init_thread(self, target: Callable, name: str, *args: object,
                     **kwargs: object) -> None:
        thr = Thread(
            target=self._thread_wrapper,
            name=f"Bot:{self.bot.id}:{name}",
            args=(target, ) + args,
            kwargs=kwargs,
        )
        thr.start()
        self.__threads.append(thr)

    def _thread_wrapper(self, target: Callable, *args: object,
                        **kwargs: object) -> None:
        thr_name = current_thread().name
        self.logger.debug('%s - started', thr_name)
        try:
            target(*args, **kwargs)
        except Exception:
            self.__exception_event.set()
            self.logger.exception('unhandled exception in %s', thr_name)
            raise
        self.logger.debug('%s - ended', thr_name)

    def start_polling(
        self,
        poll_interval: float = 0.0,
        timeout: float = 10,
        clean: bool = None,
        bootstrap_retries: int = -1,
        read_latency: float = 2.0,
        allowed_updates: List[str] = None,
        drop_pending_updates: bool = None,
    ) -> Optional[Queue]:
        """Starts polling updates from Telegram.

        Args:
            poll_interval (:obj:`float`, optional): Time to wait between polling updates from
                Telegram in seconds. Default is ``0.0``.
            timeout (:obj:`float`, optional): Passed to :meth:`telegram.Bot.get_updates`.
            drop_pending_updates (:obj:`bool`, optional): Whether to clean any pending updates on
                Telegram servers before actually starting to poll. Default is :obj:`False`.

                .. versionadded :: 13.4
            clean (:obj:`bool`, optional): Alias for ``drop_pending_updates``.

                .. deprecated:: 13.4
                    Use ``drop_pending_updates`` instead.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                :class:`telegram.ext.Updater` will retry on failures on the Telegram server.

                * < 0 - retry indefinitely (default)
                *   0 - no retries
                * > 0 - retry up to X times

            allowed_updates (List[:obj:`str`], optional): Passed to
                :meth:`telegram.Bot.get_updates`.
            read_latency (:obj:`float` | :obj:`int`, optional): Grace time in seconds for receiving
                the reply from server. Will be added to the ``timeout`` value and used as the read
                timeout from server (Default: ``2``).

        Returns:
            :obj:`Queue`: The update queue that can be filled from the main thread.

        """
        if (clean is not None) and (drop_pending_updates is not None):
            raise TypeError(
                '`clean` and `drop_pending_updates` are mutually exclusive.')

        if clean is not None:
            warnings.warn(
                'The argument `clean` of `start_polling` is deprecated. Please use '
                '`drop_pending_updates` instead.',
                category=TelegramDeprecationWarning,
                stacklevel=2,
            )

        drop_pending_updates = drop_pending_updates if drop_pending_updates is not None else clean

        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                self.job_queue.start()
                dispatcher_ready = Event()
                polling_ready = Event()
                self._init_thread(self.dispatcher.start,
                                  "dispatcher",
                                  ready=dispatcher_ready)
                self._init_thread(
                    self._start_polling,
                    "updater",
                    poll_interval,
                    timeout,
                    read_latency,
                    bootstrap_retries,
                    drop_pending_updates,
                    allowed_updates,
                    ready=polling_ready,
                )

                self.logger.debug(
                    'Waiting for Dispatcher and polling to start')
                dispatcher_ready.wait()
                polling_ready.wait()

                # Return the update queue so the main thread can insert updates
                return self.update_queue
            return None

    def start_webhook(
        self,
        listen: str = '127.0.0.1',
        port: int = 80,
        url_path: str = '',
        cert: str = None,
        key: str = None,
        clean: bool = None,
        bootstrap_retries: int = 0,
        webhook_url: str = None,
        allowed_updates: List[str] = None,
        force_event_loop: bool = None,
        drop_pending_updates: bool = None,
        ip_address: str = None,
    ) -> Optional[Queue]:
        """
        Starts a small http server to listen for updates via webhook. If :attr:`cert`
        and :attr:`key` are not provided, the webhook will be started directly on
        http://listen:port/url_path, so SSL can be handled by another
        application. Else, the webhook will be started on
        https://listen:port/url_path. Also calls :meth:`telegram.Bot.set_webhook` as required.

        .. versionchanged:: 13.4
            :meth:`start_webhook` now *always* calls :meth:`telegram.Bot.set_webhook`, so pass
            ``webhook_url`` instead of calling ``updater.bot.set_webhook(webhook_url)`` manually.

        Args:
            listen (:obj:`str`, optional): IP-Address to listen on. Default ``127.0.0.1``.
            port (:obj:`int`, optional): Port the bot should be listening on. Default ``80``.
            url_path (:obj:`str`, optional): Path inside url.
            cert (:obj:`str`, optional): Path to the SSL certificate file.
            key (:obj:`str`, optional): Path to the SSL key file.
            drop_pending_updates (:obj:`bool`, optional): Whether to clean any pending updates on
                Telegram servers before actually starting to poll. Default is :obj:`False`.

                .. versionadded :: 13.4
            clean (:obj:`bool`, optional): Alias for ``drop_pending_updates``.

                .. deprecated:: 13.4
                    Use ``drop_pending_updates`` instead.
            bootstrap_retries (:obj:`int`, optional): Whether the bootstrapping phase of the
                :class:`telegram.ext.Updater` will retry on failures on the Telegram server.

                * < 0 - retry indefinitely (default)
                *   0 - no retries
                * > 0 - retry up to X times

            webhook_url (:obj:`str`, optional): Explicitly specify the webhook url. Useful behind
                NAT, reverse proxy, etc. Default is derived from ``listen``, ``port`` &
                ``url_path``.
            ip_address (:obj:`str`, optional): Passed to :meth:`telegram.Bot.set_webhook`.

                .. versionadded :: 13.4
            allowed_updates (List[:obj:`str`], optional): Passed to
                :meth:`telegram.Bot.set_webhook`.
            force_event_loop (:obj:`bool`, optional): Legacy parameter formerly used for a
                workaround on Windows + Python 3.8+. No longer has any effect.

                .. deprecated:: 13.6
                   Since version 13.6, ``tornade>=6.1`` is required, which resolves the former
                   issue.

        Returns:
            :obj:`Queue`: The update queue that can be filled from the main thread.

        """
        if (clean is not None) and (drop_pending_updates is not None):
            raise TypeError(
                '`clean` and `drop_pending_updates` are mutually exclusive.')

        if clean is not None:
            warnings.warn(
                'The argument `clean` of `start_webhook` is deprecated. Please use '
                '`drop_pending_updates` instead.',
                category=TelegramDeprecationWarning,
                stacklevel=2,
            )

        if force_event_loop is not None:
            warnings.warn(
                'The argument `force_event_loop` of `start_webhook` is deprecated and no longer '
                'has any effect.',
                category=TelegramDeprecationWarning,
                stacklevel=2,
            )

        drop_pending_updates = drop_pending_updates if drop_pending_updates is not None else clean

        with self.__lock:
            if not self.running:
                self.running = True

                # Create & start threads
                webhook_ready = Event()
                dispatcher_ready = Event()
                self.job_queue.start()
                self._init_thread(self.dispatcher.start, "dispatcher",
                                  dispatcher_ready)
                self._init_thread(
                    self._start_webhook,
                    "updater",
                    listen,
                    port,
                    url_path,
                    cert,
                    key,
                    bootstrap_retries,
                    drop_pending_updates,
                    webhook_url,
                    allowed_updates,
                    ready=webhook_ready,
                    ip_address=ip_address,
                )

                self.logger.debug(
                    'Waiting for Dispatcher and Webhook to start')
                webhook_ready.wait()
                dispatcher_ready.wait()

                # Return the update queue so the main thread can insert updates
                return self.update_queue
            return None

    @no_type_check
    def _start_polling(
        self,
        poll_interval,
        timeout,
        read_latency,
        bootstrap_retries,
        drop_pending_updates,
        allowed_updates,
        ready=None,
    ):  # 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.

        self.logger.debug('Updater thread started (polling)')

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

        self.logger.debug('Bootstrap done')

        def polling_action_cb():
            updates = self.bot.get_updates(
                self.last_update_id,
                timeout=timeout,
                read_latency=read_latency,
                allowed_updates=allowed_updates,
            )

            if updates:
                if not self.running:
                    self.logger.debug(
                        'Updates ignored and will be pulled again on restart')
                else:
                    for update in updates:
                        self.update_queue.put(update)
                    self.last_update_id = updates[-1].update_id + 1

            return True

        def polling_onerr_cb(exc):
            # Put the error into the update queue and let the Dispatcher
            # broadcast it
            self.update_queue.put(exc)

        if ready is not None:
            ready.set()

        self._network_loop_retry(polling_action_cb, polling_onerr_cb,
                                 'getting Updates', poll_interval)

    @no_type_check
    def _network_loop_retry(self, action_cb, onerr_cb, description, interval):
        """Perform a loop calling `action_cb`, retrying after network errors.

        Stop condition for loop: `self.running` evaluates :obj:`False` or return value of
        `action_cb` evaluates :obj:`False`.

        Args:
            action_cb (:obj:`callable`): Network oriented callback function to call.
            onerr_cb (:obj:`callable`): Callback to call when TelegramError is caught. Receives the
                exception object as a parameter.
            description (:obj:`str`): Description text to use for logs and exception raised.
            interval (:obj:`float` | :obj:`int`): Interval to sleep between each call to
                `action_cb`.

        """
        self.logger.debug('Start network loop retry %s', description)
        cur_interval = interval
        while self.running:
            try:
                if not action_cb():
                    break
            except RetryAfter as exc:
                self.logger.info('%s', exc)
                cur_interval = 0.5 + exc.retry_after
            except TimedOut as toe:
                self.logger.debug('Timed out %s: %s', description, toe)
                # If failure is due to timeout, we should retry asap.
                cur_interval = 0
            except InvalidToken as pex:
                self.logger.error('Invalid token; aborting')
                raise pex
            except TelegramError as telegram_exc:
                self.logger.error('Error while %s: %s', description,
                                  telegram_exc)
                onerr_cb(telegram_exc)
                cur_interval = self._increase_poll_interval(cur_interval)
            else:
                cur_interval = interval

            if cur_interval:
                sleep(cur_interval)

    @staticmethod
    def _increase_poll_interval(current_interval: float) -> float:
        # increase waiting times on subsequent errors up to 30secs
        if current_interval == 0:
            current_interval = 1
        elif current_interval < 30:
            current_interval += current_interval / 2
        elif current_interval > 30:
            current_interval = 30
        return current_interval

    @no_type_check
    def _start_webhook(
        self,
        listen,
        port,
        url_path,
        cert,
        key,
        bootstrap_retries,
        drop_pending_updates,
        webhook_url,
        allowed_updates,
        ready=None,
        ip_address=None,
    ):
        self.logger.debug('Updater thread started (webhook)')

        # Note that we only use the SSL certificate for the WebhookServer, if the key is also
        # present. This is because the WebhookServer may not actually be in charge of performing
        # the SSL handshake, e.g. in case a reverse proxy is used
        use_ssl = cert is not None and key is not None

        if not url_path.startswith('/'):
            url_path = f'/{url_path}'

        # Create Tornado app instance
        app = WebhookAppClass(url_path, self.bot, self.update_queue)

        # Form SSL Context
        # An SSLError is raised if the private key does not match with the certificate
        if use_ssl:
            try:
                ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
                ssl_ctx.load_cert_chain(cert, key)
            except ssl.SSLError as exc:
                raise TelegramError('Invalid SSL Certificate') from exc
        else:
            ssl_ctx = None

        # Create and start server
        self.httpd = WebhookServer(listen, port, app, ssl_ctx)

        if not webhook_url:
            webhook_url = self._gen_webhook_url(listen, port, url_path)

        # We pass along the cert to the webhook if present.
        self._bootstrap(
            max_retries=bootstrap_retries,
            drop_pending_updates=drop_pending_updates,
            webhook_url=webhook_url,
            allowed_updates=allowed_updates,
            cert=open(cert, 'rb') if cert is not None else None,
            ip_address=ip_address,
        )

        self.httpd.serve_forever(ready=ready)

    @staticmethod
    def _gen_webhook_url(listen: str, port: int, url_path: str) -> str:
        return f'https://{listen}:{port}{url_path}'

    @no_type_check
    def _bootstrap(
        self,
        max_retries,
        drop_pending_updates,
        webhook_url,
        allowed_updates,
        cert=None,
        bootstrap_interval=5,
        ip_address=None,
    ):
        retries = [0]

        def bootstrap_del_webhook():
            self.logger.debug('Deleting webhook')
            if drop_pending_updates:
                self.logger.debug(
                    'Dropping pending updates from Telegram server')
            self.bot.delete_webhook(drop_pending_updates=drop_pending_updates)
            return False

        def bootstrap_set_webhook():
            self.logger.debug('Setting webhook')
            if drop_pending_updates:
                self.logger.debug(
                    'Dropping pending updates from Telegram server')
            self.bot.set_webhook(
                url=webhook_url,
                certificate=cert,
                allowed_updates=allowed_updates,
                ip_address=ip_address,
                drop_pending_updates=drop_pending_updates,
            )
            return False

        def bootstrap_onerr_cb(exc):
            if not isinstance(exc, Unauthorized) and (
                    max_retries < 0 or retries[0] < max_retries):
                retries[0] += 1
                self.logger.warning(
                    'Failed bootstrap phase; try=%s max_retries=%s',
                    retries[0], max_retries)
            else:
                self.logger.error(
                    'Failed bootstrap phase after %s retries (%s)', retries[0],
                    exc)
                raise exc

        # Dropping pending updates from TG can be efficiently done with the drop_pending_updates
        # parameter of delete/start_webhook, even in the case of polling. Also we want to make
        # sure that no webhook is configured in case of polling, so we just always call
        # delete_webhook for polling
        if drop_pending_updates or not webhook_url:
            self._network_loop_retry(
                bootstrap_del_webhook,
                bootstrap_onerr_cb,
                'bootstrap del webhook',
                bootstrap_interval,
            )
            retries[0] = 0

        # Restore/set webhook settings, if needed. Again, we don't know ahead if a webhook is set,
        # so we set it anyhow.
        if webhook_url:
            self._network_loop_retry(
                bootstrap_set_webhook,
                bootstrap_onerr_cb,
                'bootstrap set webhook',
                bootstrap_interval,
            )

    def stop(self) -> None:
        """Stops the polling/webhook thread, the dispatcher and the job queue."""

        self.job_queue.stop()
        with self.__lock:
            if self.running or self.dispatcher.has_running_threads:
                self.logger.debug('Stopping Updater and Dispatcher...')

                self.running = False

                self._stop_httpd()
                self._stop_dispatcher()
                self._join_threads()

                # Stop the Request instance only if it was created by the Updater
                if self._request:
                    self._request.stop()

    @no_type_check
    def _stop_httpd(self) -> None:
        if self.httpd:
            self.logger.debug(
                'Waiting for current webhook connection to be '
                'closed... Send a Telegram message to the bot to exit '
                'immediately.')
            self.httpd.shutdown()
            self.httpd = None

    @no_type_check
    def _stop_dispatcher(self) -> None:
        self.logger.debug('Requesting Dispatcher to stop...')
        self.dispatcher.stop()

    @no_type_check
    def _join_threads(self) -> None:
        for thr in self.__threads:
            self.logger.debug('Waiting for %s thread to end', thr.name)
            thr.join()
            self.logger.debug('%s thread has ended', thr.name)
        self.__threads = []

    @no_type_check
    def signal_handler(self, signum, frame) -> None:
        self.is_idle = False
        if self.running:
            self.logger.info('Received signal %s (%s), stopping...', signum,
                             get_signal_name(signum))
            if self.persistence:
                # Update user_data, chat_data and bot_data before flushing
                self.dispatcher.update_persistence()
                self.persistence.flush()
            self.stop()
            if self.user_sig_handler:
                self.user_sig_handler(signum, frame)
        else:
            self.logger.warning('Exiting immediately!')
            # pylint: disable=C0415,W0212
            import os

            os._exit(1)

    def idle(
        self, stop_signals: Union[List, Tuple] = (SIGINT, SIGTERM, SIGABRT)
    ) -> None:
        """Blocks until one of the signals are received and stops the updater.

        Args:
            stop_signals (:obj:`list` | :obj:`tuple`): List containing signals from the signal
                module that should be subscribed to. :meth:`Updater.stop()` will be called on
                receiving one of those signals. Defaults to (``SIGINT``, ``SIGTERM``, ``SIGABRT``).

        """
        for sig in stop_signals:
            signal(sig, self.signal_handler)

        self.is_idle = True

        while self.is_idle:
            sleep(1)
    def do_POST(self):
        post_string = self.rfile.read(int(self.headers['Content-Length']))
        post = json.loads(post_string)
        #print(post)
        self.send_response(200)
        self.send_header('Content-Type', 'application/json')
        self.end_headers()
        # Return empty JSON
        self.wfile.write('{}\n')

        xrb_account = post['account']
        account = mysql_select_by_account(xrb_account)
        if (account is False):
            account = mysql_select_by_account_extra(xrb_account)
        if (account is not False):
            block = json.loads(post['block'])
            if ((block['type'] == 'state')
                    and (block['subtype'] == 'receive')):
                if (proxy_url is None):
                    bot = Bot(api_key)
                else:
                    proxy = Request(proxy_url=proxy_url,
                                    urllib3_proxy_kwargs={
                                        'username': proxy_user,
                                        'password': proxy_pass
                                    })
                    bot = Bot(token=api_key, request=proxy)
                raw_received = int(post['amount'])
                received_amount = int(math.floor(raw_received / (10**24)))

                balance = account_balance(xrb_account)
                try:
                    mysql_balance = int(account[3])
                except Exception as e:
                    mysql_balance = 0
                if (mysql_balance == balance):  # workaround
                    logging.warning(
                        'Warning receive balance change. Old: {0}, new: {1}'.
                        format(mysql_balance, balance))
                    time.sleep(1)
                    balance = account_balance(xrb_account)
                    if (mysql_balance == balance):
                        time.sleep(8)
                        balance = account_balance(xrb_account)
                # workaround
                frontier = post['hash']
                try:
                    z = account[5]
                    mysql_update_frontier_extra(account[1], frontier)
                except IndexError as e:
                    mysql_update_frontier(account[1], frontier)
                logging.info('{0} --> {1}	{2}'.format(mrai_text(account[3]),
                                                      mrai_text(balance),
                                                      frontier))
                # retrieve sender
                send_source = block['link']
                block_account = rpc(
                    {
                        "action": "block_account",
                        "hash": send_source
                    }, 'account')
                lang_id = mysql_select_language(account[0])
                sender = lang_text('frontiers_sender_account',
                                   lang_id).format(block_account)
                # Sender info
                if (block_account == faucet_account):
                    sender = lang_text('frontiers_sender_faucet', lang_id)
                elif ((block_account == fee_account)
                      or (block_account == welcome_account)):
                    sender = lang_text('frontiers_sender_bot', lang_id)
                elif (block_account == account[1]):
                    sender = lang_text('frontiers_sender_self', lang_id)
                else:
                    sender_account = mysql_select_by_account(block_account)
                    if (sender_account is not False):
                        if ((sender_account[4] is not None)
                                and (sender_account[4])):
                            sender = lang_text('frontiers_sender_username',
                                               lang_id).format(
                                                   sender_account[4])
                        else:
                            sender = lang_text('frontiers_sender_users',
                                               lang_id).format(block_account)
                    else:
                        sender_account_extra = mysql_select_by_account_extra(
                            block_account)
                        if (sender_account_extra is not False):
                            user_sender = mysql_select_user(
                                sender_account_extra[0])
                            if ((user_sender[8] is not None)
                                    and (user_sender[8]) and
                                (account[0] != sender_account_extra[0])):
                                sender = lang_text('frontiers_sender_username',
                                                   lang_id).format(
                                                       user_sender[8])
                            elif (account[0] != sender_account_extra[0]):
                                sender = lang_text(
                                    'frontiers_sender_users',
                                    lang_id).format(block_account)
                try:
                    z = account[5]
                    sender = lang_text('frontiers_sender_by', lang_id).format(
                        sender, account[1].replace("_", "\_"))
                    mysql_update_balance_extra(account[1], balance)
                except IndexError as e:
                    mysql_update_balance(account[1], balance)
                logging.info(sender)
                logging.info(block_account)
                logging.info(
                    '{0} Nano (XRB) received by {1}, hash: {2}'.format(
                        mrai_text(received_amount), account[0], frontier))
                text = lang_text('frontiers_receive',
                                 lang_id).format(mrai_text(received_amount),
                                                 mrai_text(balance),
                                                 mrai_text(0), frontier,
                                                 hash_url, sender)
                mysql_set_sendlist(account[0], text)
                #print(text)
                try:
                    push(bot, account[0], text)
                    if (received_amount >= large_amount_warning):
                        time.sleep(0.25)
                        push(
                            bot, account[0],
                            lang_text('frontiers_large_amount_warning',
                                      lang_id))
                except BadRequest as e:
                    logging.exception('Bad request account {0}'.format(
                        account[0]))
                mysql_delete_sendlist(account[0])
        return
Example #32
0
def main():
    logger.info("Start tasks bot")
    bot_token = os.getenv("bot_token")
    req = Request(connect_timeout=0.5, read_timeout=1, con_pool_size=8)
    bot = Bot(
        token=bot_token,
        request=req,
    )
    updater = Updater(bot=bot, use_context=True)
    dp = updater.dispatcher

    dp.add_handler(CommandHandler(commands["start"], start))
    dp.add_handler(CommandHandler(commands["lists"], lists.show_lists))
    dp.add_handler(CallbackQueryHandler(callback_handler))

    dp.add_handler(
        ConversationHandler(
            entry_points=[
                CommandHandler(commands["add_list"], lists.add_list)
            ],
            states={
                conversations["add_list"]["name"]:
                [MessageHandler(Filters.text, lists.handle_list_name)],
            },
            fallbacks=[CommandHandler(commands["cancel"], cancel)],
        ))

    dp.add_handler(
        ConversationHandler(
            entry_points=[
                CommandHandler(commands["remove_list"], lists.remove_list)
            ],
            states={
                conversations["remove_list"]["choose_list"]:
                [MessageHandler(Filters.text, lists.handle_removing_list)],
            },
            fallbacks=[CommandHandler(commands["cancel"], cancel)],
        ))

    dp.add_handler(
        ConversationHandler(
            entry_points=[
                CommandHandler(commands["add_tasks"], tasks.add_tasks)
            ],
            states={
                conversations["add_tasks"]["choose_list"]:
                [MessageHandler(Filters.text, tasks.choose_list_to_add)],
                conversations["add_tasks"]["handle_tasks"]:
                [MessageHandler(Filters.text, tasks.handle_adding_task)],
            },
            fallbacks=[CommandHandler(commands["cancel"], cancel)],
        ))

    dp.add_handler(
        ConversationHandler(
            entry_points=[CommandHandler(commands["tasks"], tasks.show_tasks)],
            states={
                conversations["tasks"]["choose_list"]:
                [MessageHandler(Filters.text, tasks.choose_list_to_show)],
            },
            fallbacks=[CommandHandler(commands["cancel"], cancel)],
        ))

    dp.add_handler(
        ConversationHandler(
            entry_points=[
                CommandHandler(commands["done_task"], tasks.done_task)
            ],
            states={
                conversations["done_task"]["choose_list"]:
                [MessageHandler(Filters.text, tasks.choose_list_to_done)],
                conversations["done_task"]["handle_task"]:
                [MessageHandler(Filters.text, tasks.handle_done_task)],
            },
            fallbacks=[CommandHandler(commands["cancel"], cancel)],
        ))

    dp.add_handler(
        ConversationHandler(
            entry_points=[
                CommandHandler(commands["undone_task"], tasks.undone_task)
            ],
            states={
                conversations["undone_task"]["choose_list"]:
                [MessageHandler(Filters.text, tasks.choose_list_to_undone)],
                conversations["undone_task"]["handle_task"]:
                [MessageHandler(Filters.text, tasks.handle_undone_task)],
            },
            fallbacks=[CommandHandler(commands["cancel"], cancel)],
        ))

    dp.add_error_handler(handle_error)

    updater.start_polling()

    updater.idle()
    logger.info("Stop tasks bot")
Example #33
0
from .utils import utils
from .utils.pyrogram import client
from .database import base
from .bot import StickersBot
from config import config

logger = logging.getLogger(__name__)

stickersbot = StickersBot(
    bot=ExtBot(
        token=config.telegram.token,
        defaults=Defaults(parse_mode=ParseMode.HTML,
                          disable_web_page_preview=True),
        # https://github.com/python-telegram-bot/python-telegram-bot/blob/8531a7a40c322e3b06eb943325e819b37ee542e7/telegram/ext/updater.py#L267
        request=Request(con_pool_size=config.telegram.get('workers', 1) + 4)),
    use_context=True,
    workers=config.telegram.get('workers', 1),
    persistence=utils.persistence_object(
        config_enabled=config.telegram.get('persistent_temp_data', True)),
)


def main():
    utils.load_logging_config('logging.json')

    if config.pyrogram.enabled:
        logger.info('starting pyrogram client...')
        client.start()

    stickersbot.import_handlers(r'bot/handlers/')
Example #34
0
 def __init__(self, db):
     self.bot = Bot(token=annxious_tbot_token,
                    request=Request(con_pool_size=10))
     self.db = db
Example #35
0
def main():
    workers = 8
    con_pool_size = workers + 4

    job_queue = JobQueue()

    request = Request(con_pool_size=con_pool_size)
    bot = MQBot(token=TELEGRAM_API_TOKEN, request=request)
    dispatcher = Dispatcher(bot, Queue(),
                           job_queue=job_queue,
                           workers=workers)
    job_queue.set_dispatcher(dispatcher)
    updater = Updater(dispatcher=dispatcher, workers=None)

    xenian.bot.job_queue = job_queue

    def on_start():
        self = get_self(updater.bot)
        logger.info(f'Acting as {self.name} [link: {self.link}, id: {self.id}], with the key "{TELEGRAM_API_TOKEN}"')

    def stop_and_restart(chat_id):
        """Gracefully stop the Updater and replace the current process with a new one.
        """
        logger.info('Restarting: stopping')
        updater.stop()
        logger.info('Restarting: starting')
        os.execl(sys.executable, sys.executable, *sys.argv + [f'is_restart={chat_id}'])

    def restart(bot: Bot, update: Update):
        """Start the restarting process

        Args:
            bot (:obj:`telegram.bot.Bot`): Telegram Api Bot Object.
            update (:obj:`telegram.update.Update`): Telegram Api Update Object
        """
        update.message.reply_text('Bot is restarting...')
        Thread(target=lambda: stop_and_restart(update.message.chat_id)).start()

    def send_message_if_reboot():
        args = sys.argv
        is_restart_arg = [item for item in args if item.startswith('is_restart')]
        if any(is_restart_arg):
            chat_id = is_restart_arg[0].split('=')[1]
            updater.bot.send_message(chat_id, 'Bot has successfully restarted.')

    dispatcher.add_handler(CommandHandler('restart', restart, filters=Filters.user(username=ADMINS)))

    for command_class in BaseCommand.all_commands:
        for command in command_class.commands:
            dispatcher.add_handler(command['handler'](**command['options']), command['group'])

    # log all errors
    dispatcher.add_error_handler(error)

    if MODE['active'] == 'webhook':
        webhook = MODE['webhook']
        updater.start_webhook(listen=webhook['listen'], port=webhook['port'], url_path=webhook['url_path'])
        updater.bot.set_webhook(url=webhook['url'])
        send_message_if_reboot()
        logger.info('Starting webhook...')
        on_start()
    else:
        updater.start_polling()
        logger.info('Start polling...')
        send_message_if_reboot()
        on_start()
        updater.idle()