Python telegram.utils.request.Request() Examples

The following are 8 code examples of telegram.utils.request.Request(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module telegram.utils.request , or try the search function .
Example #1
Source File: bot.py    From TranscriberBot with GNU General Public License v3.0 6 votes vote down vote up
def start(self, token):
    self.voice_thread_pool = ThreadPoolExecutor(
      max_workers=config.get_config_prop("app")["voice_max_threads"]
    )
    self.photos_thread_pool = ThreadPoolExecutor(
      max_workers=config.get_config_prop("app")["photos_max_threads"]
    )

    self.misc_thread_pool = ThreadPoolExecutor(
      max_workers=2
    )

    self.queue = mq.MessageQueue()
    self.request = Request(con_pool_size=10)
    self.mqbot = self.MQBot(token, request=self.request, mqueue=self.queue)
    self.updater = Updater(bot=self.mqbot, use_context=True)
    self.dispatcher = self.updater.dispatcher
    self.__register_handlers()
    self.updater.start_polling(clean=True)
    self.updater.idle() 
Example #2
Source File: telegram_obs.py    From sacred with MIT License 5 votes vote down vote up
def get_proxy_request(telegram_config):
        from telegram.utils.request import Request

        if telegram_config["proxy_url"].startswith("socks5"):
            urllib3_proxy_kwargs = dict()
            for key in ["username", "password"]:
                if key in telegram_config:
                    urllib3_proxy_kwargs[key] = telegram_config[key]
            return Request(
                proxy_url=telegram_config["proxy_url"],
                urllib3_proxy_kwargs=urllib3_proxy_kwargs,
            )
        elif telegram_config["proxy_url"].startswith("http"):
            cred_string = ""
            if "username" in telegram_config:
                cred_string += telegram_config["username"]
            if "password" in telegram_config:
                cred_string += ":" + telegram_config["password"]
            if len(cred_string) > 0:
                domain = telegram_config["proxy_url"].split("/")[-1].split("@")[-1]
                cred_string += "@"
                proxy_url = "http://{}{}".format(cred_string, domain)
                return Request(proxy_url=proxy_url)
            else:
                return Request(proxy_url=telegram_config["proxy_url"])
        else:
            raise Exception(
                "Proxy URL should be in format "
                "PROTOCOL://PROXY_HOST[:PROXY_PORT].\n"
                "HTTP and Socks5 are supported."
            ) 
Example #3
Source File: bot.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
def __init__(self, token, base_url=None, base_file_url=None, request=None):
        self.token = self._validate_token(token)

        if base_url is None:
            base_url = 'https://api.telegram.org/bot'

        if base_file_url is None:
            base_file_url = 'https://api.telegram.org/file/bot'

        self.base_url = str(base_url) + str(self.token)
        self.base_file_url = str(base_file_url) + str(self.token)
        self.bot = None
        self._request = request or Request()
        self.logger = logging.getLogger(__name__) 
Example #4
Source File: updater.py    From telegram-robot-rss with Mozilla Public License 2.0 5 votes vote down vote up
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() 
Example #5
Source File: common.py    From NanoWalletBot with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def bot_start():
	# set bot
	if (proxy_url_common is None):
		bot = Bot(api_key_common)
	else:
		proxy = Request(proxy_url = proxy_url_common, urllib3_proxy_kwargs = {'username': proxy_user_common, 'password': proxy_pass_common })
		bot = Bot(token=api_key_common, request = proxy)
	return bot 
Example #6
Source File: utils.py    From munich-scripts with MIT License 5 votes vote down vote up
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
Source File: main.py    From BotListBot with MIT License 4 votes vote down vote up
def main():
    # Start API
    # thread = threading.Thread(target=botlistapi.start_server)
    # thread.start()
    if settings.is_sentry_enabled():
        sentry_sdk.init(settings.SENTRY_URL, environment=settings.SENTRY_ENVIRONMENT)

    botchecker_context = {}

    bot_token = str(settings.BOT_TOKEN)

    botlistbot = BotListBot(
        bot_token,
        request=Request(
            read_timeout=8,
            connect_timeout=7,
            con_pool_size=max(settings.WORKER_COUNT, 4),
        ),
    )
    updater = Updater(bot=botlistbot, workers=settings.WORKER_COUNT)

    botlistbot.formatter = MarkdownFormatter(updater.bot)

    appglobals.job_queue = updater.job_queue

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

    routing.register(dp, None)
    basic.register(dp)

    updater.job_queue.run_repeating(admin.last_update_job, interval=3600 * 24)

    if settings.DEV:
        log.info("Starting using long polling...")
        updater.start_polling()
    else:
        log.info("Starting using webhooks...")
        updater.start_webhook(
            listen="0.0.0.0", port=settings.PORT, url_path=settings.BOT_TOKEN
        )
        updater.bot.set_webhook(
            f"https://botlistbot.herokuapp.com/{settings.BOT_TOKEN}"
        )

    log.info("Listening...")
    updater.bot.send_message(settings.DEVELOPER_ID, "Ready to rock", timeout=10)

    # Idling
    updater.idle()
    updater.stop()

    log.info("Disconnecting...") 
Example #8
Source File: updater.py    From telegram-robot-rss with Mozilla Public License 2.0 4 votes vote down vote up
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 = []