Skip to main content

Running aiogram in neighbor container, sending messages to telegram via redis

Project description

django-redis-aiogram

django-redis-aiogram provides a quick way to install aiogram in a container adjacent to django, allowing you to use your own router and loop. Also allows you to send messages through redis.

Installation

The easiest and recommended way to install django-redis-aiogram is from PyPI

pip install django-redis-aiogram

You need to add telegram_bot to INSTALLED_APPS in your projects settings.py.

# settings.py

INSTALLED_APPS = (
    ...
    'telegram_bot',
    ...
)

Also, you need to specify the minimum settings:

# settings.py

TELEGRAM_BOT = {
    'REDIS_URL': REDIS_URL,
    'TOKEN': TELEGRAM_BOT_TOKEN,
}

Next, add a separate container to your docker-compose.yml. (optional, if you want to use routers and handlers)

# docker-compose.yml

services:
  ...
  
  telegram_bot:
    container_name: telegram_bot
    restart: always
    command: python manage.py start_tgbot
    build:
      context: ./

Example Usage

To send a message, use the following code:

# test.py

from aiogram import types, F
from telegram_bot import bot

# sending a message directly
bot.send_raw(chat_id=CHAT_ID, text=TEXT)
bot.send_raw('send_photo', chat_id=CHAT_ID, caption=TEXT, photo=URL)

# sending a message via redis
bot.send_redis(chat_id=CHAT_ID, text=TEXT)
bot.send_redis('send_photo', chat_id=CHAT_ID, caption=TEXT, photo=URL)

# markup example
markup = types.InlineKeyboardMarkup(inline_keyboard=[
    [types.InlineKeyboardButton(
        text='best project ever',
        web_app=types.WebAppInfo(url='https://pypi.org/project/django-redis-aiogram')
    )]
])

bot.send_raw(chat_id=CHAT_ID, text=TEXT, reply_markup=markup)
bot.send_redis(chat_id=CHAT_ID, text=TEXT, reply_markup=markup)


# if RAISE_EXCEPTION is True, you can use try-except to handle errors from send_raw
from aiogram.exceptions import TelegramBadRequest

try:
    bot.send_raw(chat_id=CHAT_ID, text='**test*', parse_mode='Markdown')
except TelegramBadRequest:
    print('Telegram bad request :)')

If you need to use handlers, create file tg_router.py (by default) in your app, use the following code:

from aiogram import types, F
from telegram_bot import bot


@bot.message(F.text.startswith('/start'))
async def start_handler(message: types.Message) -> None:
    await message.answer('hi')


@bot.message()
async def simple_handler(message: types.Message) -> None:
    await message.reply(message.text)

You can use all handler types like in aiogram.

Settings

You can override settings:

# settings.py

def default_kwargs(function: str) -> dict[str, Any]:
    """Default kwargs for telegram bot functions."""
    prepared_dict = {
        'send_message': {'parse_mode': 'HTML'},
        'send_photo': {'parse_mode': 'Markdown', 'caption': '`Photo`'}
    }
    return prepared_dict.get(function, {})

TELEGRAM_BOT = {
    {
    # event expiration time in redis
    'REDIS_EXP_TIME': 5,
    # redis key for handling expired event
    'REDIS_EXP_KEY': 'TELEGRAM_BOT_EXP',
    # redis key for collecting messages
    'REDIS_MESSAGES_KEY': 'TELEGRAM_BOT_MESSAGE',
    # name of the module to find
    'MODULE_NAME': 'tg_router',
    # default kwargs for telegram bot
    'DEFAULT_KWARGS': default_kwargs,
    # telegram bot token
    'TOKEN': <TELEGRAM_BOT_TOKEN>,
    # url for redis connection
    'REDIS_URL': <REDIS_URL>,
    # max retries for sending message
    'MAX_RETRIES': 10,
    # raise exception if error occurred
    'RAISE_EXCEPTION': False
}

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django-redis-aiogram-1.0.8.tar.gz (7.9 kB view details)

Uploaded Source

Built Distribution

django_redis_aiogram-1.0.8-py3-none-any.whl (9.8 kB view details)

Uploaded Python 3

File details

Details for the file django-redis-aiogram-1.0.8.tar.gz.

File metadata

  • Download URL: django-redis-aiogram-1.0.8.tar.gz
  • Upload date:
  • Size: 7.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.0.0 CPython/3.11.6

File hashes

Hashes for django-redis-aiogram-1.0.8.tar.gz
Algorithm Hash digest
SHA256 10cdefa64628f50535bc88001f417a7f4b5ff19a0b0c415a269a88071c5d1126
MD5 5db2492a92295ccdde331194051fcf7b
BLAKE2b-256 6d4da011b7996b0766151c5a32f1b201e17372147f68063c9d1a49e7f274dc29

See more details on using hashes here.

File details

Details for the file django_redis_aiogram-1.0.8-py3-none-any.whl.

File metadata

File hashes

Hashes for django_redis_aiogram-1.0.8-py3-none-any.whl
Algorithm Hash digest
SHA256 0e8516757bc29a3c294e877db49e98adc4d8094d914d6b402abeb527b3faba30
MD5 4b3b05dd8fdc27448e00447a77ee2554
BLAKE2b-256 be5bef1b9ad0f0baa96a7766c118da8fa68920f37b08a1e165baf6bdd78c7b6f

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page