Giter Club home page Giter Club logo

aiogram's Introduction

aiogram

MIT License

PyPi status

PyPi Package Version

Downloads

Supported python versions

Telegram Bot API

Codecov

aiogram is a modern and fully asynchronous framework for Telegram Bot API written in Python 3.8 using asyncio and aiohttp.

Make your bots faster and more powerful!

Documentation:

Features

  • Asynchronous (asyncio docs, 492)
  • Has type hints (484) and can be used with mypy
  • Supports PyPy
  • Supports Telegram Bot API 7.2 and gets fast updates to the latest versions of the Bot API
  • Telegram Bot API integration code was autogenerated and can be easily re-generated when API gets updated
  • Updates router (Blueprints)
  • Has Finite State Machine
  • Uses powerful magic filters
  • Middlewares (incoming updates and API calls)
  • Provides Replies into Webhook
  • Integrated I18n/L10n support with GNU Gettext (or Fluent)

Warning

It is strongly advised that you have prior experience working with asyncio before beginning to use aiogram.

If you have any questions, you can visit our community chats on Telegram:

aiogram's People

Contributors

ars2014 avatar arsnotfound avatar arwichok avatar b0g3r avatar birdi7 avatar bobronium avatar danipulok avatar darksidecat avatar evgfilim1 avatar forden avatar gabbhack avatar goduni avatar hum4noidx avatar jrootjunior avatar kylmakalle avatar latand avatar mahenzon avatar mastergroosha avatar melissalemon avatar melomansky avatar monkeywithacupcake avatar olegt0rr avatar setazer avatar sheldygg avatar tishka17 avatar unintended avatar uwinx avatar vasya-polyansky avatar wakaree avatar whitememory99 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aiogram's Issues

An error in starting bot through webhook

I'm trying to start example with webhooks, and got this error (all needed ports are openned):
Traceback (most recent call last):
File "/usr/lib/python3.6/asyncio/base_events.py", line 1044, in create_server
sock.bind(sa)
OSError: [Errno 99] Cannot assign requested address

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "bot.py", line 163, in
web.run_app(app, host=WEBHOOK_HOST, port=WEBHOOK_PORT, ssl_context=context)
File "/home/ubuntu/work/arturka_test/venv/lib/python3.6/site-packages/aiohttp/web.py", line 108, in run_app
loop.run_until_complete(site.start())
File "/usr/lib/python3.6/asyncio/base_events.py", line 467, in run_until_complete
return future.result()
File "/home/ubuntu/work/arturka_test/venv/lib/python3.6/site-packages/aiohttp/web_runner.py", line 87, in start
reuse_port=self._reuse_port)
File "/usr/lib/python3.6/asyncio/base_events.py", line 1048, in create_server
% (sa, err.strerror.lower()))
OSError: [Errno 99] error while attempting to bind on address ('xx.xxx.xx.xxx', 443): cannot assign requested address
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x7f691c7c45f8>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x7f691c6e1ef0>, 20234.463400305)]']
connector: <aiohttp.connector.TCPConnector object at 0x7f691c82efd0>

How can I fix it? This problem is detected on amazon aws.

Bad request when sending a BytesIO object directly derived from the downloaded one

I ran into this weird issue when implementing my bot, so I thought about sending it here.

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Operating System: Ubuntu 18.04
  • Python Version: 3.7.0
  • aiogram version: 2.0
  • aiohttp version: 3.4.4
  • uvloop version (if installed): 0.11.3

Current Behavior

I'm using a image library to do some transformations in images sent by the user, but I managed to reproduce the issue without it. Basically, when I download an image using the download_file_by_id function and write its byte contents into another BytesIO Object (standing in for the Image type in the image library), then send this second BytesIO object with send_photo, I get an error.

Steps to Reproduce

I created a simple test bot to reproduce the steps:


from aiogram import Bot, Dispatcher, executor, types
from aiogram.types import ContentTypes
from bot_info import API_TOKEN
from io import BytesIO

# Configure logging
logging.basicConfig(level=logging.INFO)

# Initialize bot and dispatcher
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)


@dp.message_handler(content_types=ContentTypes.PHOTO)
async def test(message: types.Message):
	downloaded = await bot.download_file_by_id(message.photo[-1].file_id)
	b = BytesIO()
	b.write(downloaded.getvalue())
	with open('testfile.jpg', 'wb') as f:
		f.write(b.getvalue())
	await bot.send_photo(message.chat.id, b)


if __name__ == '__main__':
    executor.start_polling(dp, skip_updates=True)

I managed to get around this bug by saving the BytesIO content into a intermediate file, then immediately opening this intermediate file and sending it in the send_photo method.

Failure Logs

The error stack trace is as follows:

ERROR:asyncio:Task exception was never retrieved
future: <Task finished coro=<Dispatcher._process_polling_updates() done, defined at /home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/dispatcher/dispatcher.py:265> exception=BadRequest('Bad request: file must be non-empty')>
Traceback (most recent call last):
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/dispatcher/dispatcher.py", line 273, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/dispatcher/dispatcher.py", line 147, in process_updates
    return await asyncio.gather(*tasks)
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/dispatcher/handler.py", line 99, in notify
    response = await handler(*args, **partial_data)
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/dispatcher/dispatcher.py", line 168, in process_update
    return await self.message_handlers.notify(update.message)
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/dispatcher/handler.py", line 99, in notify
    response = await handler(*args, **partial_data)
  File "test_bot.py", line 23, in send_welcome
    await bot.send_photo(message.chat.id, b)
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/bot/bot.py", line 284, in send_photo
    result = await self.request(api.Methods.SEND_PHOTO, payload, files)
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/bot/base.py", line 112, in request
    proxy=self.proxy, proxy_auth=self.proxy_auth, **kwargs)
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/bot/api.py", line 98, in make_request
    return await check_result(method, response.content_type, response.status, await response.text())
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/bot/api.py", line 72, in check_result
    exceptions.BadRequest.detect(description)
  File "/home/carol/.pyenv/versions/3.7.0/lib/python3.7/site-packages/aiogram/utils/exceptions.py", line 117, in detect
    raise cls(description)
aiogram.utils.exceptions.BadRequest: Bad request: file must be non-empty

New filters in builtin module

Next list of filters is planned for implementation in builtin module and registered in filters factory:

SOCKS5 proxy not works in some examples


name: Bug with SOCKS5 proxy authentication
about: Works unreliably with SOCKS5 proxy authentication giving errors from time to time.


Context

I'm using a socks5 proxy with authentication. Tried to put credentials both in address string and pass with proxy_auth as aiohttp.BasicAuth. And getting aiohttp_socks.errors.SocksError: Address type not supported

  • Operating System: Ubuntu 18.10
  • Python Version: 3.7
  • aiogram version: 2.0.dev1 (latest dev-2.x branch HEAD, commit 8ef279b)
  • aiohttp version: 3.4.4
  • uvloop version (if installed): no

Failure Information (for bugs)

Nevertheless there is a bug resolved I still facing issues with socks5 proxy authentication.

Steps to Reproduce

Either use URL with credentials of this kind
socks5://user:[email protected]:yy/
and provide no proxy_auth to Bot.

or use URL of kind socks5://xx.xx.xx.xx:yy/
and provide proxy_auth like aiohttp.BasicAuth(login='user', password='pass')

Both methods doesn't fail immediately. They even are capable of receiving some messages and give response. But both are fail with logs provided below. Looks like first with credentials in the string works a bit more reliable.

You can reproduce the bug with finite_state_machine_example.py and media_group.py gives the same error if you provide them with socks5 proxy. echo_bot.py gives same error on request of the picture.

Failure Logs

> python finite_state_machine_example.py
Skipped 1 updates.
Cause exception while getting updates.
Traceback (most recent call last):
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiogram-2.0.dev1-py3.7.egg/aiogram/dispatcher/dispatcher.py", line 261, in start_polling
    updates = await self.bot.get_updates(limit=limit, offset=offset, timeout=timeout)
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiogram-2.0.dev1-py3.7.egg/aiogram/bot/bot.py", line 101, in get_updates
    result = await self.request(api.Methods.GET_UPDATES, payload, timeout=timeout + 2 if timeout else None)
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiogram-2.0.dev1-py3.7.egg/aiogram/bot/base.py", line 115, in request
    proxy=self.proxy, proxy_auth=self.proxy_auth, **kwargs)
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiogram-2.0.dev1-py3.7.egg/aiogram/bot/api.py", line 97, in make_request
    async with session.post(url, data=req, **kwargs) as response:
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiohttp/client.py", line 855, in__aenter__
    self._resp = await self._coro
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiohttp/client.py", line 370, in_request
    timeout=timeout
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiohttp/connector.py", line 445,in connect
    proto = await self._create_connection(req, traces, timeout)
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiohttp/connector.py", line 757,in _create_connection
    req, traces, timeout)
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiohttp/connector.py", line 862,in _create_direct_connection
    req=req, client_error=client_error)
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiohttp_socks/connector.py", line 50, in _wrap_create_connection
    await sock.connect((host, port))
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiohttp_socks/proto.py", line 150, in connect
    await self.negotiate()
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiohttp_socks/proto.py", line 366, in negotiate
    await self._socks_connect()
  File "/home/ali/miniconda3/envs/telebot/lib/python3.7/site-packages/aiohttp_socks/proto.py", line 306, in _socks_connect
    raise SocksError(SOCKS5_ERRORS.get(err_code, 'Unknown error'))
aiohttp_socks.errors.SocksError: Address type not supported

Exeption if use dp.proccess_update() and /cmd@bot_name


name: Bug with proccess_update()
about: Exeption if use dp.proccess_update() and /cmd@bot_name


Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Operating System: Windows 10 x64
  • Python Version: 3.7.1
  • aiogram version: 2.0
  • aiohttp version: 3.4.4
  • uvloop version (if installed):

Failure Information (for bugs)

I use one server for several bots, so instead of the code from the examples I use types.Update(**update) and dp.process_update() for each bot and I catch this error when I use commands with the bot name. / start @ mybot does not work, / start works well

Steps to Reproduce

just code

import asyncio
from aiogram import Bot, Dispatcher, types

API_TOKEN = '....'
bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot)


@dp.message_handler(commands=['start', 'help'])
async def send_welcome(message: types.Message):
    await message.reply("Hi!\nI'm EchoBot!\nPowered by aiogram.")

async def myupdate():
    update = {"update_id": 957250703, "message": {"message_id": 12345, "from": {"id": 12345, "is_bot": False, "first_name": "qwerty", "last_name": "qwerty", "username": "qwerty", "language_code": "ru"}, "chat": {"id": -123456, "title": "qwerty", "username": "qwerty", "type": "supergroup"}, "date": 1544743937, "text": "/go@svinexample_bot", "entities": [{"offset": 0, "length": 19, "type": "bot_command"}]}}
    update = types.Update(**update)
    await dp.process_updates([update])


loop = asyncio.get_event_loop()
tasks = [loop.create_task(myupdate())]
wait_tasks = asyncio.wait(tasks)
loop.run_until_complete(wait_tasks)
loop.close()

Failure Logs

ERROR:asyncio:Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000024BF17EC940>
ERROR:asyncio:Task exception was never retrieved
future: <Task finished coro=<myupdate() done, defined at C:/Users/Владислав/Desktop/test/mybot/my_bot.py:33> exception=AttributeError("'NoneType' object has no attribute 'me'")>
Traceback (most recent call last):
  File "C:/Users/Владислав/Desktop/test/mybot/my_bot.py", line 36, in myupdate
    await dp.process_updates([update])
  File "D:\Programs\Python\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 147, in process_updates
    return await asyncio.gather(*tasks)
  File "D:\Programs\Python\lib\site-packages\aiogram\dispatcher\handler.py", line 99, in notify
    response = await handler(*args, **partial_data)
  File "D:\Programs\Python\lib\site-packages\aiogram\dispatcher\dispatcher.py", line 168, in process_update
    return await self.message_handlers.notify(update.message)
  File "D:\Programs\Python\lib\site-packages\aiogram\dispatcher\handler.py", line 90, in notify
    data.update(await check_filters(self.dispatcher, filters, args))
  File "D:\Programs\Python\lib\site-packages\aiogram\dispatcher\filters\filters.py", line 60, in check_filters
    f = await check_filter(dispatcher, filter_, args)
  File "D:\Programs\Python\lib\site-packages\aiogram\dispatcher\filters\filters.py", line 43, in check_filter
    return await filter_(*args, **kwargs)
  File "D:\Programs\Python\lib\site-packages\aiogram\dispatcher\filters\filters.py", line 144, in __call__
    return await self.check(obj)
  File "D:\Programs\Python\lib\site-packages\aiogram\dispatcher\filters\builtin.py", line 56, in check
    return await self.check_command(message, self.commands, self.prefixes, self.ignore_case, self.ignore_mention)
  File "D:\Programs\Python\lib\site-packages\aiogram\dispatcher\filters\builtin.py", line 63, in check_command
    if not ignore_mention and mention and (await message.bot.me).username.lower() != mention.lower():
AttributeError: 'NoneType' object has no attribute 'me'

message.reply_audio неверное название аудиозаписи

@dp.message_handler(regexp='^https:\/\/music.yandex.ru\/?a?l?b?u?m?\/?[0-9]+?\/track\/[0-9]+$')
async def music_handler(message: types.Message):
    url, title = await parse_url(message.text, loop)
    print(url)
    print(title)

    await message.reply_audio(audio=url, title=title)

Принт:
https://длинная_ссылка
Twenty One Pilots - Nico And The Niners

В Телеграме:
default
Похоже что title хоть и передаётся в reply_audio, но не используется.

UPD: bot.send_audio тоже пробовал, результат тот же.

JSONStorage and PickleStorage aren't persistent

Context

  • Operating System: Linux Linux Mint 19.1 Tessa
  • Python Version: 3.7.1
  • aiogram version: 2.2
  • aiohttp version: 3.5.4

Expected Behavior

The user's states will be saved with calling

await dispatcher.storage.close()
await dispatcher.storage.wait_closed()

on shutdown and after the restart will stay the same as before.

Current Behavior

The states are not saved on the disk, the empty object is saved instead.

Failure Information

During the shutdown, the storage makes 2 writing operations on the disk: first one with the correct data and the second with an empty object. The invocation of dispatcher.storage.close() performs these 2 operations.
There is no bug in restoring data: if saving was successful, everything works correctly.

Steps to Reproduce

  1. Run this gist. The JSONStorage is used there, but the situation with the PickleStorage is the same
  2. Set your state with /s1 or /s2 and check if it is set with /g
  3. Restart the script. An empty object will be saved In your "fsm_data.json" file
  4. Check that your state has changed after rebooting with /g

Documentation request: Inline Keyboard example

Currently inline keyboards are only documented as the raw class headers. At least a simple example would be very useful since there's many different functions that seemingly need to be chained to get any useful results.

Handler doesn't handle Venue Messages

@dp.message_handler(content_types=types.ContentType.VENUE)
async def func(message):
    print(message)

i tried this code, and it doesent handler Venue messages

if i use a filter on any types like
@dp.message_handler(content_types=types.ContentType.ANY)
This handle Venue in addition to others

Forward message without forwarding

In some cases need to forward message (with any content type) as new message (without using forwardMessage)

As I see the final result of the decision:
Add new method to Message object:

message.send_to(chat_id)

This method should generate new message from existing message and send it to the specified chat.

Cannot install by pip or git source


name: Bug report
about: Cannot install aiogram

Context

Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.

  • Operating System: Ubuntu 16.04.6 LTS
  • Python Version: 3.7
  • aiogram version:
  • aiohttp version:
  • uvloop version (if installed):

Behavior

~/aiogram$ sudo python3.7 setup.py install
...
Traceback (most recent call last):
File "setup.py", line 84, in
include_package_data=False,
File "/usr/lib/python3.7/distutils/core.py", line 148, in setup
dist.run_commands()
File "/usr/lib/python3.7/distutils/dist.py", line 966, in run_commands
self.run_command(cmd)
File "/usr/lib/python3.7/distutils/dist.py", line 985, in run_command
cmd_obj.run()
File "/usr/lib/python3/dist-packages/setuptools/command/install.py", line 67, in run
self.do_egg_install()
File "/usr/lib/python3/dist-packages/setuptools/command/install.py", line 109, in do_egg_install
self.run_command('bdist_egg')
File "/usr/lib/python3.7/distutils/cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "/usr/lib/python3.7/distutils/dist.py", line 985, in run_command
cmd_obj.run()
File "/usr/lib/python3/dist-packages/setuptools/command/bdist_egg.py", line 209, in run
os.path.join(archive_root, 'EGG-INFO'), self.zip_safe()
File "/usr/lib/python3/dist-packages/setuptools/command/bdist_egg.py", line 245, in zip_safe
return analyze_egg(self.bdist_dir, self.stubs)
File "/usr/lib/python3/dist-packages/setuptools/command/bdist_egg.py", line 355, in analyze_egg
safe = scan_module(egg_dir, base, name, stubs) and safe
File "/usr/lib/python3/dist-packages/setuptools/command/bdist_egg.py", line 392, in scan_module
code = marshal.load(f)
ValueError: bad marshal data (unknown type code)

--------------------------

~/aiogram$ pip3 install aiogram

Collecting aiohttp>=3.4.4 (from aiogram)
Could not find a version that satisfies the requirement aiohttp>=3.4.4 (from aiogram) (from versions: 0.1, 0.2, 0.3, 0.4, 0.4.1, 0.4.2, 0.4.3, 0.4.4, 0.5.0, 0.6.0, 0.6.1, 0.6.2, 0.6.3, 0.6.4, 0.6.5, 0.7.0, 0.7.1, 0.7.2, 0.7.3, 0.8.0, 0.8.1, 0.8.2, 0.8.3, 0.8.4, 0.9.0, 0.9.1, 0.9.2, 0.9.3, 0.10.0, 0.10.1, 0.10.2, 0.11.0, 0.12.0, 0.13.0, 0.13.1, 0.14.0, 0.14.1, 0.14.2, 0.14.3, 0.14.4, 0.15.0, 0.15.1, 0.15.2, 0.15.3, 0.16.0, 0.16.1, 0.16.2, 0.16.3, 0.16.4, 0.16.5, 0.16.6, 0.17.0, 0.17.1, 0.17.2, 0.17.3, 0.17.4, 0.18.0, 0.18.1, 0.18.2, 0.18.3, 0.18.4, 0.19.0, 0.20.0, 0.20.1, 0.20.2, 0.21.0, 0.21.1, 0.21.2, 0.21.4, 0.21.5, 0.21.6, 0.22.0a0, 0.22.0b0, 0.22.0b1, 0.22.0b2, 0.22.0b3, 0.22.0b4, 0.22.0b5, 0.22.0b6, 0.22.0, 0.22.1, 0.22.2, 0.22.3, 0.22.4, 0.22.5, 1.0.0, 1.0.1, 1.0.2, 1.0.3, 1.0.5, 1.1.0, 1.1.1, 1.1.2, 1.1.3, 1.1.4, 1.1.5, 1.1.6, 1.2.0, 1.3.0, 1.3.1, 1.3.2, 1.3.3, 1.3.4, 1.3.5, 2.0.0rc1, 2.0.0, 2.0.1, 2.0.2, 2.0.3, 2.0.4, 2.0.5, 2.0.6, 2.0.6.post1, 2.0.7, 2.1.0, 2.2.0, 2.2.1, 2.2.2, 2.2.3, 2.2.4, 2.2.5, 2.3.0a1, 2.3.0a2, 2.3.0a4, 2.3.0, 2.3.1a1, 2.3.1, 2.3.2b2, 2.3.2b3, 2.3.2, 2.3.3, 2.3.4, 2.3.5, 2.3.6, 2.3.7, 2.3.8, 2.3.9, 2.3.10, 3.0.0b0)
No matching distribution found for aiohttp>=3.4.4 (from aiogram)

Bot API 4.0 // aiogram 1.4

This update will be based on dev-1.x branch and after relese will be merged into dev-2.x.

Text of Bot API release notes:

  • Added support for Telegram Passport. See the official announcement on the blog and the manual for details.
  • Added support for editing the media content of messages: added the method editMessageMedia and new types inputMediaAnimation, inputMediaAudio, and inputMediaDocument.
  • Added the field thumb to the Audio object to contain the thumbnail of the album cover to which the music file belongs.
  • Added support for attaching custom thumbnails to uploaded files. For animations, audios, videos and video notes, which are less than 10 MB in size, thumbnails are generated automatically.
  • tg:// URLs now can be used in inline keyboard url buttons and text_link message entities.
  • Added the method sendAnimation, which can be used instead of sendDocument to send animations, specifying their duration, width and height.
  • Added the field animation to the Message object. For backward compatibility, when this field is set, the document field will be also set.
  • Added two new MessageEntity types: cashtag and phone_number.
  • Added support for Foursquare venues: added the new field foursquare_type to the objects Venue, InlineQueryResultVenue and InputVenueMessageContent, and the parameter foursquare_type to the sendVenue method.
  • You can now create inline mentions of users, who have pressed your bot's callback buttons.
  • You can now use the Retry-After response header to configure the delay after which the Bot API will retry the request after an unsuccessful response from a webhook.
  • If a webhook returns the HTTP error 410 Gone for all requests for more than 23 hours successively, it can be automatically removed.
  • Added vCard support when sharing contacts: added the field vcard to the objects Contact, InlineQueryResultContact, InputContactMessageContent and the method sendContact.

Async timer

Need help, how to use timer, to make actions every hour (for example)
As I understand, it's possible to make a special async def, for comparing current time with the time from database

Imposible to download file into directory

Context

  • Operating System: Arch Linux
  • Python Version: 3.7.3
  • aiogram version: 2.2
  • aiohttp version: 3.5.4

Expected Behavior

Able to download file into specified directory.

Current Behavior

Got IsADirectoryError exception.

Failure Information (for bugs)

Problem lay in line https://github.com/aiogram/aiogram/blob/dev-2.x/aiogram/types/mixins.py#L27:

os.path.join(destination, file.file_path)

which is noop in current context.

Steps to Reproduce

  1. Setup message handler:
async def new_photo(message: types.Message):
    await message.photo[0].download(destination='/path/to/existing/directory')
  1. Send photo to bot.
  2. Get tracelog with IsADirectoryError exception.

Send data from middlewares to filters

In middleware, I get a user object from the database, but it is not passed to filters.
I think we need to replace
data.update(await check_filters(handler_obj.filters, args)) in handler
on
data.update(await check_filters(handler_obj.filters, args + (data,)))

Cannot install aiogram from tar.gz archive


name: Bug report
about: Create a report to help us improve


Context

  • Operating System: GNU/Linux 4.18.7-1-default, openSUSE Tumbleweed
  • Python Version: 3.7.0
  • aiogram version: 2.0
  • aiohttp version: Irrelevant
  • uvloop version (if installed): Irrelevant

Expected Behavior

I run pip install https://files.pythonhosted.org/packages/b8/78/64dff7c69f21df0383bf442060a44c4dbf8842bd454c03858c11fa483330/aiogram-2.0.tar.gz and it installs fine.

Current Behavior

$ pip install https://files.pythonhosted.org/packages/b8/78/64dff7c69f21df0383bf442060a44c4dbf8842bd454c03858c11fa483330/aiogram-2.0.tar.gz       
Looking in indexes: https://pypi.kama.gs/tech/index, https://pypi.org/simple
Collecting https://files.pythonhosted.org/packages/b8/78/64dff7c69f21df0383bf442060a44c4dbf8842bd454c03858c11fa483330/aiogram-2.0.tar.gz                               
  Using cached https://files.pythonhosted.org/packages/b8/78/64dff7c69f21df0383bf442060a44c4dbf8842bd454c03858c11fa483330/aiogram-2.0.tar.gz                           
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "/home/rominf/.pyenv/versions/3.7.0/envs/kgjirabot-3.7.0/lib/python3.7/site-packages/pip/_internal/download.py", line 437, in get_file_content              
        with open(url, 'rb') as f:
    FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pip-req-build-7tlnzhry/requirements.txt'                                                             

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-req-build-7tlnzhry/setup.py", line 82, in <module>
        install_requires=get_requirements()
      File "/tmp/pip-req-build-7tlnzhry/setup.py", line 58, in get_requirements
        return [str(ir.req) for ir in install_reqs]
      File "/tmp/pip-req-build-7tlnzhry/setup.py", line 58, in <listcomp>
        return [str(ir.req) for ir in install_reqs]
      File "/home/rominf/.pyenv/versions/3.7.0/envs/kgjirabot-3.7.0/lib/python3.7/site-packages/pip/_internal/req/req_file.py", line 80, in parse_requirements         
        filename, comes_from=comes_from, session=session
      File "/home/rominf/.pyenv/versions/3.7.0/envs/kgjirabot-3.7.0/lib/python3.7/site-packages/pip/_internal/download.py", line 441, in get_file_content              
        'Could not open requirements file: %s' % str(exc)
    pip._internal.exceptions.InstallationError: Could not open requirements file: [Errno 2] No such file or directory: '/tmp/pip-req-build-7tlnzhry/requirements.txt'  

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-req-build-7tlnzhry/ 

Failure Information (for bugs)

Steps to Reproduce

Run the command above.

Failure Logs

See above.

Why?

I need this because access to pypi.org is blocked and I want to install from archive (it can be downloaded before the installation).

Adding timeout for Bot API methods.

Is your feature request related to a problem? Please describe.
The problem is that Bot API doesn't send any errors, if bot got limited with some methods, like delete_message. Example code:

l=[(i, -1000-i) for i in range(1000)]
for i in l:
   try:
      await bot.delete_message(message_id=max(i), chat_id=min(i))
   except Exception:
       pass

If there are no await asyncio.sleep(), a bot will freeze after deleting ~700-800 msgs. No exceptions will raise, but the process will be completely blocked.

Describe the solution you'd like
The best way to solve this problem is by adding timeout for every method, e.g. in aiogram.Bot params.

Additional context
Example: INFO:bot:Process update [ID:711526853]: [success] (in 15379 ms)

aiohttp ClientConnectorSSLError: SSL certificate verify failed

There are troubles with broken SSL certs bundle. (Reported from OS X)
aiogram.utils.exceptions.NetworkError: Aiohttp client throws an error: ClientConnectorSSLError: Cannot connect to host api.telegram.org:443 ssl:True [[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:777)]

TypeError with LazyProxy object in keyboards

_ = i18n.lazy_gettext

async def main():
    await bot.send_message(..., reply_markup=types.InlineKeyboardMarkup()
                           .add(types.InlineKeyboardButton(_("Test"))))
    await bot.send_message(..., reply_markup=types.ReplyKeyboardMarkup([[
        types.KeyboardButton(_("Test"))
    ]]))

TypeError: Object of type LazyProxy is not JSON serializable

The error occurs in the prepare_arg function. I think we can implement the check for LazyProxy somewhere here. Of course, it should lead to change of the text field type in InlineKeyboardButton and KeyboardButton

Of course, this is not a bug, but use of LazyProxy in keyboards simplifies localization, because we do not have to generate a keyboard every time.

Send content to channel using bot

Hi guys,

I'm newbie in aiogram, I want to send data to my channel using bot, I've already add my bot to my channel as administrator, but how can I send content via this package?

Thanks

Let the SOCKS proxy to resolve hostname

The problem is if the telegram api is blocked by provider then in some cases you can not connect to telegram because of redirection (rewriting dns by provider? i don't know).

The solution is to resolve hostname by socks proxy. aiohttp_socks SocksConnector has the special parameter rdns which allows to do this.

It would be great to have ability to specify this option as parameter in Bot constructor.

Need to check real IP address for proxy deployments or document behaviour

Checking the X-Forwarded-For header field for IP address filtering here might not be enough for some deployments.

E.g.

  • The bot is bind on 0.0.0.0 and an appropriate firewall rule is not used
  • The bot is bind on a public Internet IP address to which a different server forwards Telegram packets and an appropriate firewall rule is not used

The exemplified use cases are (hopefully) unusual but still very possible, especially in testing environments. In each of these cases, one could easily impersonate Telegram by sending HTTP requests to the server's public IP address and forging the X-Forwarded-For header field.
Although this does seem more like a IT administration issue than an aiogram issue, I think this should at least be documented, since a developer (especially one that's less-then-savvy with computer networks) could legitimately presume that the IP address filtering functionality would provide complete security against such attacks. I could also imagine larger deployments in which the above presumptions could be true for performance reasons.

If you are also considering a hard fix, here are some ideas:

  • Add default logic to presume that non-HTTPS deployments should only be local (and from a local IP address), only allow a different behavior if explicitly enabled (secure by default, no need to break code compatibility)
  • Change the IP address filtering option to force the developer to explicitly state what should be in the X-Forwarded-For HTTP header field instead of determining it through the current logic (secure by updating bot code, probably breaks code compatibility)

Use different bot tokens in the same time

Feature request

Discussion: @aiogram_ru#37921
In some cases need to create temporary instance of bot with different tokens. For example for managers of bot's and etc.

Now it can be done as follows:

You need to create new instance of bot and after all required actions close the session

await tmp_bot.get_me()  # -> @FooBot
try:
   tmp_bot = Bot('TOKEN HERE')  # Create instance of bot
   tmp_bot.get_me()  # -> @BarBot
finally:
  await tmp_bot.close()  # Close bot session
await tmp_bot.get_me()  # -> @FooBot

What can a solution look like?

contextvars can be used for do that with context manager.

await tmp_bot.get_me()  # -> @FooBot
with bot.with_token('TOKEN HERE'):  # Setup token into context
    await bot.get_me()  # This request will be use token from context. // -> @FooBot  
await bot.get_me()  # -> @BarBot

But need to don't forget about cachable property (await bot.me). Need prevent to use that while token is changed.

This solution use one instance of bot, don't create more aiohttp client sessions, more easy for configuring and doesn't require a lot of additional code from bot developer.

"date" field in Message object is returned incorrectly

As seen in documentation:
date | Integer | Date the message was sent in Unix time

Aiogram returns formatted datetime instead which is incorrect (expected integer as seen in docs) and makes harder to port code from other libraries.

Test case:

@dp.message_handler()
async def show_datetime(message: types.Message):
    print(message.date)
    return

Expected output:
>>> 1532863711

Got output:
>>> 2018-07-29 11:28:31

Migrate to Python 3.7 (aiogram 2.0)

This update will break backward compability with Python 3.6 in some reasons:

  1. contextvars (PEP-567);
  2. New syntax for annotations (PEP-563).

Plans:

  • Use contextvars instead of current mechanism of execution context variables;
  • Merge branch filters-factory into dev-2.x;
  • Implement mechanism of passing results from filters (as dicts) as kwargs in handlers (like fixtures in pytest);
  • Allow to change from middlewares returned data from filters before it will be passed to handler.
  • Improve Filters-factory feature;
  • Implement i18n middleware;
  • States group feature (FSM improvements);
  • Allow to customize command prefix in CommandsFilter;
  • Bot API 4.0 (merge from master);
  • Rewrite file uploading mechanism;
  • Fix storage's (MemoryStorage: mutability)
  • Allow to use python-rapidjson instead of ujson/json
  • Implement pipe for uploading files from URL;
  • Write instruction for migrating from v1.x to v2.x;

Delayed:

  • Update examples;
  • Make an webhook security improvements (#47) (Write instructions);
  • Change error detection mechanism (from aiograph);
  • Improve documentation;
  • (Canceled) Allow to use any HTTP Client library (Implement connectors);
  • (Deferred) Implement utils for Telegram Passport;

Schedule:

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.