From a93fb463820fc6924bc22ffeb1c1d2a579a0f3f0 Mon Sep 17 00:00:00 2001 From: Suren Khorenyan Date: Sun, 11 Aug 2019 15:49:27 +0300 Subject: [PATCH] Refactor examples/proxy_and_emojize.py --- examples/proxy_and_emojize.py | 31 ++++++++++++++++++------------- 1 file changed, 18 insertions(+), 13 deletions(-) diff --git a/examples/proxy_and_emojize.py b/examples/proxy_and_emojize.py index 17e33872..5ef40608 100644 --- a/examples/proxy_and_emojize.py +++ b/examples/proxy_and_emojize.py @@ -1,4 +1,3 @@ -import asyncio import logging import aiohttp @@ -11,13 +10,13 @@ from aiogram.utils.executor import start_polling from aiogram.utils.markdown import bold, code, italic, text # Configure bot here -API_TOKEN = 'BOT TOKEN HERE' -PROXY_URL = 'http://PROXY_URL' # Or 'socks5://...' +API_TOKEN = 'BOT_TOKEN_HERE' +PROXY_URL = 'http://PROXY_URL' # Or 'socks5://host:port' -# If authentication is required in your proxy then uncomment next line and change login/password for it +# NOTE: If authentication is required in your proxy then uncomment next line and change login/password for it # PROXY_AUTH = aiohttp.BasicAuth(login='login', password='password') -# And add `proxy_auth=PROXY_AUTH` argument in line 25, like this: -# >>> bot = Bot(token=API_TOKEN, loop=loop, proxy=PROXY_URL, proxy_auth=PROXY_AUTH) +# And add `proxy_auth=PROXY_AUTH` argument in line 30, like this: +# >>> bot = Bot(token=API_TOKEN, proxy=PROXY_URL, proxy_auth=PROXY_AUTH) # Also you can use Socks5 proxy but you need manually install aiohttp_socks package. # Get my ip URL @@ -26,26 +25,32 @@ GET_IP_URL = 'http://bot.whatismyipaddress.com/' logging.basicConfig(level=logging.INFO) bot = Bot(token=API_TOKEN, proxy=PROXY_URL) + +# If auth is required: +# bot = Bot(token=API_TOKEN, proxy=PROXY_URL, proxy_auth=PROXY_AUTH) dp = Dispatcher(bot) -async def fetch(url, proxy=None, proxy_auth=None): - async with aiohttp.ClientSession() as session: - async with session.get(url, proxy=proxy, proxy_auth=proxy_auth) as response: - return await response.text() +async def fetch(url, session): + async with session.get(url) as response: + return await response.text() @dp.message_handler(commands=['start']) async def cmd_start(message: types.Message): + # fetching urls will take some time, so notify user that everything is OK + await types.ChatActions.typing() + content = [] # Make request (without proxy) - ip = await fetch(GET_IP_URL) + async with aiohttp.ClientSession() as session: + ip = await fetch(GET_IP_URL, session) content.append(text(':globe_showing_Americas:', bold('IP:'), code(ip))) # This line is formatted to '🌎 *IP:* `YOUR IP`' - # Make request through proxy - ip = await fetch(GET_IP_URL, bot.proxy, bot.proxy_auth) + # Make request through bot's proxy + ip = await fetch(GET_IP_URL, bot.session) content.append(text(':locked_with_key:', bold('IP:'), code(ip), italic('via proxy'))) # This line is formatted to '🔐 *IP:* `YOUR IP` _via proxy_'