aiotg¶
Asynchronous Python API for building Telegram bots, featuring:
- Easy and declarative API
- Hassle-free setup - no need for SSL certificates or static IP
- Built-in support for analytics via botan.io
- Automatic handling of Telegram API throttling or timeouts
Install it with pip:
pip install aiotg
Then you can create a new bot in few lines:
from aiotg import Bot, Chat
bot = Bot(api_token="...")
@bot.command(r"/echo (.+)")
def echo(chat: Chat, match):
return chat.reply(match.group(1))
bot.run()
Now run it with a proper API_TOKEN and it should reply to /echo commands.
Note
Type annotations are not required but will help your editor/IDE to provide code completion.
The example above looks like a normal synchronous code but it actually returns a coroutine. If you want to make an external request (and that’s what bots usually do) just use aiohttp and async/await syntax:
import aiohttp
from aiotg import Bot, Chat
bot = Bot(api_token="...")
@bot.command("bitcoin")
async def bitcoin(chat: Chat, match):
url = "https://api.bitcoinaverage.com/ticker/global/USD/"
async with aiohttp.get(url) as s:
info = await s.json()
await chat.send_text(info["24h_avg"])
bot.run()
But what if you just want to write a quick integration and don’t need to provide a conversational interface? We’ve got you covered! You can send messages (or any other media) by constructing a Chat object with user_id or channel name. We even saved you some extra keystrokes by providing handy Channel constructors:
...
channel = bot.channel("@yourchannel")
private = bot.private("1111111")
async def greeter():
await channel.send_text("Hello from channel!")
await private.send_text("Why not greet personally?")
...
Examples¶
For a real world example, take a look at WhatisBot or Music Catalog Bot.
For more information on how to use the project, see the project’s documentation. Have a question? Ask it on project’s Telegram chat.
Reference¶
Bot Interface¶
-
class
aiotg.bot.
Bot
(api_token, api_timeout=60, botan_token=None, name=None, json_serialize=<function dumps>, json_deserialize=<function loads>, default_in_groups=False)[source]¶ Bases:
object
Telegram bot framework designed for asyncio
Parameters: - api_token (str) – Telegram bot token, ask @BotFather for this
- api_timeout (int) – Timeout for long polling
- botan_token (str) – Token for http://botan.io
- name (str) – Bot name
- json_serialize (callable) – Json serializer function. (json.dumps() by default)
- json_deserialize (callable) – Json deserializer function. (json.loads() by default)
- default_in_groups (bool) – Enables default callback in groups
-
api_call
(method, **params)[source]¶ Call Telegram API.
See https://core.telegram.org/bots/api for reference.
Parameters: - method (str) – Telegram API method
- params – Arguments for the method call
-
callback
(callback)[source]¶ Set callback for callback queries
Example: >>> @bot.callback >>> def echo(chat, cq): >>> return cq.answer()
>>> @bot.callback(r"buttonclick-(.+)") >>> def echo(chat, cq, match): >>> return chat.reply(match.group(1))
-
channel
(channel_name)[source]¶ Construct a Chat object used to post to channel
Parameters: channel_name (str) – Channel name
-
command
(regexp)[source]¶ Register a new command
Parameters: regexp (str) – Regular expression matching the command to register Example: >>> @bot.command(r"/echo (.+)") >>> def echo(chat, match): >>> return chat.reply(match.group(1))
-
create_webhook_app
(path, loop=None)[source]¶ Shorthand for creating aiohttp.web.Application with registered webhook hanlde
-
default
(callback)[source]¶ Set callback for default command that is called on unrecognized commands for 1-to-1 chats If default_in_groups option is True, callback is called in groups too
Example: >>> @bot.default >>> def echo(chat, message): >>> return chat.reply(message["text"])
-
edit_message_reply_markup
(chat_id, message_id, reply_markup, **options)[source]¶ Edit a reply markup of message in a chat
Parameters: - chat_id (int) – ID of the chat the message to edit is in
- message_id (int) – ID of the message to edit
- reply_markup (str) – New inline keyboard markup for the message
- options – Additional API options
-
edit_message_text
(chat_id, message_id, text, **options)[source]¶ Edit a text message in a chat
Parameters: - chat_id (int) – ID of the chat the message to edit is in
- message_id (int) – ID of the message to edit
- text (str) – Text to edit the message to
- options – Additional API options
-
get_file
(file_id)[source]¶ Get basic information about a file and prepare it for downloading.
Parameters: file_id (int) – File identifier to get information about Returns: File object (see https://core.telegram.org/bots/api#file)
-
get_me
()[source]¶ Returns basic information about the bot (see https://core.telegram.org/bots/api#getme)
-
get_user_profile_photos
(user_id, **options)[source]¶ Get a list of profile pictures for a user
Parameters: - user_id (int) – Unique identifier of the target user
- options – Additional getUserProfilePhotos options (see https://core.telegram.org/bots/api#getuserprofilephotos)
-
group
(group_id)[source]¶ Construct a Chat object used to post group messages
Parameters: group_id (str) – Group chat id
-
handle
(msg_type)[source]¶ Set handler for specific message type
Example: >>> @bot.handle("audio") >>> def handle(chat, audio): >>> pass
-
inline
(callback)[source]¶ Set callback for inline queries
Example: >>> @bot.inline >>> def echo(iq): >>> return iq.answer([ >>> {"type": "text", "title": "test", "id": "0"} >>> ])
>>> @bot.inline(r"myinline-(.+)") >>> def echo(chat, iq, match): >>> return iq.answer([ >>> {"type": "text", "title": "test", "id": "0"} >>> ])
-
leave_chat
(chat_id)[source]¶ Use this method for your bot to leave a group, supergroup or channel. Returns True on success.
Parameters: chat_id (int) – Unique identifier for the target chat or username of the target supergroup or channel (in the format @channelusername)
-
loop
()[source]¶ Return bot’s main loop as coroutine. Use with asyncio.
Example: >>> loop = asyncio.get_event_loop() >>> loop.run_until_complete(bot.loop())
or
>>> loop = asyncio.get_event_loop() >>> loop.create_task(bot.loop())
-
private
(user_id)[source]¶ Construct a Chat object used to post direct messages
Parameters: user_id (str) – User id
-
run
(debug=False, reload=None)[source]¶ Convenience method for running bots in getUpdates mode
Parameters: - debug (bool) – Enable debug logging and automatic reloading
- reload (bool) – Automatically reload bot on code change
Example: >>> if __name__ == '__main__': >>> bot.run()
-
run_webhook
(webhook_url, **options)[source]¶ Convenience method for running bots in webhook mode
Example: >>> if __name__ == '__main__': >>> bot.run_webhook(webhook_url="https://yourserver.com/webhooktoken")
Additional documentation on https://core.telegram.org/bots/api#setwebhook
-
send_message
(chat_id, text, **options)[source]¶ Send a text message to chat
Parameters: - chat_id (int) – ID of the chat to send the message to
- text (str) – Text to send
- options – Additional sendMessage options (see https://core.telegram.org/bots/api#sendmessage)
-
session
¶
-
track
(message, name='Message')[source]¶ Track message using http://botan.io Set botan_token to make it work
-
class
aiotg.bot.
InlineQuery
(bot, src)[source]¶ Bases:
object
Incoming inline query See https://core.telegram.org/bots/api#inline-mode for details
-
class
aiotg.bot.
TgBot
(*args, **kwargs)[source]¶ Bases:
aiotg.bot.Bot
-
class
aiotg.bot.
TgInlineQuery
(*args, **kwargs)[source]¶ Bases:
aiotg.bot.InlineQuery
Chat Interface¶
-
class
aiotg.chat.
Chat
(bot, chat_id, chat_type='private', src_message=None)[source]¶ Bases:
object
Wrapper for telegram chats, passed to most callbacks
-
edit_reply_markup
(message_id, markup)[source]¶ Edit only reply markup of the message in this chat.
Parameters: - message_id (int) – ID of the message to edit
- markup (dict) – Markup options
-
edit_text
(message_id, text, markup=None, parse_mode=None)[source]¶ Edit the message in this chat.
Parameters: - message_id (int) – ID of the message to edit
- text (str) – Text to edit the message to
- markup (dict) – Markup options
- parse_mode (str) – Text parsing mode (
"Markdown"
,"HTML"
orNone
)
-
forward_message
(from_chat_id, message_id)[source]¶ Forward a message from another chat to this chat.
Parameters: - from_chat_id (int) – ID of the chat to forward the message from
- message_id (int) – ID of the message to forward
-
static
from_message
(bot, message)[source]¶ Create a
Chat
object from a message.Parameters: - bot (Bot) –
Bot
object the message and chat belong to - message (dict) – Message to base the object on
Returns: A chat object based on the message
- bot (Bot) –
-
get_chat_administrators
()[source]¶ Get a list of administrators in a chat. Chat must not be private.
-
get_chat_member
(user_id)[source]¶ Get information about a member of a chat.
Parameters: user_id (int) – Unique identifier of the target user
-
is_group
()[source]¶ Check if this chat is a group.
Returns: True
if this chat is a group,False
otherwise
-
kick_chat_member
(user_id)[source]¶ Use this method to kick a user from a group or a supergroup. The bot must be an administrator in the group for this to work.
Parameters: user_id (int) – Unique identifier of the target user
-
reply
(text, markup=None, parse_mode=None)[source]¶ Reply to the message this Chat object is based on.
Parameters: - text (str) – Text of the message to send
- markup (dict) – Markup options
- parse_mode (str) – Text parsing mode (
"Markdown"
,"HTML"
orNone
)
-
send_audio
(audio, **options)[source]¶ Send an mp3 audio file to the chat.
Parameters: - audio – Object containing the audio data
- options – Additional sendAudio options (see https://core.telegram.org/bots/api#sendaudio)
Example: >>> with open("foo.mp3", "rb") as f: >>> await chat.send_audio(f, performer="Foo", title="Eversong")
-
send_chat_action
(action)[source]¶ Send a chat action, to tell the user that something is happening on the bot’s side.
Available actions:
- typing for text messages
- upload_photo for photos
- record_video and upload_video for videos
- record_audio and upload_audio for audio files
- upload_document for general files
- find_location for location data
Parameters: action (str) – Type of action to broadcast
-
send_contact
(phone_number, first_name, **options)[source]¶ Send phone contacts.
Parameters: - phone_number (str) – Contact’s phone number
- first_name (str) – Contact’s first name
- options – Additional sendContact options (see https://core.telegram.org/bots/api#sendcontact)
-
send_document
(document, caption='', **options)[source]¶ Send a general file.
Parameters: - document – Object containing the document data
- caption (str) – Document caption (optional)
- options – Additional sendDocument options (see https://core.telegram.org/bots/api#senddocument)
Example: >>> with open("file.doc", "rb") as f: >>> await chat.send_document(f)
-
send_location
(latitude, longitude, **options)[source]¶ Send a point on the map.
Parameters: - latitude (float) – Latitude of the location
- longitude (float) – Longitude of the location
- options – Additional sendLocation options (see https://core.telegram.org/bots/api#sendlocation)
-
send_photo
(photo, caption='', **options)[source]¶ Send a photo to the chat.
Parameters: - photo – Object containing the photo data
- caption (str) – Photo caption (optional)
- options – Additional sendPhoto options (see https://core.telegram.org/bots/api#sendphoto)
Example: >>> with open("foo.png", "rb") as f: >>> await chat.send_photo(f, caption="Would you look at this!")
-
send_sticker
(sticker, **options)[source]¶ Send a sticker to the chat.
Parameters: - sticker – Sticker to send (file or string)
- options – Additional sendSticker options (see https://core.telegram.org/bots/api#sendsticker)
-
send_text
(text, **options)[source]¶ Send a text message to the chat.
Parameters: - text (str) – Text of the message to send
- options – Additional sendMessage options (see https://core.telegram.org/bots/api#sendmessage
-
send_venue
(latitude, longitude, title, address, **options)[source]¶ Send information about a venue.
Parameters: - latitude (float) – Latitude of the location
- longitude (float) – Longitude of the location
- title (str) – Name of the venue
- address (str) – Address of the venue
- options – Additional sendVenue options (see https://core.telegram.org/bots/api#sendvenue)
-
send_video
(video, caption='', **options)[source]¶ Send an mp4 video file to the chat.
Parameters: - video – Object containing the video data
- caption (str) – Video caption (optional)
- options – Additional sendVideo options (see https://core.telegram.org/bots/api#sendvideo)
Example: >>> with open("foo.mp4", "rb") as f: >>> await chat.send_video(f)
-
send_voice
(voice, **options)[source]¶ Send an OPUS-encoded .ogg audio file.
Parameters: - voice – Object containing the audio data
- options – Additional sendVoice options (see https://core.telegram.org/bots/api#sendvoice)
Example: >>> with open("voice.ogg", "rb") as f: >>> await chat.send_voice(f)
-
-
class
aiotg.chat.
Sender
[source]¶ Bases:
dict
A small wrapper for sender info, mostly used for logging
-
class
aiotg.chat.
TgChat
(*args, **kwargs)[source]¶ Bases:
aiotg.chat.Chat
-
class
aiotg.chat.
TgSender
(*args, **kwargs)[source]¶ Bases:
aiotg.chat.Sender