- Notifications
You must be signed in to change notification settings - Fork5.9k
Adding defaults to your bot
Hinrich Mahler edited this pageJan 1, 2025 ·11 revisions
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.
parse_modedisable_notificationdisable_web_page_previewallow_sending_without_replydo_quotetzinfoblockprotect_contentlink_preview_options
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
- 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