Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Extensions Your first Bot

Andrey Dodonov edited this pageJun 20, 2024 ·16 revisions

Introduction

Thetelegram.ext submodule is built on top of the pure API implementation. It provides an easy-to-use interface and takes some work off the programmer, so youdon't have to repeat yourself.

It consists of several classes, but the most important one istelegram.ext.Application.

TheApplication class is responsible for fetching updates from theupdate_queue, which is where theUpdater class continuously fetches new updates from Telegram and adds them to this queue.If you create anApplication object, usingApplicationBuilder, it will automatically create anUpdater for you and link them together with anasyncio.Queue.You can then register handlers of different types in theApplication, which will sort the updates fetched by theUpdater according to the handlers you registered, and deliver them to a callback function that you defined.

Every handler is an instance of any subclass of thetelegram.ext.BaseHandler class. The library provideshandler classes for almost all use cases, but if you need something very specific, you can also subclassHandler yourself.

Tip

To begin, you'll need an Access Token. If you have already read and followedIntroduction to the API, you can use the one you generated then. If not: To generate an Access Token, you have to talk to@BotFather and follow a few simple steps (describedhere). You should really read the introduction first, though.

Your first Bot, step-by-step

Please create a new file if you want to follow this tutorial.We will add new content to the file several times during the tutorial.For the sake of brevity, we will not repeat everything every time we add something.

So,let's get started!.Paste the following into your file:

importloggingfromtelegramimportUpdatefromtelegram.extimportApplicationBuilder,ContextTypes,CommandHandlerlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)asyncdefstart(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitcontext.bot.send_message(chat_id=update.effective_chat.id,text="I'm a bot, please talk to me!")if__name__=='__main__':application=ApplicationBuilder().token('TOKEN').build()start_handler=CommandHandler('start',start)application.add_handler(start_handler)application.run_polling()

Now this is a lot to digest, so let's go through it step by step.

importlogginglogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)

This part is for setting uplogging module, so you will know when (and why) things don't work as expected:

Note: Read the article onExceptions, Warnings and Logging if you want to learn more.

application=ApplicationBuilder().token('TOKEN').build()

Here the first real magic happens: You have to create anApplication object. Replace'TOKEN' with your Bot's API token.For more details on how this works, seethis page.

Related docs:telegram.ext.ApplicationBuilder,telegram.ext.Application

The application alone doesn't do anything.To add functionality, we do two things.First, we define a function that should process a specific type of update:

asyncdefstart(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitcontext.bot.send_message(chat_id=update.effective_chat.id,text="I'm a bot, please talk to me!"    )

The goal is to have this function called every time the Bot receives a Telegram message that contains the/start command.

As you can see, this function will receive two parameters: anupdate, which is an object that contains all the information and data that are coming from Telegram itself (like the message, the user who issued the command, etc) and acontext, which is another object that contains information and data about the status of the library itself (like theBot, theApplication, thejob_queue, etc).

Related docs:send_message,telegram.ext.CallbackContext (the type of the context argument),telegram.Update (the type of update argument)

To tell your bot to listen to/start commands, you can use aCommandHandler (one of the providedHandler subclasses) and register it in the application:

fromtelegram.extimportCommandHandlerstart_handler=CommandHandler('start',start)application.add_handler(start_handler)

Related docs:telegram.ext.CommandHandler,telegram.ext.Application.add_handler

And that's all you need.

Finally, the lineapplication.run_polling() runs the bot until you hitCTRL+C.

Related docs:telegram.ext.Application.run_polling

Give it a try! Start a chat with your bot and issue the/start command - if all went right, it will reply.

But our Bot can now only answer to the/start command.Let's add another handler that listens for regular messages. Use theMessageHandler, anotherHandler subclass, to echo all text messages.First, stop your bot by hittingCTRL+C.Now define a new function and add a corresponding handler:

fromtelegramimportUpdatefromtelegram.extimportfilters,MessageHandler,ApplicationBuilder,CommandHandler,ContextTypes...asyncdefecho(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitcontext.bot.send_message(chat_id=update.effective_chat.id,text=update.message.text)if__name__=='__main__':    ...echo_handler=MessageHandler(filters.TEXT& (~filters.COMMAND),echo)application.add_handler(start_handler)application.add_handler(echo_handler)application.run_polling()

Related docs:telegram.ext.MessageHandler,telegram.ext.filters

From now on, your bot should echo all non-command messages it receives.

Note

Thefilters module contains a number of so-called filters that filter incoming messages for text, images, status updates and more. Any message that returnsTrue for at least one of the filters passed toMessageHandler will be accepted. You can also write your own filters if you want. See more inAdvanced Filters.

Let's add some actual functionality to your bot. We want to implement a/caps command that will take some text as an argument (e.g./caps argument) and reply to it in CAPS. To make things easy, you will receive the arguments (as alist, split on spaces) that were passed to a command in the callback function:

asyncdefcaps(update:Update,context:ContextTypes.DEFAULT_TYPE):text_caps=' '.join(context.args).upper()awaitcontext.bot.send_message(chat_id=update.effective_chat.id,text=text_caps)if__name__=='__main__':    ...caps_handler=CommandHandler('caps',caps)application.add_handler(start_handler)application.add_handler(echo_handler)application.add_handler(caps_handler)application.run_polling()

Note

Take a look at the usage ofcontext.args. TheCallbackContext will have several attributes, depending on which handler is used.

Another cool feature of the Telegram Bot API is theinline mode. If you want to implement inline functionality for your bot, please first talk to@BotFather and enable inline mode using/setinline. It sometimes takes a while until your Bot registers as an inline bot on your client. You might be able to speed up the process by restarting your Telegram App (or sometimes, you just have to wait for a while).

As your bot is obviously a very loud one, let's continue with this theme for inline. You probably know the process by now, but there are a number of new types used here, so pay some attention:

fromtelegramimportInlineQueryResultArticle,InputTextMessageContentfromtelegram.extimportInlineQueryHandlerfromuuidimportuuid4...asyncdefinline_caps(update:Update,context:ContextTypes.DEFAULT_TYPE):query=update.inline_query.queryifnotquery:returnresults= []results.append(InlineQueryResultArticle(id=str(uuid4()),title='Caps',input_message_content=InputTextMessageContent(query.upper())        )    )awaitcontext.bot.answer_inline_query(update.inline_query.id,results)if__name__=='__main__':    ...inline_caps_handler=InlineQueryHandler(inline_caps)application.add_handler(inline_caps_handler)application.run_polling()

Related docs:telegram.ext.InlineQueryHandler,answer_inline_query

Not bad! Your Bot can now yell on command (ha!) and via inline mode.

Some confused users might try to send commands to the bot that it doesn't understand, so you can use aMessageHandler with aCOMMAND filter to reply to all commands that were not recognized by the previous handlers.

...asyncdefunknown(update:Update,context:ContextTypes.DEFAULT_TYPE):awaitcontext.bot.send_message(chat_id=update.effective_chat.id,text="Sorry, I didn't understand that command.")if__name__=='__main__':    ...# Other handlersunknown_handler=MessageHandler(filters.COMMAND,unknown)application.add_handler(unknown_handler)application.run_polling()

Important

This handlermust be added last.If you added it before the other handlers, it would be triggered before theCommandHandlers had a chance to look at the update.Once an update is handled, all further handlers are ignored.To circumvent this, you can pass the keyword argumentgroup (int) toadd_handler with a value other than 0.Seetelegram.ext.Application.add_handler andthis wiki page for details.

If you're done playing around, stop the bot by pressingCTRL+C.

What to read next?

Have a look at the ready-to-runexamples.

Learn about the library exceptions and best practices inExceptions, Warnings and Logging.

You wantmore features? Check outExtensions - JobQueue!

Wiki ofpython-telegram-bot © Copyright 2015-2025 – Licensed byCreative 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 forApplication
  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. Arbitrarycallback_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

Administration

Clone this wiki locally

[8]ページ先頭

©2009-2025 Movatter.jp