# Types of Handlers(翻譯) ###### tags: `telegram` `bot` >[name=shaoe.chen] :::danger [官方文件](https://github.com/python-telegram-bot/python-telegram-bot/wiki/Types-Of-Handlers) ::: [TOC] `Handler`是由基類[telegram.ext.Handler](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.handler.html#telegram.ext.Handler)所衍實例,負責不同類型更新(文本,音頻,inlinequery,按鈕按下等)的路由到程式碼中相對應的callback function。 舉例來說,如果你希望你的機器人回覆命令`/start`,你可以使用[CommandHandler](https://python-telegram-bot.readthedocs.io/en/latest/telegram.ext.commandhandler.html)來映射用戶輸入到callback function`start_callback`: ```python def start_callback(update, context): update.message.reply_text("Welcome to my awesome bot!") ... dispatcher.add_handler(CommandHandler("start", start_callback)) ``` ## CommandHandlers with arguments 也可以為你機器人所提供的命令使用參數,讓我們延申`start_callback`,加入某些參數,以便用戶可以在相同步驟中提供額外的信息: ```python def start_callback(update, context): user_says = " ".join(context.args) update.message.reply_text("You said: " + user_says) ... dispatcher.add_handler(CommandHandler("start", start_callback)) ``` 發送"/start Hello World!"給你的機器人會將/start以後的所有東西以空白字符分割為單詞列表(list of works),並傳給`context`的參數`args`:`["Hello", "World!"]`。我們利用呼叫`" ".join(context.args)`來連結這些區塊,然後回應結果字串給用戶。 ### Deep-Linking start parameters 當用戶點擊start URL的時候,它的參數傳遞與上面所說的完全一樣,就像這樣: ``` https://t.me/roolsbot?start=Hello_World! ``` 點擊這個連結會開啟你的Telegram客戶端,並且顯示一個很大的START按鈕。當它被點擊時,URL的參數"Hello_World!"會被傳遞到你的上下文物件的`args` 要注意的是,因為telegram並不支援在deep linking參數中使用空格,你必須手動分割參數`Hello_World`為`["Hello", "World!"]`(例如,使用`context.args[0].split('_')`) 你還需要注意Telegram本身所能接受的最大長度。如[文件](https://core.telegram.org/bots#deep-linking)所說,參數start的最大長度為64。 還有,因為這是一個URL參數,所以必須注意如何正確傳遞數值,以避免傳遞URL的保留字符。考慮使用`base64.urlsafe_b64encode`。 ## Pattern matching: The RegexHandler 不建議使用,因此不翻譯了。
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up