Skip to main content

Autogram

0x00 An efficient asyncronous Telegram bot API wrapper!

Autogram is an asyncrounous, extensible telegram BOT API wrapper written in python using asyncio.

import os
from autogram.updates import Message
from autogram import Autogram, onLoadConfig


@Message.onCommand('/start')
def commandHandler(msg: Message):
    msg.deleteMessage()
    msg.sendText("Hello! How may I help you?")

@Message.onCommand('/logout')
def stopHandler(msg: Message):
    msg.deleteMessage()
    if msg.autogram.admin == msg.sender['id']:
        msg.autogram.admin = None
    else:
        msg.autogram.deputy_admin = None
    msg.sendText('Logged out.')

@Message.onCommand('/shutdown')
def shutdownCommand(msg: Message):
    msg.autogram.terminate.set()
    msg.deleteMessage()

@Message.onMessageType('text')
def messageHandler(msg: Message):
    msg.replyText(msg.text)

@Message.onMessageType('voice')
@Message.onMessageType('audio')
@Message.onMessageType('photo')
@Message.onMessageType('video')
@Message.onMessageType('document')
@Message.onMessageType('video_note')
def fileHandler(msg: Message):
    temp_dir = 'Downloads'
    if not os.path.exists(temp_dir):
        os.mkdir(temp_dir)
    file_path = f"{temp_dir}/{msg.file['name']}"
    with open(file_path, 'wb') as file:
        file.write(msg.file['bytes'])
    msg.deleteMessage()


@onLoadConfig('autogram.json')
def startBot(config: dict):
    bot = Autogram(config=config)
    bot_thread = bot.send_online()
    bot_thread.join()

The above implementation assumes you want to control your bot through telegram messages only, as calling join on bot.send_online(...) which returns a thread object will block. If you intend to use the bot alongside other code, call bot.send_online(...) and leave it at that. The bot thread will terminate when your program finishes execution.

  1. You can use the bot handle returned by bot = Autogram(token) to terminate the telegram bot. Just call bot.terminate.set() to set the terminate event in the bot thread.
  2. The bot has implicit chat actions. i.e typing, sending photo, etc which are invoked when you call reply functions on update objects.

0x02 Why AutoGram?

I needed a bot framework that was easy to control remotely.

AutoGram has a built-in webhook endpoint written using Bottle Framework. Therefore, if you have a public IP, or can get an external service to comminicate with localhost through a service like ngrok (I use it too!), then add that IP or publicly visible address to your environment variables. If the public addr is not found, the program will use polling to fetch updates from telegram servers. You add functionality to Autogram bot py implementing and adding callback functions. The bot will therefore work with available callbacks, and will continue to work even if none is specified! This allows the bot to work with available features, despite of missing handlers for specific types of messages.

0x03 Tell me about the callback functions :)

The basic idea is that you can have a running bot without handlers. To be able to handle a normal user message, you'll need to import the Message module, and add a handler to it. When a normal user message is received, the Message object will parse the message, parse some of the content and set attributes on itself, then pass itself down to your handler. While creating the handler, you can tell the Message object whether you want to download message attachments too. If you don't, they will be downloaded when you attempt to access them. Below is a list of Update Objects you can (or will be able to) add callbacks to.

from .poll import Poll, pollAnswer
from .message import Message, editedMessage
from .inline import inlineQuery, chosenInlineResult
from .channel import channelPost, editedChannelPost
from .chat import chatMember, myChatMember, chatJoinRequest
from .query import callbackQuery, shippingQuery, precheckoutQuery

The above are largely unimplemented, as my current project only requires the Message functionality. I intend to implement the rest either for fun, or as requirements for my future projects. Should you need an implementation, let me know so I can speed it up for you. I will include a list of completed features at the end.

0x04 Currently supported update types

  • Message

0x05 Complete features

  • Bot knows it's admin
  • Deputy admin can enroll using a secret phrase
  • Default handlers are set to forward to admin.
  • Media messages are forwared to admin, but ignored if admin sends them.

0x06 Upcoming features

  • Add state using SQLAlchemy
  • Plans to cover the entire telegram API -> in progress
  • Track deleted messages to avoid multiple deletes. causes an error
  • Format and forward notifications/alerts to admin. i.e: added to group, blocked, etc -> Not started

footnotes

  • short-polling is available for testing.
  • If you're using with ngrok, use ngrok http 80
  • Don't run multiple bots with the same TELEGRAM TOKEN as this will cause update problems
  • Update types not listed above may not work as intented. Hit me up to speed up a module for you.
  • Try and have fun ;)

Metadata

Release files for autogram 1.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for autogram 1.1.1
File Size Uploaded
autogram-1.1.1.tar.gz 14.8 kB Details

Built distribution (wheel)

Table of built distributions (wheels) for autogram 1.1.1
File Interpreter ABI Platform
autogram-1.1.1-py3-none-any.whl Python 3 none any Details

Total release size: 30.3 kB

Release files / autogram-1.1.1.tar.gz

Download URL autogram-1.1.1.tar.gz
Size 14.8 kB
Tags Source
SHA-256 checksum
How to use checksums
e386cc538b9a6148b5eed046939ba7173cd1acc6d6a83355ad27e07ea40c644b
BLAKE2b-256 checksum
How to use checksums
7c97e5eec180339b5f2679dfd68ce84be396c7063ed2d736e9ace5e64ef4f68a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.10.6

Release files / autogram-1.1.1-py3-none-any.whl

Download URL autogram-1.1.1-py3-none-any.whl
Size 15.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
13a6f95c758542147e171920e49905410bed434552b01ea4e894af868385acb2
BLAKE2b-256 checksum
How to use checksums
3e6d992ab2d9a73fd2975777df8c80cddf8a47493ecd4d47afb9e5a9d597f3d8
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/4.0.2 CPython/3.10.6

Release history Release notifications | RSS feed

4.0.0

2 release files

3.7.0

2 release files

3.6.1

2 release files

3.6.0

2 release files

3.5.0

2 release files

3.4.4

2 release files

3.4.3

2 release files

3.4.2

2 release files

3.4.1

2 release files

3.4.0

2 release files

3.3.2

2 release files

3.0.0

2 release files

2.0.3

2 release files

This release

1.1.1 This release

2 release files

1.0.2

2 release files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page