# Line 通知推播
``` python=
import network, ubinascii
import time
import urequests as requests
wlan = network.WLAN(network.STA_IF)
ssid = 'ITOutsourcing 1F'
passwd = '0928aiai'
def main():
active_wlan()
#show_wifi()
if connect_sta():
print(f'\nConnected ssid {ssid}. Network config: {wlan.ifconfig()}')
else:
print(f'\nFailed. Not Connected to: {ssid}')
# 修改為你要傳送的訊息內容
msg = 'Temperature: 30, Humidity: 40%25'
msg = msg.replace(" ", "%20")
# 修改為你的權杖內容
token = 'Rn4XMSoO1K3ktjmFcnRkUP54c3ZVMVfNQWZWPrUmNY8'
lineNotifyMessage(token, msg)
print("succ")
def active_wlan():
active = wlan.active()
if not active:
wlan.active(True)
def show_wifi():
scans = wlan.scan()
for scan in scans:
ssid = scan[0].decode()
bssid = ubinascii.hexlify(scan[1],'.').decode()
print(ssid, bssid)
def connect_sta():
if wlan.isconnected():
return True
print(f'Trying to connect to {ssid}')
wlan.connect(ssid, passwd)
for retry in range(100):
connected = wlan.isconnected()
if connected:
break
time.sleep(0.1)
print('.', end='')
return connected
def lineNotifyMessage(token, msg):
headers = {
"Authorization": "Bearer " + token,
"Content-Type" : "application/x-www-form-urlencoded"
}
link = "https://notify-api.line.me/api/notify?message=" + msg
r = requests.post(link, headers = headers)
return r.status_code
main()
```
#### *分段解析*:
貌似目前只能輸入英文,如輸入中文會無法傳遞
注意:在 URL 裡不能直接輸入空格` `,故用`%20`替代
```python=
# 修改為你要傳送的訊息內容
msg = 'Temperature: 30, Humidity: 40%25'
msg = msg.replace(" ", "%20")
```
`https://notify-api.line.me/api/notify`後方加入`?message=`用以傳遞訊息
``` python=
def lineNotifyMessage(token, msg):
headers = {
"Authorization": "Bearer " + token,
"Content-Type" : "application/x-www-form-urlencoded"
}
link = "https://notify-api.line.me/api/notify?message=" + msg
r = requests.post(link, headers = headers)
return r.status_code
```
11/22修正
```python=
def lineNotifyMessage(token, msg):
print(f"token {token} message {msg}")
headers = {"Content-Type": "application/x-www-form-urlencoded",
"Authorization": "Bearer " + token}
post_data = f"message={msg}"
response = requests.post('https://notify-api.line.me/api/notify', headers = headers, data = post_data)
print(response.text)
if response.status_code<300: #"response.status_code.ok" is also good
print("successed")
else:
print("[HTTPError]"+str(response.status_code))
return response.status_code
```