GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Introduction to the API

Introduction to the API

Jump to bottom Edit New page
Hinrich Mahler edited this page Mar 24, 2024 · 47 revisions

Pure Telegram Bot API

The Bot API is exposed via the telegram.Bot class. The methods are the snake_case equivalents of the methods described in the official Telegram Bot API. The exact camelCase method names as in the Telegram docs are also available for your convenience. For example, telegram.Bot.send_message is the same as telegram.Bot.sendMessage. All the classes of the Bot API can also be found in the telegram module, e.g. the Message class is available as telegram.Message.

To generate an Access Token, you have to talk to BotFather and follow a few simple steps (described here).

For full details see the official Telegram documentation at Bots: An introduction for developers. You might also find the official tutorial useful for getting to know the principles of working with Telegram API (although Java is used in examples there, you will find a link to equivalent Python code).

Hello, Telegram!

To get a feeling for the API and how to use it with python-telegram-bot, please create a new Python file.

We first want to create an instance of the telegram.Bot and check that the credentials are correct. Please paste the following code into your file. 'TOKEN' should be replaced by the API token you received from @BotFather

import asyncio
import telegram


async def main():
    bot = telegram.Bot("TOKEN")
    async with bot:
        print(await bot.get_me())


if __name__ == '__main__':
    asyncio.run(main())

Here we simply call the API method getMe. The async with bot: ensures that PTB can properly acquire and release resources. If you run the file you should get an output along the lines

$ python main.py
User(first_name="Toledo's Palace Bot", is_bot=True, username="ToledosPalaceBot", ...)

So far so good. Now we can try and actually do something - let's send a message.

Important

Bots can't initiate conversations with users. A user must either add them to a group or send them a message first. People can use t.me/<bot_username> links or username search to find your bot.

Because of that restriction, we'll have to first send a message to the bot. After we've done that, we can fetch the update by refactoring the main function in our file with

async def main():
    bot = telegram.Bot("TOKEN")
    async with bot:
        updates = (await bot.get_updates())[0]
        print(updates)

The output should now look something like this (we abbreviated the output a bit):

$ python main.py
Update(message=Message(chat=Chat(first_name='John', id=1234567890, last_name='Doe', ...), from_user=User(first_name='John', id=1234567890, last_name='Doe', ...), text='Hi!', ...), update_id=219017225)

We copy the chat id, here 1234567890. Note that you can access it also as updates[0].message.from_user.id, because updates[0] is an instance of the Update class. Now that we have the chat ID, we can send a message by again adjusting the main():

async def main():
    bot = telegram.Bot("TOKEN")
    async with bot:
        await bot.send_message(text='Hi John!', chat_id=1234567890)

Beyond the pure API

That's all very nice, but usually you want your bot to actually react to more complex user input. That is, you want to build a chat-bot. python-telegram-bot offers a powerful extension module called telegram.ext that takes a lot of work off your shoulders. You can find an introduction at the Tutorial: Your first bot.

Wiki of python-telegram-bot © Copyright 2015-2026 – Licensed by Creative Commons

Must read

  1. Introduction to the API
  2. Tutorial: Your first bot
  3. FAQ
  4. How to ask good questions
  5. How to write an MWE

Concepts & Important Elements

  1. Architecture Overview
  2. Builder Pattern for Application
  3. Types of Handlers
  4. Working with Files and Media
  5. Exceptions, Warnings and Logging
  6. Concurrency in PTB

Notable Features

  1. Advanced Filters
  2. Storing data
  3. Making your bot persistent
  4. Adding Defaults
  5. Job Queue
  6. Arbitrary callback_data
  7. Avoiding flood limits
  8. Webhooks
  9. Bot API Forward Compatiblity

Code Resources

  1. Frequently requested design patterns
  2. Code snippets
  3. Performance Optimizations
  4. Telegram Passport
  5. Bots built with PTB
  6. Automated Bot Tests

Examples explained

  1. InlineKeyboard Example

Networking

  1. Working Behind a Proxy
  2. Handling network errors

Other resources

  1. Where to host Telegram Bots
  2. How to host your bot
  3. Local API Server
  4. Type Checking with PTB
  5. Press
  6. Notes on GAE
  7. Related Projects
  8. Emoji

Transition Guides

  • Version 4
  • Version 5
  • Version 12
  • Version 13
  • Version 20

Administration

  • Test Bots
  • How To Release
  • Bots, Groups & Channels
  • PTB tests knowledge base
  • Bot API Backward Compatibility

Clone this wiki locally

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.