GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — Extensions Your first Bot Extensions Your first Bot
Hinrich Mahler edited this page
The It consists of several classes, but the most important one is The Every handler is an instance of any subclass of the Tip To begin, you'll need an Access Token. If you have already read and followed Introduction 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 (described here). You should really read the introduction first, though. 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: import logging from telegram import Update from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await context.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. import logging logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO ) This part is for setting up Note: Read the article on Exceptions, Warnings and Logging if you want to learn more. application = ApplicationBuilder().token('TOKEN').build() Here the first real magic happens: You have to create an Related docs: 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: async def start(update: Update, context: ContextTypes.DEFAULT_TYPE): await context.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 As you can see, this function will receive two parameters: an Related docs: To tell your bot to listen to from telegram.ext import CommandHandler start_handler = CommandHandler('start', start) application.add_handler(start_handler) Related docs: And that's all you need. Finally, the line Related docs: Give it a try! Start a chat with your bot and issue the But our Bot can now only answer to the from telegram import Update from telegram.ext import filters, MessageHandler, ApplicationBuilder, CommandHandler, ContextTypes ... async def echo(update: Update, context: ContextTypes.DEFAULT_TYPE): await context.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: From now on, your bot should echo all non-command messages it receives. Note The Let's add some actual functionality to your bot. We want to implement a async def caps(update: Update, context: ContextTypes.DEFAULT_TYPE): text_caps = ' '.join(context.args).upper() await context.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 of Another cool feature of the Telegram Bot API is the inline mode. If you want to implement inline functionality for your bot, please first talk to @BotFather and enable inline mode using 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: from telegram import InlineQueryResultArticle, InputTextMessageContent from telegram.ext import InlineQueryHandler from uuid import uuid4 ... async def inline_caps(update: Update, context: ContextTypes.DEFAULT_TYPE): query = update.inline_query.query if not query: return results = [] results.append( InlineQueryResultArticle( id=str(uuid4()), title='Caps', input_message_content=InputTextMessageContent(query.upper()) ) ) await context.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 a ... async def unknown(update: Update, context: ContextTypes.DEFAULT_TYPE): await context.bot.send_message(chat_id=update.effective_chat.id, text="Sorry, I didn't understand that command.") if __name__ == '__main__': ... # Other handlers unknown_handler = MessageHandler(filters.COMMAND, unknown) application.add_handler(unknown_handler) application.run_polling() Important This handler must be added last.
If you added it before the other handlers, it would be triggered before the If you're done playing around, stop the bot by pressing Have a look at the ready-to-run examples. Learn about the library exceptions and best practices in Exceptions, Warnings and Logging. You want more features? Check out Extensions - JobQueue! Wiki of
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. |