- Notifications
You must be signed in to change notification settings - Fork5.7k
Introduction to the API
The Bot API is exposed via thetelegram.Bot
class.The methods are thesnake_case
equivalents of the methods described in the officialTelegram Bot API.The exactcamelCase
method names as in the Telegram docs are also available for your convenience.For example,telegram.Bot.send_message
is the same astelegram.Bot.sendMessage
.All the classes of the Bot API can also be found in thetelegram
module, e.g. theMessage
class is available astelegram.Message
.
To generate an Access Token, you have to talk toBotFather and follow a few simple steps (describedhere).
For full details see the official Telegram documentation atBots: An introduction for developers. You might also findthe 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).
To get a feeling for the API and how to use it withpython-telegram-bot
, please create a new Python file.
We first want to create an instance of thetelegram.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
importasyncioimporttelegramasyncdefmain():bot=telegram.Bot("TOKEN")asyncwithbot:print(awaitbot.get_me())if__name__=='__main__':asyncio.run(main())
Here we simply call the API methodgetMe.Theasync 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.pyUser(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 uset.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 themain
function in our file with
asyncdefmain():bot=telegram.Bot("TOKEN")asyncwithbot:updates= (awaitbot.get_updates())[0]print(updates)
The output should now look something like this (we abbreviated the output a bit):
$ python main.pyUpdate(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, here1234567890
.Note that you can access it also asupdates[0].message.from_user.id
, becauseupdates[0]
is an instance of theUpdate
class.Now that we have the chat ID, we can send a message by again adjusting themain()
:
asyncdefmain():bot=telegram.Bot("TOKEN")asyncwithbot:awaitbot.send_message(text='Hi John!',chat_id=1234567890)
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 calledtelegram.ext
that takes a lot of work off your shoulders. You can find an introduction at theTutorial: Your first bot.
Wiki ofpython-telegram-bot
© Copyright 2015-2025 – Licensed byCreative Commons
- Architecture Overview
- Builder Pattern for
Application
- Types of Handlers
- Working with Files and Media
- Exceptions, Warnings and Logging
- Concurrency in PTB
- Advanced Filters
- Storing data
- Making your bot persistent
- Adding Defaults
- Job Queue
- Arbitrary
callback_data
- Avoiding flood limits
- Webhooks
- Bot API Forward Compatiblity
- Frequently requested design patterns
- Code snippets
- Performance Optimizations
- Telegram Passport
- Bots built with PTB
- Automated Bot Tests