Proxy and emojizeΒΆ

proxy_and_emojize.pyΒΆ
 1import logging
 2
 3import aiohttp
 4
 5from aiogram import Bot, types
 6from aiogram.dispatcher import Dispatcher
 7from aiogram.types import ParseMode
 8from aiogram.utils.emoji import emojize
 9from aiogram.utils.executor import start_polling
10from aiogram.utils.markdown import bold, code, italic, text
11
12# Configure bot here
13API_TOKEN = 'BOT_TOKEN_HERE'
14PROXY_URL = 'http://PROXY_URL'  # Or 'socks5://host:port'
15
16# NOTE: If authentication is required in your proxy then uncomment next line and change login/password for it
17# PROXY_AUTH = aiohttp.BasicAuth(login='login', password='password')
18# And add `proxy_auth=PROXY_AUTH` argument in line 30, like this:
19# >>> bot = Bot(token=API_TOKEN, proxy=PROXY_URL, proxy_auth=PROXY_AUTH)
20# Also you can use Socks5 proxy but you need manually install aiohttp_socks package.
21
22# Get my ip URL
23GET_IP_URL = 'http://bot.whatismyipaddress.com/'
24
25logging.basicConfig(level=logging.INFO)
26
27bot = Bot(token=API_TOKEN, proxy=PROXY_URL)
28
29# If auth is required:
30# bot = Bot(token=API_TOKEN, proxy=PROXY_URL, proxy_auth=PROXY_AUTH)
31dp = Dispatcher(bot)
32
33
34async def fetch(url, session):
35    async with session.get(url) as response:
36        return await response.text()
37
38
39@dp.message_handler(commands=['start'])
40async def cmd_start(message: types.Message):
41    # fetching urls will take some time, so notify user that everything is OK
42    await types.ChatActions.typing()
43
44    content = []
45
46    # Make request (without proxy)
47    async with aiohttp.ClientSession() as session:
48        ip = await fetch(GET_IP_URL, session)
49    content.append(text(':globe_showing_Americas:', bold('IP:'), code(ip)))
50    # This line is formatted to '🌎 *IP:* `YOUR IP`'
51
52    # Make request through bot's proxy
53    ip = await fetch(GET_IP_URL, bot.session)
54    content.append(text(':locked_with_key:', bold('IP:'), code(ip), italic('via proxy')))
55    # This line is formatted to 'πŸ” *IP:* `YOUR IP` _via proxy_'
56
57    # Send content
58    await bot.send_message(message.chat.id, emojize(text(*content, sep='\n')), parse_mode=ParseMode.MARKDOWN)
59
60    # In this example you can see emoji codes: ":globe_showing_Americas:" and ":locked_with_key:"
61    # You can find full emoji cheat sheet at https://www.webpagefx.com/tools/emoji-cheat-sheet/
62    # For representing emoji codes into real emoji use emoji util (aiogram.utils.emoji)
63    # (you have to install emoji module)
64
65    # For example emojize('Moon face :new_moon_face:') is transformed to 'Moon face 🌚'
66
67
68if __name__ == '__main__':
69    start_polling(dp, skip_updates=True)