自動傳出LINE訊息---利用python及txt檔

2024/02/28閱讀時間約 16 分鐘

1.    目的  

設計程式來讀取欲傳送訊息之參數txt檔案,再利用程式自動傳出訊息至LINE群組。使用者能簡易使用於任何場合。

 

2.    作業說明                                                  

       2.1   程式名稱:  LINE_send_notify.exe                                                     

       2.2 開發工具 : Python 3.8.3  [MSC v.1916 64 bit (AMD64)]。 

編輯工具 Spyder 4.1.4                                                              

       2.3   使用模組Module/套件 :                                                          

           import requests    #Line notify requests                                              

      from datetime import datetime                                                     

       2.4  讀取參數txt檔:

檔名 LINE_send_notify_par.txt, 內含 LINE Notify 所需之三要項,

即是 T , I , M  三個代碼,代碼功能如下: 

 T : token, 欲發送通知之LINE群組之字串權杖

 I : image ,欲附上圖片或 LINE icon貼圖之檔案儲存path     

 M: message,欲發送出去之訊息內容,可記入多行訊息

                                                    

         * 除了M 以外,相同的代碼若重複時,後面的代碼資料會取代面

    2.5  利用讀入之參數檔,讓本程式可多元彈性,靈活運用,

           參數檔需與程式檔案存置於同一資料夾內

                                                                  

3.  程式設計:

     3.1 程式編輯python coding

     3.2 程式測試:

         程式執行訊息傳送之結果,有可能出現訊息code如下            

         200: Success            

         400 Invalid image. Bad request 理由 : Token 有問題,或無            

         401: Invalid access token                 

         500: Failure due to server error              

 

              3.3 程式測試後,若成功無問題時,可將其編譯成執行檔

             python compile (compile to exe file)方法如下:

        ==>於Anaconda Powershell Prompt -->視窗下 以系統管理者帳號執行

                             

         ==>於Anaconda Powershell Prompt --> compile執行指令如下,

     執行後,若出現如下訊息,表示compile成功                               

       (base) PS C:\WINDOWS\system32> pyinstaller -F D:\.spyder-py3\linct\LINE_send_notify.py           

     …..                                                                                                          

       56678 INFO: Appending archive to EXE C:\WINDOWS\system32\dist\LINE_send_notify.exe        

56775 INFO: Building EXE from EXE-00.toc completed successfully.

(base) PS C:\WINDOWS\system32>   

                                                              

       4.  運用說明:                                                          

  4.1 欲自動推播訊息內容,記入LINE_send_notify_par.txt之文字內

         依使用者需求,自行輸入傳送訊息之內容。

參數txt檔,參考例如下:

M,

M,柴山生態班即將開班通知

M,一. 報名地點: 3月25日08:30 於海邊里活動中心

M,二. 課程費用: 600元, 介紹柴山生態共12週課程

M,

T,i----YOUR Token code---- 

 

     4.2 是否要傳出圖片,可有可無,使用者可自行決定

     4.3 將上述程式LINE_send_notify.exe,設計成一個bat檔案,讓它能依照排程,

於任意日期,任何時間,定期自動執行,執行後自動發出LINE訊息

     4.4  上述各檔案如exe ,txt, jpg 檔,需配置於同一資料夾內                 

   4.5執行後結果

        依照上述4.1參數txt檔實例,自動傳出訊息至LINE群組,如下圖示:

raw-image

                                                          

5.  將來構想:                                                          

           5.1 各業務定期報表,日報月報等,執行結果可自動發出訊息給擔當           ,非上班時間亦可及時自動傳出LINE訊息,讓各相關人員能夠掌握    業務運作狀況                            

          5.2  對每日或定期執行的程式或作業,一旦執行失敗或異常故障發生時,及時發出LINE之警告訊息,讓擔當可以盡快針對系統機器或程式資料,及時進行排除對應,避免事件擴大發生                                              

           5.3  定期作業之作業記錄檔,可供確認保存,做為稽核監查時,備查憑證資料,減少手工時間,提高作業效率                                              

           5.4 年度,月度,每季之定例計畫事項,或不定時計畫事件,可利用本程式,事先自動傳出LINE訊息,通知各相關人員,讓擔當可以事先及時準備對應,避免計畫事件被遺忘,或無法事先充分準備,而耽誤業務推進  

 

6.  程式內容:(python)

# -*- coding: utf-8 -*-
"""
Created on Wed Aug 6 18:35:38 2021

@author: KTMN0094 in 2021/8/8
"""
# import sys #Adding parameter
import requests #Line notify requests
from datetime import datetime

#d=str(datetime.now().strftime('%y/%m/%d %H:%M:%S'))
d=str(datetime.now().strftime('%Y/%m/%d %H:%M'))
#rem f=open (R'D:\Users\ktmn0094\.spyder-py3\linct\Subj_TO_Attach.txt','r',encoding='cp950')
f=open (R'LINE_send_notify_par.txt','r',encoding='cp950')
message = ' ' # 當無 M , 無message時 default = 空string
imagefile = ' ' # 當無 I , 無imagefile時 default = 空string
token = ' '

while True: # ----- 讀取input參數檔 'LINE_Notify_par.txt'
s=f.readline().replace('\n', '')
if not s: # 讀到最後EOF
break
else:
s=s.split(',')
s0=s[0]
s =s[1: ]
while (s0 == 'M'): # ----- 依據 參數 s0 值,做各項處理
s1_str =','.join(s) # list -> string then got contents string
message = message + s1_str +'\n'
break
while (s0 == 'I'): # ----- 依據 參數 s0 值,做各項處理
s1_str =','.join(s) # list -> string then got contents string
imagefile = s1_str
break
while (s0 == 'T'): # ----- 依據 參數 s0 值,做各項處理
s1_str =','.join(s) # list -> string then got contents string
token = s1_str
break
f.close()

if message == ' ':
message = message + '### None message ###' +'\n'
while (imagefile !=' '): # ------ 判斷圖片檔 是否存在?
import os
imagefile=imagefile.strip() # imagefile.strip() 前後之空白去除
if os.path.isfile(imagefile) != True:
message = message + '### ERROR--> imagefile is invalid ###' +'\n' + imagefile +'\n'
imagefile = ' '
break
message = message + '*** send on ' + d
#print ('M',message)
#print ('I',imagefile)
#print ('T',token)
##############注意image 無時 (token ,message ) , else (token ,message, imagefile )
def LINE_send_notify(token, message, imagefile=None, stickerPackageId=None, stickerId=None):
headers = {
"Authorization": "Bearer " + token
}
param = {'message': message}
if stickerPackageId and stickerId:
param['stickerPackageId'] = stickerPackageId
param['stickerId'] = stickerId
if imagefile != ' ':
image = {'imageFile': open(imagefile, 'rb')}
# print(image)
r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=param, files=image)
else:
# print("no image")
r = requests.post("https://notify-api.line.me/api/notify", headers=headers, params=param)
return r

res = LINE_send_notify(token, message, imagefile)

if res.status_code==200:
print("LINE訊息傳送成功 res=",res )
else:
print("LINE訊息傳送失敗 ! res=",res)
print (res.status_code,res.text)

----------------------recorded by linct----------------

8會員
48內容數
樂趣體驗紀錄,沙龍房間有歌唱,生活,科技
留言0
查看全部
發表第一個留言支持創作者!