0%

[Python] 撰寫第一個 Line Notify 模組

由於最近想開發一個自由化調用的 Line Notify,於是決定了這次程式內容,如果未來想要開發更多功能時,這將會增加我們的擴充性。


前提 First

  • LINE Notify — 需申請幾組 Token
  • Python — 基礎 Python 能力
  • Google — 需擁有自行查資料的能力

結果

Image for post

Image for post


附上程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import os, lineTool, requests, configparser
# 需先於Line Notify申請你的Token 你可以定義它的名稱
token = {
'test': 'test_token',
'stock': 'stock_token',
}

# 建立模組化 Function
def lineNotify(bot_name, msg):
url = "https://notify-api.line.me/api/notify"
headers = {
"Authorization": "Bearer " + token[bot_name],
"Content-Type" : "application/x-www-form-urlencoded"
}
payload = {'message': msg}
r = requests.post(url, headers = headers, params = payload)
if r.status_code == 200:
return 'ok.'
else:
return 'failed.'

# 調用方法
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('bot_name', help="使用bot的名稱") # 建立 args 以便後續呼叫
parser.add_argument('msg', help="要傳送的訊息") # 建立 args 以便後續呼叫
args = parser.parse_args() # 將元素加入到 args
# 呼叫lineNotify
print(lineNotify(args.bot_name,args.msg))