Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

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

Adding defaults to your bot

Hinrich Mahler edited this pageJan 1, 2025 ·11 revisions

Introduction

As of version 12.4, PTB supports passing default values for arguments such asparse_mode to reduce the need for repetition. For this purpose, theDefaults class was introduced. This makes it possible to set defaults for often used arguments. These are set at the creation of the bot and areimmutable.

What can be set to a default

  • parse_mode
  • disable_notification
  • disable_web_page_preview
  • allow_sending_without_reply
  • do_quote
  • tzinfo
  • block
  • protect_content
  • link_preview_options

Example

Here is a show case for settingparse_mode toParseMode.HTML andtzinfo topytz.timezone('Europe/Berlin') by default:

importloggingimportdatetimeasdtmimportzoneinfofromtelegram.constantsimportParseModefromtelegram.extimportMessageHandler,filters,Defaults,Applicationlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',level=logging.INFO)asyncdefjob(context):chat_id=context.job.chat_idtimezone=context.bot.defaults.tzinfolocal_now=dtm.datetime.now(timezone)utc_now=dtm.datetime.now(dtm.UTC)text=f'Running job at{local_now} in timezone{timezone}, which equals{utc_now} UTC.'awaitcontext.bot.send_message(chat_id=chat_id,text=text)asyncdefecho(update,context):text=update.message.text# Send with default parse modeawaitupdate.message.reply_text(f'<b>{text}</b>')# Override default parse mode locallyawaitupdate.message.reply_text(f'*{text}*',parse_mode=ParseMode.MARKDOWN)# Send with no parse modeawaitupdate.message.reply_text(f'*{text}*',parse_mode=None)# Schedule jobcontext.job_queue.run_once(job,dtm.datetime.now()+dtm.timedelta(seconds=1),chat_id=update.effective_chat.id    )defmain():"""Instantiate a Defaults object"""defaults=Defaults(parse_mode=ParseMode.HTML,tzinfo=zoneinfo.ZoneInfo('Europe/Berlin'))application= (Application.builder()        .token("TOKEN")        .defaults(defaults)        .build()    )# on non command text message - echo the message on Telegramapplication.add_handler(MessageHandler(filters.TEXT&~filters.COMMAND,echo))# Start the Botapplication.run_polling()if__name__=='__main__':main()

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