這個問題相信是很多人都想知道的吧, 網上關於telegram bot 相關的資訊都是以C做成的, 目前筆者也鮮少看到用MicroPython 玩chatbot這樣的情報出現. 因此筆者做了諸多實驗就是想用MicroPython玩耍 ....
另外, 對C有興趣的朋友可以參考這篇的實作:ESP8266-TelegramBot for C
[實驗開始]
import urequests
url = "https://api.telegram.org/bot{0}/sendMessage?chat_id={1}&text={2}".format(token, chat_id, sendout)
ric = urequests.get(url)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "urequests.py", line 112, in get
File "urequests.py", line 100, in request
File "urequests.py", line 97, in request
NotImplementedError: Redirects not yet supported
[秘訣] MicroPython 沒有實做重導向這部份, 所以當遇到重導向的部份就會噴302 Moved Temporarilly error code
4. 筆者使用Browser 中的Development tools 去追查最後轉址到哪, 發現是轉址到下面的位置
api.telegram.org 轉址到 149.154.167.220
url = "https://149.154.167.229/bot{0}/sendMessage?chat_id={1}&text={2}".format(token, chat_id, sendout)
ric = urequests.get(url)
TLS buffer overflow, record size: 5165 (+5)
ssl_handshake_status: -257
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "urequests.py", line 112, in get
File "urequests.py", line 100, in request
File "urequests.py", line 60, in request
OSError: [Errno 5] EIO
[秘訣]
(1) 瀏覽器遇到301/ 302 的狀態時會自動處理轉址這過程, 但MicroPython 沒有實做這部份就會噴bug
(2) 這次看起來是SSL的問題
6. 接下來改用uscoket 實作
import socket
>>> s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
>>> s.connect(('149.154.167.220',443))
>>> sslSocket = ssl.wrap_socket(s)
ssl_handshake_status: -256
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 5] EIO
>>>
筆者發現可以跟server 取得連線, 但還是會出現SSL錯誤的部份, 這部份在網路上有很多種解法. 就留待有興趣的朋友去研究了 .... 筆者目前也還在努力嘗試找出最佳解