Skip to main content

A simple and easy-to-use Python wrapper for Telegram bots.

Project description

Simple Telegram API

A simple and easy-to-use Python wrapper for Telegram bots. This library allows you to send messages, edit messages, fetch updates, handle messages, and run continuous loops easily.

Getting a Bot Token

To get a bot token, message @BotFather on Telegram and follow the instructions to create a new bot. BotFather will provide you with a token that looks like 123456789:ABCdefGHIjklmNOPQrstUVwxyz.

Installation

uv is recommended for managing and installing packages in isolated environments.

uv add simple-telegram-api

You can also install it using pip:

pip install simple-telegram-api

Usage/Examples

A simple echo bot:

from simple_telegram_api import TelegramBot

bot = TelegramBot("BOT_TOKEN")

def echo_bot():
    updates = bot.get_updates()
    if updates["result"]:
        for update in updates["result"]:
            text, chat_id = (
                update["message"]["text"],
                update["message"]["chat"]["id"],
            )
            bot.send_message(text, chat_id)

        # Update offset to skip already processed messages in future calls.
        bot.reset_updates(updates=updates)

if __name__ == "__main__":
    bot.start_loop(echo_bot)

Using the TelegramBot Class

from simple_telegram_api import TelegramBot

bot = TelegramBot("BOT_TOKEN")

Get Bot Information

Get information about your bot:

bot_info = bot.get_me()
print(bot_info)

Get Updates

This function gets new messages from Telegram with optional parameters:

# Basic usage
updates = bot.get_updates()

# Advanced usage with parameters
updates = bot.get_updates(
    offset=None,          # Identifier of the first update to be returned
    limit=100,            # Limits the number of updates (1-100)
    timeout=0,            # Timeout in seconds for long polling
    allowed_updates=None  # List of update types to receive
)

Example Get Updates Output

Here is an example of the output from the get_updates() function:

{
    'ok': True,
    'result': [
        {
            'update_id': 123456789,
            'message': {
                'message_id': 123,
                'from': {
                    'id': 123456789,
                    'is_bot': False,
                    'first_name': 'Person Name',
                    'username': 'username',
                    'language_code': 'en'
                },
                'chat': {
                    'id': 123456789,
                    'first_name': 'Person Name',
                    'username': 'username',
                    'type': 'private'
                },
                'date': 123456789,
                'text': 'Hello!'
            }
        }
    ]
}

Reset Updates

This function deletes old messages from updates. If no updates are provided, it will automatically fetch new ones:

# With updates parameter (Recommended)
bot.reset_updates(updates=updates)

# Without updates parameter (will fetch automatically)
bot.reset_updates()

Send Message

To send a message:

bot.send_message(text="Hello!", chat_id=chat_id)

To send a message with additional parameters:

bot.send_message(
    text="Hello!",
    chat_id=chat_id,
    parse_mode="Markdown",
    reply_to_message_id=message_id
)

Example Send Message Output

Here is an example of the output from the send_message() function:

{
    'ok': True,
    'result': {
        'message_id': 123,
        'from': {
            'id': 1234567890,
            'is_bot': True,
            'first_name': 'Bot',
            'username': 'my_bot'
        },
        'chat': {
            'id': 123456789,
            'first_name': 'Person Name',
            'username': 'username',
            'type': 'private'
        },
        'date': 123456789,
        'text': 'Hello!'
    }
}

Edit Message

Edit an existing message:

bot.edit_message(text="Updated text", chat_id=chat_id, message_id=message_id)

Edit with additional parameters:

bot.edit_message(
    text="Updated text",
    chat_id=chat_id,
    message_id=message_id,
    parse_mode="Markdown"
)

Example Edit Message Output

Here is an example of the output from the edit_message() function:

{
    'ok': True,
    'result': {
        'message_id': 123,
        'from': {
            'id': 1234567890,
            'is_bot': True,
            'first_name': 'Bot',
            'username': 'my_bot'
        },
        'chat': {
            'id': 123456789,
            'first_name': 'Person Name',
            'username': 'username',
            'type': 'private'
        },
        'date': 123456789,
        'edit_date': 123456790,
        'text': 'Updated text'
    }
}

Start Loop

Run continuous callback functions at set intervals:

def get_messages():
    # Function to retrieve messages (to be implemented)
    pass

def say_hello():
    # This function will be called repeatedly by the loop
    pass

# Start the loop, calling get_messages and say_hello every 1 second
bot.start_loop(get_messages, say_hello, interval=1.0)

Error Handling

The library includes custom exception:

  • TelegramBotError: TelegramBot Error.

Recommendations

  • If updates is not provided in reset_updates(), new updates will be fetched automatically
  • Use the result from get_updates() as updates parameter in reset_updates() for better performance
  • Use the start_loop() method for continuous bot operation with custom callback functions

License

This project is licensed under the MIT License.

Links

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

simple_telegram_api-1.0.1.tar.gz (5.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

simple_telegram_api-1.0.1-py3-none-any.whl (6.4 kB view details)

Uploaded Python 3

File details

Details for the file simple_telegram_api-1.0.1.tar.gz.

File metadata

  • Download URL: simple_telegram_api-1.0.1.tar.gz
  • Upload date:
  • Size: 5.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.8.22

File hashes

Hashes for simple_telegram_api-1.0.1.tar.gz
Algorithm Hash digest
SHA256 f503c6683ab33ebeb9dbf08039a070c2c98ed14acc241080d8400b224f8d29ca
MD5 abf8128fd9d965caddf6af358daa0229
BLAKE2b-256 7e1a0cda9ecd44fef9b1bda28b8054de1414deec6fdb0fcfda46e6244165321c

See more details on using hashes here.

File details

Details for the file simple_telegram_api-1.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for simple_telegram_api-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 60c653605da3c2f781889b72804d95850c849039ab5ec885e12416359913518c
MD5 e84e9c6587c71cab45bce83328ad16bb
BLAKE2b-256 f20e22b2f4f22f10642afb64db87a613ba4ee12573f48b32704a8c1244dc1d11

See more details on using hashes here.

Supported by

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