kandi background
Explore Kits

aiogram | pretty simple and fully asynchronous framework | Bot library

 by   aiogram Python Version: v2.20 License: MIT

 by   aiogram Python Version: v2.20 License: MIT

Download this library from

kandi X-RAY | aiogram Summary

aiogram is a Python library typically used in Automation, Bot applications. aiogram has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has medium support. You can install using 'pip install aiogram' or download it from GitHub, PyPI.
aiogram is a pretty simple and fully asynchronous framework for Telegram Bot API written in Python 3.7 with asyncio and aiohttp. It helps you to make your bots faster and simpler.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • aiogram has a medium active ecosystem.
  • It has 2538 star(s) with 490 fork(s). There are 90 watchers for this library.
  • There were 1 major release(s) in the last 6 months.
  • There are 54 open issues and 274 have been closed. On average issues are closed in 112 days. There are 24 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of aiogram is v2.20
aiogram Support
Best in #Bot
Average in #Bot
aiogram Support
Best in #Bot
Average in #Bot

quality kandi Quality

  • aiogram has 0 bugs and 0 code smells.
aiogram Quality
Best in #Bot
Average in #Bot
aiogram Quality
Best in #Bot
Average in #Bot

securitySecurity

  • aiogram has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • aiogram code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
aiogram Security
Best in #Bot
Average in #Bot
aiogram Security
Best in #Bot
Average in #Bot

license License

  • aiogram is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
aiogram License
Best in #Bot
Average in #Bot
aiogram License
Best in #Bot
Average in #Bot

buildReuse

  • aiogram releases are available to install and integrate.
  • Deployable package is available in PyPI.
  • Build file is available. You can build the component from source.
  • Installation instructions are not available. Examples and code snippets are available.
  • aiogram saves you 6541 person hours of effort in developing the same functionality from scratch.
  • It has 15155 lines of code, 1522 functions and 180 files.
  • It has medium code complexity. Code complexity directly impacts maintainability of the code.
aiogram Reuse
Best in #Bot
Average in #Bot
aiogram Reuse
Best in #Bot
Average in #Bot
Top functions reviewed by kandi - BETA

kandi has reviewed aiogram and discovered the below as its top functions. This is intended to give you an instant insight into aiogram implemented functionality, and help decide if they suit your requirements.

  • Use this method to send an invoice .
  • Reply to a poll .
  • Setup the filters .
  • Process a message .
  • Initialize a chat .
  • Promote a user to a member .
  • Download a file .
  • Mark a function as deprecated .
  • Decorator to mark a function as renamed .
  • Check the result of a method .

aiogram Key Features

Is a pretty simple and fully asynchronous framework for Telegram Bot API written in Python 3.7 with asyncio and aiohttp.

Simple

copy iconCopydownload iconDownload
import asyncio
from aiogram import Bot

BOT_TOKEN = ""

async def main():
    bot = Bot(token=BOT_TOKEN)

    try:
        me = await bot.get_me()
        print(f"🤖 Hello, I'm {me.first_name}.\nHave a nice Day!")
    finally:
        await bot.close()

asyncio.run(main())

Poll BotAPI for updates and process updates

copy iconCopydownload iconDownload
import asyncio
from aiogram import Bot, Dispatcher, types

BOT_TOKEN = ""

async def start_handler(event: types.Message):
    await event.answer(
        f"Hello, {event.from_user.get_mention(as_html=True)} 👋!",
        parse_mode=types.ParseMode.HTML,
    )

async def main():
    bot = Bot(token=BOT_TOKEN)
    try:
        disp = Dispatcher(bot=bot)
        disp.register_message_handler(start_handler, commands={"start", "restart"})
        await disp.start_polling()
    finally:
        await bot.close()

asyncio.run(main())

Python aiogram: state switch

copy iconCopydownload iconDownload
class SomeStates(StatesGroup):
    MAIN_MENU = State()
    PARSING_WORD = State()
    PARSING_NUMBER = State()
    HELP_MENU = State()
    FAQ_MENU = State()
    

@dp.message_handler(text='Parse', state="*")
async def process_parse_command(msg: types.Message):
    await msg.reply(f"What words to watch for?\n")
    stat = dp.current_state(user=msg.from_user.id)
    print(stat)
    await stat.set_state(SomeStates.PARSING_WORD)


@dp.message_handler(state=SomeStates.PARSING_WORD)
async def process_parse_word(msg: types.Message):
    # there was a mistake here
    # argument = message.get_args() - NameError: name 'message' is not defined
    # argument = msg.get_args() # None is here, better use message.text
    argument = msg.text
    print(argument) 
    stat = dp.current_state(user=msg.from_user.id)
    print(stat)

How to send dataframes tables in telegram bot using python

copy iconCopydownload iconDownload
import pandas as pd

pd.set_option('display.max_columns', None)

# Your code here

Dont send message with inlinekeyboard pyrogram

copy iconCopydownload iconDownload
btn = pyrokbbut(text,url=url)
kb = pyrokbmk(inline_keyboard=[btn])
keyboard = [  # List of rows:
    [button, button],  # First Row
    [button],  # Second Row
]
-----------------------
btn = pyrokbbut(text,url=url)
kb = pyrokbmk(inline_keyboard=[btn])
keyboard = [  # List of rows:
    [button, button],  # First Row
    [button],  # Second Row
]

asyncpg + aiogram. cannot perform operation: another operation is in progress

copy iconCopydownload iconDownload
...
data_ = {}


class Database:

    def __init__(self, pool: asyncpg.create_pool):
        self.pool = pool

    async def get_lang(self, user_id, token):
        search_d = [user_id, token]

        async with self.pool.acquire() as conn:
            res = await conn.fetchval(SELECT_USER_LANG, *search_d)

        if res is None:
            return "ru"
        return res


async def create_pool():
    pool = await asyncpg.create_pool(**LOG_PG)
    data_["db"] = Database(pool)


async def echo_msg(message: Message):
    user_id = message.from_user.id

    await message.send_copy(user_id)
    await data_["db"].get_lang(user_id, token)

dp.message.register(callback=echo_msg)

if __name__ == '__main__':
    dp.startup.register(create_pool) # ANSWER
    dp.run_polling(bot, skip_updates=True)

Accept a request to subscribe to a private telegram channel via aiogram

copy iconCopydownload iconDownload
    @dp.chat_join_request_handler()
    async def echo(message: types.Message):
         await bot.approve_chat_join_request(
                      message.chat.id,                                   
                      message.from_user.id)
-----------------------
@dp.chat_join_request_handler()
async def join(update: types.ChatJoinRequest):
    await update.approve()

aiogram - How to execute a function?

copy iconCopydownload iconDownload
@dp.message_handler()
async def echo(message: types.Message):
    await bot.send_message(message.chat.id, message.text)
2021-06-01 09:31:42,729:INFO:Bot: YourBot [@YourBot]
2021-06-01 09:31:42,729:WARNING:Updates were skipped successfully.
2021-06-01 09:31:42,729:INFO:Start polling.
-----------------------
@dp.message_handler()
async def echo(message: types.Message):
    await bot.send_message(message.chat.id, message.text)
2021-06-01 09:31:42,729:INFO:Bot: YourBot [@YourBot]
2021-06-01 09:31:42,729:WARNING:Updates were skipped successfully.
2021-06-01 09:31:42,729:INFO:Start polling.
-----------------------
from aiogram import Bot, Dispatcher, executor, types

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

@dp.message_handler()
async def echo(message: types.Message):
   await bot.send_message(message.chat.id, message.text)

def test_hi():
   print("Hello World")

if __name__ == '__main__':
   test_hi()
   executor.start_polling(dp, skip_updates=True)
-----------------------
from asyncio import get_event_loop
from aiogram import Bot, Dispatcher, executor, types

API_TOKEN = 'API'

bot = Bot(token=API_TOKEN)
dp = Dispatcher(bot=bot, loop=get_event_loop())  # Initialising event loop for the dispatcher

async def notify_message():
    print('Hello World')

if __name__ == '__main__':
    dp.loop.create_task(notify_message())  # Providing awaitable as an argument
    executor.start_polling(dp, skip_updates=True)
-----------------------
from aiogram import Bot, Dispatcher, executor

bot = Bot(token='your_api_token')
dp = Dispatcher(bot)

async def notify_message() # THIS FUNCTION
  # await bot.sendMessage(chat.id, 'Bot Started')
  await print('Hello World')

@dp.message_handler()
async def echo(message: types.Message):
  await message.answer(message.text)

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

send_media_group with BytesIO to telegram bot

copy iconCopydownload iconDownload
# Some code is omitted in favor of brievity

def wrap_media(bytesio, **kwargs):
    """Wraps plain BytesIO objects into InputMediaPhoto"""
    # First, rewind internal file pointer to the beginning so the contents
    #  can be read by InputFile class
    bytesio.seek(0)
    return types.InputMediaPhoto(types.InputFile(bytesio), **kwargs)

@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
    await message.answer_media_group([wrap_media(createimg()), wrap_media(createimg())])

Why is the response from the user not recorded in the database?

copy iconCopydownload iconDownload
with self.connection:
    self.connection.execute("INSERT INTO 'clients' ('user_id') VALUES (?)", (user_id,))
with contextlib.closing(self.connection.cursor()) as cursor:
    cursor.execute(...)
-----------------------
with self.connection:
    self.connection.execute("INSERT INTO 'clients' ('user_id') VALUES (?)", (user_id,))
with contextlib.closing(self.connection.cursor()) as cursor:
    cursor.execute(...)

How to implement automatic reloading of the python aiogram bot?

copy iconCopydownload iconDownload
/lib/systemd/system/myBot.service 
[Unit]
Description=myBot - Telegram bot
After=network.target

[Service]
ExecStart=/opt/mybot/myBot.py
WorkingDirectory=/opt/mybot/
KillMode=process
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
systemctl enable myBbot
systemctl start myBot
systemctl status myBot
systemctl stop myBot
systemctl daemon-reload
-----------------------
/lib/systemd/system/myBot.service 
[Unit]
Description=myBot - Telegram bot
After=network.target

[Service]
ExecStart=/opt/mybot/myBot.py
WorkingDirectory=/opt/mybot/
KillMode=process
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
systemctl enable myBbot
systemctl start myBot
systemctl status myBot
systemctl stop myBot
systemctl daemon-reload
-----------------------
/lib/systemd/system/myBot.service 
[Unit]
Description=myBot - Telegram bot
After=network.target

[Service]
ExecStart=/opt/mybot/myBot.py
WorkingDirectory=/opt/mybot/
KillMode=process
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
systemctl enable myBbot
systemctl start myBot
systemctl status myBot
systemctl stop myBot
systemctl daemon-reload
-----------------------
/lib/systemd/system/myBot.service 
[Unit]
Description=myBot - Telegram bot
After=network.target

[Service]
ExecStart=/opt/mybot/myBot.py
WorkingDirectory=/opt/mybot/
KillMode=process
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
systemctl enable myBbot
systemctl start myBot
systemctl status myBot
systemctl stop myBot
systemctl daemon-reload
-----------------------
/lib/systemd/system/myBot.service 
[Unit]
Description=myBot - Telegram bot
After=network.target

[Service]
ExecStart=/opt/mybot/myBot.py
WorkingDirectory=/opt/mybot/
KillMode=process
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
systemctl enable myBbot
systemctl start myBot
systemctl status myBot
systemctl stop myBot
systemctl daemon-reload
-----------------------
/lib/systemd/system/myBot.service 
[Unit]
Description=myBot - Telegram bot
After=network.target

[Service]
ExecStart=/opt/mybot/myBot.py
WorkingDirectory=/opt/mybot/
KillMode=process
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
systemctl enable myBbot
systemctl start myBot
systemctl status myBot
systemctl stop myBot
systemctl daemon-reload
-----------------------
/lib/systemd/system/myBot.service 
[Unit]
Description=myBot - Telegram bot
After=network.target

[Service]
ExecStart=/opt/mybot/myBot.py
WorkingDirectory=/opt/mybot/
KillMode=process
Restart=always
RestartSec=5

[Install]
WantedBy=multi-user.target
systemctl enable myBbot
systemctl start myBot
systemctl status myBot
systemctl stop myBot
systemctl daemon-reload

Can I run a coroutine in python independently from all other code?

copy iconCopydownload iconDownload
from threading import Thread
from time import sleep

# Here is a function that uses the sleep() function. If you called this directly, it would stop the main Python execution
def my_independent_function():
    print("Starting to sleep...")
    sleep(10)
    print("Finished sleeping.")

# Make a new thread which will run this function
t = Thread(target=my_independent_function)
# Start it in parallel
t.start()

# You can see that we can still execute other code, while other function is running
for i in range(5):
    print(i)
    sleep(1)
Starting to sleep...
0
1
2
3
4

Finished sleeping.
-----------------------
from threading import Thread
from time import sleep

# Here is a function that uses the sleep() function. If you called this directly, it would stop the main Python execution
def my_independent_function():
    print("Starting to sleep...")
    sleep(10)
    print("Finished sleeping.")

# Make a new thread which will run this function
t = Thread(target=my_independent_function)
# Start it in parallel
t.start()

# You can see that we can still execute other code, while other function is running
for i in range(5):
    print(i)
    sleep(1)
Starting to sleep...
0
1
2
3
4

Finished sleeping.

Community Discussions

Trending Discussions on aiogram
  • Python aiogram: state switch
  • How to send dataframes tables in telegram bot using python
  • Dont send message with inlinekeyboard pyrogram
  • TraceBack Cannot connect to host api.telegram.org:443
  • Python aiogram bot: send message from another thread
  • asyncpg + aiogram. cannot perform operation: another operation is in progress
  • Accept a request to subscribe to a private telegram channel via aiogram
  • aiogram - How to execute a function?
  • send_media_group with BytesIO to telegram bot
  • I can’t get the user id
Trending Discussions on aiogram

QUESTION

Python aiogram: state switch

Asked 2022-Mar-31 at 17:44

I am learning aiogram, and trying to get some messages as args for funtion call. As I learned from internet I should use State Machine

First I ask for some args and change state, to catch next message

@dp.message_handler(text='Parse', state="*")
async def process_parse_command(msg: types.Message):
    await msg.reply(f"What words to watch for?\n", reply_markup=remove_kb)
    stat = dp.current_state(user=msg.from_user.id)
    await stat.set_state(SomeStates.PARSING_WORD)

Next I try to catch any message when I am on another state

@dp.message_handler(state=SomeStates.PARSING_WORD)
async def process_parse_word(msg: types.Message):
    argument = message.get_args()
    print(argument)
    stat = dp.current_state(user=msg.from_user.id)
    print(stat)

upd: this is my utils file

from aiogram.utils.helper import Helper, HelperMode, ListItem
class SomeStates(Helper):
    mode = HelperMode.snake_case

    MAIN_MENU = ListItem()
    PARSING_WORD = ListItem()
    PARSING_NUMBER = ListItem()
    HELP_MENU = ListItem()
    FAQ_MENU = ListItem()

But second message_handler is never called [TG screenshot][1] [1]: https://i.stack.imgur.com/81edC.png

Maybe I got something wrong about State Machine, but in the example lesson everything worked

ANSWER

Answered 2022-Mar-31 at 17:44

There are StatesGroup Class in aiogram, rewrite your code like this and it works

class SomeStates(StatesGroup):
    MAIN_MENU = State()
    PARSING_WORD = State()
    PARSING_NUMBER = State()
    HELP_MENU = State()
    FAQ_MENU = State()
    

@dp.message_handler(text='Parse', state="*")
async def process_parse_command(msg: types.Message):
    await msg.reply(f"What words to watch for?\n")
    stat = dp.current_state(user=msg.from_user.id)
    print(stat)
    await stat.set_state(SomeStates.PARSING_WORD)


@dp.message_handler(state=SomeStates.PARSING_WORD)
async def process_parse_word(msg: types.Message):
    # there was a mistake here
    # argument = message.get_args() - NameError: name 'message' is not defined
    # argument = msg.get_args() # None is here, better use message.text
    argument = msg.text
    print(argument) 
    stat = dp.current_state(user=msg.from_user.id)
    print(stat)

Aiogram official documentation using StatesGroup for FSM

Source https://stackoverflow.com/questions/71573487

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install aiogram

You can install using 'pip install aiogram' or download it from GitHub, PyPI.
You can use aiogram like any standard Python library. You will need to make sure that you have a development environment consisting of a Python distribution including header files, a compiler, pip, and git installed. Make sure that your pip, setuptools, and wheel are up to date. When using pip it is generally recommended to install packages in a virtual environment to avoid changes to the system.

Support

For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with aiogram
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.