Skip to main content

An easily extensible telegram API wrapper

Project description

Autogram

Autogram is a telegram bot-API wrapper written in python3, with a keen focus on remaining stupidly simple.

QuickStart

pip install autogram

  • Copy either the Functional or OOP example below.
  • Run the bot the first time to generate project-name.json config template
  • Add your telegram bot token in the config, (from telegram:BotFather chat)
  • Ready to run.
  • Add your own logic and handler methods. core.telegram.org manual is your friend.

Why AutoGram?

The name implies automated-telegram. I needed a framework that is easy and intuitive to work with.

Usage1: Functional

from autogram import Autogram
from autogram.config import Start

#-- handle private dm
@Autogram.add('message')
def message(bot, update):
    print('message:', update)

#-- handle callback queries
@Autogram.add('callback_query')
def callback_query(bot, update):
    print('callback_query:', update)

#***************************** <start>
@Start(config_file='web-auto.json')
def main(config):
    bot = Autogram(config)
    bot.run() # every call fetches updates, and updates internal offset
#-- </start>

Usage2: OOP

import time
from loguru import logger
from autogram import Autogram, Start

# --
class ExampleBot(Autogram):
    def __init__(self, config):
        super().__init__(config)

    def run(self):
        """Custom implementation of bot.poll()"""
        super().run() # initializes bot info, abstractmethod
        for _ in range(10): # should be endless loop
            offset = self.data('offset')
            for rep in self.poll(offset=offset).json()['result']:
              self.data('offset', rep.pop('update_id') + 1)
              with self.register['lock']:
                if handler := self.register['handlers'].get(list(rep.keys())[-1]):
                  handler(self, self, rep)
            time.sleep(5)

    @Autogram.add('message')
    def message(self, bot: Autogram, update):
        logger.debug(update['message']['text'])
        chat_id = update['message']['chat']['id']
        keyb = [[{'text': 'The armpit', 'callback_data': 'tickled'}]]
        data = {
            'reply_markup': bot.getInlineKeyboardMarkup(keyb)
        }
        bot.sendMessage(chat_id, 'Tickle me!', **data)

    # --
    @Autogram.add('callback_query')
    def callback_query(self, bot: Autogram, update):
        callback_id = update['callback_query']['id']
        bot.answerCallbackQuery(callback_id, 'Ha-ha-ha')

#***************************** <start>
@Start()
def main(config):
    bot = ExampleBot(config)
    bot.run()
# ************ </start>

If you have a url-endpoint, call bot.setWebhook(url), then run some sort of webserver in bot.run.

Project TODOs

  • Add webhook example.
  • Extend coverage of the API.

footnotes

  • Invalid TELEGRAM_TOKEN return 404 through bot.getMe()
  • Thread safety is not guaranteed for calls from multiple threads to: bot.data, bot.settings. Prefferably, handle the bot in a single thread, as handlers use these methods to persist data.
  • Don't run multiple bots with the same TOKEN as this will cause update problems
  • Sending unescaped special characters when using MarkdownV2 will return HTTP400
  • Have fun with whatever you're building ;)

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

autogram-3.6.1.tar.gz (7.6 kB view details)

Uploaded Source

Built Distribution

autogram-3.6.1-py3-none-any.whl (8.1 kB view details)

Uploaded Python 3

File details

Details for the file autogram-3.6.1.tar.gz.

File metadata

  • Download URL: autogram-3.6.1.tar.gz
  • Upload date:
  • Size: 7.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.10.12

File hashes

Hashes for autogram-3.6.1.tar.gz
Algorithm Hash digest
SHA256 414eb3298d0379979bc7920b5fddb49761591babb51bf88465cba015557ab7ff
MD5 80a8bb77a0555fe87d8b21304522487f
BLAKE2b-256 69f4aab562c35d7d3c7d028746ee4c852cf5bed691bf9d1adfa1f8a96bd2e792

See more details on using hashes here.

File details

Details for the file autogram-3.6.1-py3-none-any.whl.

File metadata

  • Download URL: autogram-3.6.1-py3-none-any.whl
  • Upload date:
  • Size: 8.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.10.12

File hashes

Hashes for autogram-3.6.1-py3-none-any.whl
Algorithm Hash digest
SHA256 a3c8a6a18af25e5c47570af1b9f6e67e29e968b72e6895a086f3eb5ecd661c23
MD5 573ebabf07c90f52438080761c08a8d0
BLAKE2b-256 a6ad62f5258d1e5f4d88fd0f544e1f1e3de22a83a786a0494f877b4e5b0aef0a

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