最新消息

[公告2014/05/30] 如有需要將部落格中,任何一篇文章的程式碼使用在商業用途,請與我聯繫。

[公告2015/04/26] Line版的 iInfo程式與投資應用 群組已上線想加入的朋友們,請先查看 "入群須知" 再與我聯繫 Line : aminwhite5168,加入請告知身分與回答 "入群須知" 的問題。

[公告2018/04/22] 台北 Python + Excel VBA 金融資訊爬蟲課程,課程如網頁內容 金融資訊爬蟲班:台北班 Python 金融資訊爬蟲、EXCEL VBA 金融資訊爬蟲

[公告2019/01/08] 請注意:我再次重申,部落格文章的程式碼,是要提供各位參考與學習,一旦網頁改版請自行修改,別要求東要求西要我主動修改,你們用我寫東西賺錢了、交差了,請問有分我一杯羹嗎?既然賺錢沒分我,請問有什麼理由要求我修改,如果沒能力改,就花錢來找我上課。

[公告2019/12/01] 若各位有 Excel VBA 案子開發需求,歡迎與我聯繫,可接案處理。

[公告2020/05/22] 頁面載入速度慢,起因為部分JS來源(alexgorbatchev.com)失效導致頁面載入變慢,目前已做調整,請多見諒。

2017年1月3日 星期二

LINE Notify 入門到進階應用(4) --- 傳送文字網路圖片到Line Notify 其他語言

由於Line Notify當推出不久,所以網路上的參考範例資源較少,筆者陸續轉成手邊會的程式語言分享於此,有意願分享的朋友請與筆者聯繫。
Python、GAS、ASP、C++、C# 、PHP、R、Node.js版本將陸續分享於此。
Python 2.7
import requests
def SendMessageToLineNotify(message, picurl):
    Token = "你的Token"
    url = "https://notify-api.line.me/api/notify"    
    payload = {'message':message,
               'imageThumbnail':picurl,
               'imageFullsize':picurl,
               'stickerPackageId':1,
               'stickerId':106
              }
    header = {'Content-Type':'application/x-www-form-urlencoded',
              'Authorization':'Bearer ' + Token
             }
    resp=requests.post(url, headers=header, data=payload)
    print resp.text

def main():
    message = '中文測試~!@#$%^&*()123456789'
    picurl = 'http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg'
    SendMessageToLineNotify(message, picurl)

if __name__ == '__main__':
    main()
Google Apps Script
function SendMessageToLineNotify()
{
  var message = "中文測試~!@#$%^&*()123456789";
  var pictureURL= "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg";
  sendMessage(message, pictureURL);
}

function sendMessage(message, pictureURL){
  var Token = "你的Token";
  var URL = "https://notify-api.line.me/api/notify";

  var payload = 
      {
        'message' : message,
        'imageThumbnail': pictureURL,
        'imageFullsize': pictureURL
      };
  
  var header =
      {
        'Content-Type':'application/x-www-form-urlencoded',
        'Authorization' : 'Bearer ' + Token        
      }
  
  var options =
      {
        'method'  : 'post',
        'payload' : payload,
        'headers' : header
      }; 

  var response = UrlFetchApp.fetch(URL, options);
  Logger.log(response);
}
感謝 ~ M 大大 提供以下ASP程式碼
<%     
Response.ContentType = "text/html"
Response.AddHeader "Content-Type", "text/html;charset=UTF-8"
Response.CodePage = 65001
Response.CharSet = "UTF-8"
    
    '指定的LineNotify Token
    strToken = "你的Token"
    
    'Line Notify的傳送訊息網址
    URL = "https://notify-api.line.me/api/notify"
        
    '中文字串要轉成UTF8
    strMessageUTF8Encode = Server.URLEncode(vbcrlf & "傳網頁圖檔測試 家扶娃娃撲滿 ~!@#$%^*()1234567890ABCabc")

    '網路圖片連結 家扶娃娃撲滿
    strPicURL = "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg"
    
    '傳送參數內容
    strMessage = "message=" & strMessageUTF8Encode
    strImageThumbnail = "imageThumbnail=" & strPicURL
    strImageFullsize = "imageFullsize=" & strPicURL
    strStickerPackageId = "stickerPackageId=" & "1"
    strStickerId = "stickerId=" & "106"
    
    strAllMessage = strMessage & "&" & strImageThumbnail & "&" & strImageFullsize & "&" & strStickerPackageId & "&" & strStickerId
    
    '建立Ajax物件
    Set oXML = server.CreateObject("Microsoft.XMLHTTP")
    
    With oXML
        '使用同步傳輸
        .Open "POST", URL, 0
        
        '設定傳送封包Header
        .SetRequestHeader "Content-Type", "application/x-www-form-urlencoded"
        .SetRequestHeader "Authorization", "Bearer " & strToken
        
        '執行Ajax傳送
        .send (strAllMessage)
        
        response.write  oXML.responseText
    End With
    
    '釋放物件資源
    Set oXML = Nothing  
%>
VC++
#import "msxml4.dll"

using namespace MSXML2;

inline void THROW_IF_FAIL( HRESULT _hr )  { if FAILED(_hr) throw(_hr); }

void SendMessageToLineNotify()
{
        CString csMessage;

        OutputDebugString("測試XMLHTTP傳文字與網路圖片!\n");
        
        try
        {
                //初始化Com元件
                THROW_IF_FAIL(CoInitialize(NULL));
        
                IXMLHTTPRequestPtr xmlrequest=NULL;  
                VARIANT vAsync;
                vAsync.vt = VT_BOOL;
                vAsync.boolVal = FALSE;
                
                VARIANT vUser;
                vUser.vt = VT_BOOL;
                vUser.bstrVal = NULL;
                
                VARIANT vPassword;
                vPassword.vt = VT_BOOL;
                vPassword.bstrVal = NULL;
                
                //LineNotify網址
                bstr_t sUrl = "https://notify-api.line.me/api/notify";                

                //指定的LineNotify Token
                bstr_t Token = "你的Token";

                //網路圖片連結 家扶娃娃撲滿
                CString PicURL = "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg";

                //文字訊息
                CString csPostData;
                csPostData = "message=傳網頁圖檔測試 家扶娃娃撲滿 ~!@#$%^&*()1234567890ABCabc";
                
                //網路圖片
                csPostData = csPostData + "&imageThumbnail=" + PicURL; 
                csPostData = csPostData + "&imageFullsize=" + PicURL;

                //內建貼圖號碼
                csPostData = csPostData + "&stickerPackageId=" + "1";
                csPostData = csPostData + "&stickerId=" + "106";
        
                //
                // 建立 MSXML2.XMLHTTP 物件.
                //
                THROW_IF_FAIL(xmlrequest.CreateInstance("MSXML2.XMLHTTP"));  
                
                //
                // 傳送 HTTPPOSTrequest.
                //
                bstr_t sMethod = "POST";
                THROW_IF_FAIL(xmlrequest->open(sMethod, 
                                               sUrl,
                                               vAsync,
                                               vUser,
                                               vPassword));

                //Header內容設定
                THROW_IF_FAIL(xmlrequest->setRequestHeader("Content-Type:", "application/x-www-form-urlencoded"));                
                THROW_IF_FAIL(xmlrequest->setRequestHeader("Authorization", "Bearer " + Token));
        
                //
                // 傳送 request 到 server.
                //
                THROW_IF_FAIL(xmlrequest->send(_variant_t(csPostData)));
                
                //
                // 取得執行狀態
                //
                long lStatus;
                xmlrequest->get_status(&lStatus);
                if(lStatus == 200)
                {
                   BSTR bstrResponseText;
                   xmlrequest->get_responseText(&bstrResponseText);
                   _bstr_t bstrtbody(bstrResponseText);
                   csMessage.Format("responseText = %s\n", (char*)(bstr_t)bstrtbody); 
                   MessageBox(NULL, csMessage, "執行成功", MB_ICONASTERISK);
                }
                else
                {
                   BSTR bstrResp;
                   xmlrequest->get_statusText(&bstrResp);   
                   csMessage.Format("statusText = %s\n", (char*)(bstr_t)bstrResp);
                   MessageBox(NULL, csMessage, "執行失敗", MB_ICONERROR);
                }
        }
        catch (_com_error &e)
        {
                if(BSTR(e.Description())) 
                {
                   csMessage.Format("Description = %s", BSTR(e.Description())); 
                   OutputDebugString(csMessage);
                }
        }
        catch(...)
        {
         TRACE("*** UNABLE TO LOG EXCEPTION ***");
        }
        CoUninitialize();

        OutputDebugString("執行結束\n");
}
C#
using System;
using System.IO;
using System.Net;
using System.Text;

namespace POSTXML
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a request using a URL that can receive a post. 
            WebRequest request = WebRequest.Create("https://notify-api.line.me/api/notify");

            // Set the Method property of the request to POST.
            request.Method = "POST";

            // Create POST data and convert it to a byte array.
            string Token = "你的Token";
            string message  = "message=" + "傳網頁圖檔測試 家扶娃娃撲滿 ~!@#$%^*()1234567890ABCabc";
            string picURL = "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg";
            string imageThumbnail = "&imageThumbnail=" + picURL;
            string imageFullsize = "&imageFullsize=" + picURL;
            string stickerPackageId = "&stickerPackageId=" + "1";
            string stickerId = "&stickerId=" + "106";
            string postData = message + imageThumbnail + imageFullsize + stickerPackageId + stickerId;
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            // Set the ContentType property of the WebRequest.
            request.ContentType = "application/x-www-form-urlencoded";

            // Set the Header property of the WebRequest.
            request.Headers["Authorization"] = "Bearer " + Token;

            // Set the ContentLength property of the WebRequest.
            request.ContentLength = byteArray.Length;

            // Get the request stream.
            Stream dataStream = request.GetRequestStream();

            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);

            // Close the Stream object.
            dataStream.Close();

            // Get the response.
            WebResponse response = request.GetResponse();

            // Display the status.
            Console.WriteLine(((HttpWebResponse)response).StatusDescription);

            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();

            // Open the stream using a StreamReader for easy access.
            StreamReader reader = new StreamReader(dataStream);

            // Read the content.
            string responseFromServer = reader.ReadToEnd();

            // Display the content.
            Console.WriteLine(responseFromServer);

            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();
        }
    }
}
感謝Yi Tung 大大提供的  PHP
<?php
$initData['message'] = '傳網頁圖檔測試 家扶娃娃撲滿 ~!@#$%^*()1234567890ABCabc';
$initData['imageThumbnail'] = 'http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg';
$initData['imageFullsize'] = 'http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg';
$initData['stickerPackageId'] = '1';
$initData['stickerId'] = '106';  
$token = '你的Token';

echo '<pre>';
print_r(sendLineNotify($initData, $token));
echo '</pre>';

function sendLineNotify($initData, $token,$url = 'https://notify-api.line.me/api/notify') {
    $ch = curl_init();
    $header[] = 'Authorization: Bearer';
    $header[] = $token;
    curl_setopt_array($ch, array(
        CURLOPT_URL => $url,
        CURLOPT_POST => TRUE,
        CURLOPT_RETURNTRANSFER => TRUE,
        CURLOPT_SSL_VERIFYHOST => 0,
        CURLOPT_SSL_VERIFYPEER => 0,
        CURLOPT_HTTPHEADER => array(implode(' ',$header)),
        CURLOPT_POSTFIELDS => http_build_query($initData),
    ));

    $result = curl_exec($ch);
    curl_close($ch); 
    $aResult = json_decode ($result, TRUE);
    return $aResult;
}
?>
感謝 ~ M 大大 提供以下R程式碼
library(httr)
picurl <- "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg" 
url <- "https://notify-api.line.me/api/notify"
message <- "中文測試~@#$%^&*()123456789"
token <- "Bearer 你的Token"
postdata <- list("message"=message, 
                 "imageThumbnail"=picurl, 
                 "imageFullsize"=picurl,
                 "stickerPackageId"="1", 
                 "StickerId"="106")
header <- add_headers("Authorization"=token)
req <- POST(url, header, body = postdata, encode="form") 
status <- content(req , as ="text", encoding="utf-8")
status
感謝 Cass (C.K.) 大大 協助Node.js環境建置,來完成以下程式碼
var Token = "你的Token";
var LineNotifyURL = "https://notify-api.line.me/api/notify";
var PictureURL = "http://www.ccf.org.tw/new/endpoverty/images/product/product-pic1.jpg";
var strMessage = "message=" + "傳網頁圖檔測試 家扶娃娃撲滿 ~!@#$%^*()1234567890ABCabc";   
var strStickerPackageId  ="stickerPackageId=" + "1";
var strStickerId  ="stickerId=" + "106";
var strImageThumbnail = "imageThumbnail=" + PictureURL;
var strImageFullsize = "imageFullsize=" + PictureURL;
var strAllMessage = strMessage + "&" + strImageThumbnail + "&" + strImageFullsize + "&" + strStickerPackageId + "&" + strStickerId;

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
    if (xhttp.readyState === 4) {
        console.log(xhttp.responseText);
        console.log(xhttp.status);
    }
};            

xhttp.open('POST', LineNotifyURL, true);
xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
xhttp.setRequestHeader('Authorization', 'Bearer ' + Token);
xhttp.send(strAllMessage);
可參考 Node.js 環境建置,執行xmlhttprequest

執行結果:
參考資料: