mirror of
https://github.com/aiogram/aiogram.git
synced 2025-12-11 18:01:04 +00:00
Provide proxy connection. Add example for proxy and emoji util
This commit is contained in:
parent
c94c4e8003
commit
6c21270ccb
5 changed files with 94 additions and 23 deletions
|
|
@ -2,6 +2,6 @@ from .utils.versions import Version, Stage
|
||||||
from .bot import Bot
|
from .bot import Bot
|
||||||
|
|
||||||
|
|
||||||
VERSION = Version(0, 3, 3, stage=Stage.FINAL, build=0)
|
VERSION = Version(0, 3, 4, stage=Stage.DEV, build=0)
|
||||||
|
|
||||||
__version__ = VERSION.version
|
__version__ = VERSION.version
|
||||||
|
|
|
||||||
|
|
@ -104,7 +104,7 @@ def _compose_data(params=None, files=None):
|
||||||
return data
|
return data
|
||||||
|
|
||||||
|
|
||||||
async def request(session, token, method, data=None, files=None) -> bool or dict:
|
async def request(session, token, method, data=None, files=None, **kwargs) -> bool or dict:
|
||||||
"""
|
"""
|
||||||
Make request to API
|
Make request to API
|
||||||
|
|
||||||
|
|
@ -125,7 +125,7 @@ async def request(session, token, method, data=None, files=None) -> bool or dict
|
||||||
method, data or {}, files or {}))
|
method, data or {}, files or {}))
|
||||||
data = _compose_data(data, files)
|
data = _compose_data(data, files)
|
||||||
url = Methods.api_url(token=token, method=method)
|
url = Methods.api_url(token=token, method=method)
|
||||||
async with session.post(url, data=data) as response:
|
async with session.post(url, data=data, **kwargs) as response:
|
||||||
return await _check_result(method, response)
|
return await _check_result(method, response)
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -6,6 +6,7 @@ import aiohttp
|
||||||
|
|
||||||
from . import api
|
from . import api
|
||||||
from .. import types
|
from .. import types
|
||||||
|
from ..utils import json
|
||||||
from ..utils.payload import generate_payload, prepare_arg
|
from ..utils.payload import generate_payload, prepare_arg
|
||||||
|
|
||||||
InputFile = TypeVar('InputFile', io.BytesIO, io.FileIO, str)
|
InputFile = TypeVar('InputFile', io.BytesIO, io.FileIO, str)
|
||||||
|
|
@ -22,7 +23,7 @@ class BaseBot:
|
||||||
|
|
||||||
def __init__(self, token: String,
|
def __init__(self, token: String,
|
||||||
loop: Optional[Union[asyncio.BaseEventLoop, asyncio.AbstractEventLoop]] = None,
|
loop: Optional[Union[asyncio.BaseEventLoop, asyncio.AbstractEventLoop]] = None,
|
||||||
connections_limit: Optional[Integer] = 10):
|
connections_limit: Optional[Integer] = 10, proxy=None, proxy_auth=None):
|
||||||
"""
|
"""
|
||||||
Instructions how to get Bot token is found here: https://core.telegram.org/bots#3-how-do-i-create-a-bot
|
Instructions how to get Bot token is found here: https://core.telegram.org/bots#3-how-do-i-create-a-bot
|
||||||
|
|
||||||
|
|
@ -32,6 +33,8 @@ class BaseBot:
|
||||||
"""
|
"""
|
||||||
|
|
||||||
self.__token = token
|
self.__token = token
|
||||||
|
self.proxy = proxy
|
||||||
|
self.proxy_auth = proxy_auth
|
||||||
|
|
||||||
if loop is None:
|
if loop is None:
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
|
|
@ -39,7 +42,7 @@ class BaseBot:
|
||||||
self.loop = loop
|
self.loop = loop
|
||||||
self.session = aiohttp.ClientSession(
|
self.session = aiohttp.ClientSession(
|
||||||
connector=aiohttp.TCPConnector(limit=connections_limit),
|
connector=aiohttp.TCPConnector(limit=connections_limit),
|
||||||
loop=self.loop)
|
loop=self.loop, json_serialize=json.dumps)
|
||||||
self._temp_sessions = []
|
self._temp_sessions = []
|
||||||
api.check_token(token)
|
api.check_token(token)
|
||||||
|
|
||||||
|
|
@ -93,7 +96,8 @@ class BaseBot:
|
||||||
:return: Union[List, Dict]
|
:return: Union[List, Dict]
|
||||||
:raise: :class:`aiogram.exceptions.TelegramApiError`
|
:raise: :class:`aiogram.exceptions.TelegramApiError`
|
||||||
"""
|
"""
|
||||||
return await api.request(self.session, self.__token, method, data, files)
|
return await api.request(self.session, self.__token, method, data, files,
|
||||||
|
proxy=self.proxy, proxy_auth=self.proxy_auth)
|
||||||
|
|
||||||
async def download_file(self, file_path: String,
|
async def download_file(self, file_path: String,
|
||||||
destination: Optional[InputFile] = None,
|
destination: Optional[InputFile] = None,
|
||||||
|
|
@ -121,7 +125,7 @@ class BaseBot:
|
||||||
|
|
||||||
dest = destination if isinstance(destination, io.IOBase) else open(destination, 'wb')
|
dest = destination if isinstance(destination, io.IOBase) else open(destination, 'wb')
|
||||||
try:
|
try:
|
||||||
async with session.get(url, timeout=timeout) as response:
|
async with session.get(url, timeout=timeout, proxy=self.proxy, proxy_auth=self.proxy_auth) as response:
|
||||||
while True:
|
while True:
|
||||||
chunk = await response.content.read(chunk_size)
|
chunk = await response.content.read(chunk_size)
|
||||||
if not chunk:
|
if not chunk:
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,6 @@
|
||||||
import datetime
|
import datetime
|
||||||
|
|
||||||
|
from aiogram.utils.helper import Item, HelperMode, Helper
|
||||||
from .audio import Audio
|
from .audio import Audio
|
||||||
from .base import Deserializable
|
from .base import Deserializable
|
||||||
from .chat import Chat
|
from .chat import Chat
|
||||||
|
|
@ -240,7 +241,7 @@ class Message(Deserializable):
|
||||||
return await self.chat.pin_message(self.message_id, disable_notification)
|
return await self.chat.pin_message(self.message_id, disable_notification)
|
||||||
|
|
||||||
|
|
||||||
class ContentType:
|
class ContentType(Helper):
|
||||||
"""
|
"""
|
||||||
List of message content types
|
List of message content types
|
||||||
|
|
||||||
|
|
@ -258,24 +259,25 @@ class ContentType:
|
||||||
:key: SUCCESSFUL_PAYMENT
|
:key: SUCCESSFUL_PAYMENT
|
||||||
:key: UNKNOWN
|
:key: UNKNOWN
|
||||||
"""
|
"""
|
||||||
|
mode = HelperMode.lower_case
|
||||||
|
|
||||||
TEXT = 'text'
|
TEXT = Item() # text
|
||||||
AUDIO = 'audio'
|
AUDIO = Item() # audio
|
||||||
DOCUMENT = 'document'
|
DOCUMENT = Item() # document
|
||||||
GAME = 'game'
|
GAME = Item() # game
|
||||||
PHOTO = 'photo'
|
PHOTO = Item() # photo
|
||||||
STICKER = 'sticker'
|
STICKER = Item() # sticker
|
||||||
VIDEO = 'video'
|
VIDEO = Item() # video
|
||||||
VOICE = 'voice'
|
VOICE = Item() # voice
|
||||||
NEW_CHAT_MEMBERS = 'new_chat_members'
|
NEW_CHAT_MEMBERS = Item() # new_chat_members
|
||||||
LEFT_CHAT_MEMBER = 'left_chat_member'
|
LEFT_CHAT_MEMBER = Item() # left_chat_member
|
||||||
INVOICE = 'invoice'
|
INVOICE = Item() # invoice
|
||||||
SUCCESSFUL_PAYMENT = 'successful_payment'
|
SUCCESSFUL_PAYMENT = Item() # successful_payment
|
||||||
|
|
||||||
UNKNOWN = 'unknown'
|
UNKNOWN = 'unknown'
|
||||||
|
|
||||||
|
|
||||||
class ParseMode:
|
class ParseMode(Helper):
|
||||||
"""
|
"""
|
||||||
Parse modes
|
Parse modes
|
||||||
|
|
||||||
|
|
@ -283,5 +285,7 @@ class ParseMode:
|
||||||
:key: HTML
|
:key: HTML
|
||||||
"""
|
"""
|
||||||
|
|
||||||
MARKDOWN = 'markdown'
|
mode = HelperMode.lowercase
|
||||||
HTML = 'html'
|
|
||||||
|
MARKDOWN = Item()
|
||||||
|
HTML = Item()
|
||||||
|
|
|
||||||
63
examples/proxy_and_emojize.py
Normal file
63
examples/proxy_and_emojize.py
Normal file
|
|
@ -0,0 +1,63 @@
|
||||||
|
import asyncio
|
||||||
|
import logging
|
||||||
|
|
||||||
|
from aiogram import Bot, types
|
||||||
|
from aiogram.dispatcher import Dispatcher
|
||||||
|
from aiogram.types import ParseMode
|
||||||
|
from aiogram.utils.emoji import emojize
|
||||||
|
from aiogram.utils.markdown import text, bold, italic, code
|
||||||
|
|
||||||
|
# Configure bot here
|
||||||
|
API_TOKEN = 'BOT TOKEN HERE'
|
||||||
|
PROXY_URL = 'http://PROXY_URL'
|
||||||
|
|
||||||
|
# Get my ip URL
|
||||||
|
GET_IP_URL = 'http://bot.whatismyipaddress.com/'
|
||||||
|
|
||||||
|
logging.basicConfig(level=logging.INFO)
|
||||||
|
|
||||||
|
loop = asyncio.get_event_loop()
|
||||||
|
bot = Bot(token=API_TOKEN, loop=loop, proxy=PROXY_URL)
|
||||||
|
dp = Dispatcher(bot)
|
||||||
|
|
||||||
|
|
||||||
|
@dp.message_handler(commands=['test'])
|
||||||
|
async def cmd_start(message: types.Message):
|
||||||
|
# Create temporary session
|
||||||
|
session = bot.create_temp_session()
|
||||||
|
|
||||||
|
content = []
|
||||||
|
|
||||||
|
# Make request (without proxy)
|
||||||
|
async with session.get(GET_IP_URL) as response:
|
||||||
|
content.append(text(':globe_showing_Americas:', bold('IP:'), code(await response.text())))
|
||||||
|
|
||||||
|
# Make request with proxy
|
||||||
|
async with session.get(GET_IP_URL, proxy=bot.proxy, proxy_auth=bot.proxy_auth) as response:
|
||||||
|
content.append(text(':locked_with_key:', bold('IP:'), code(await response.text()), italic('via proxy')))
|
||||||
|
|
||||||
|
# Send content
|
||||||
|
await bot.send_message(message.chat.id, emojize(text(*content, sep='\n')), parse_mode=ParseMode.MARKDOWN)
|
||||||
|
|
||||||
|
# Destroy temp session
|
||||||
|
bot.destroy_temp_session(session)
|
||||||
|
|
||||||
|
# In this example you can see emoji codes: ":globe_showing_Americas:" and ":locked_with_key:"
|
||||||
|
# Full emoji cheat sheet you can found at https://www.webpagefx.com/tools/emoji-cheat-sheet/
|
||||||
|
# For representing emoji codes to real emoji use emoji util (aiogram.utils.emoji)
|
||||||
|
# and you need to be installed emoji module
|
||||||
|
|
||||||
|
# For example emojize('Moon face :new_moon_face:') is represents to 'Moon face 🌚'
|
||||||
|
|
||||||
|
|
||||||
|
async def main():
|
||||||
|
count = await dp.skip_updates()
|
||||||
|
print(f"Skipped {count} updates.")
|
||||||
|
await dp.start_pooling()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
try:
|
||||||
|
loop.run_until_complete(main())
|
||||||
|
except KeyboardInterrupt:
|
||||||
|
loop.stop()
|
||||||
Loading…
Add table
Add a link
Reference in a new issue