推送基礎訊息

前置處理

1.建立Line bot account,取得Channel Access Token及User ID。 參考上一篇

2.安裝Visual Studio 2019以上版本,並安裝.net 6環境。

3.建立Console專案,並使用Nuget套件管理員安裝LineBotSDK套件。 套件參考

引用LineBotSDK

專案建立好並安裝好套件後,開啟Program.cs,引用LineBotSDK套件,並建立「Bot」實體將前面取得的ChannelAccessToken傳入。

private static readonly string _channelAccessToken = "--- 請更換為自己的ChannelAccessToken ---";
private static readonly string _userID = "--- 請更換為自己的User ID ---";
    
private static readonly Bot _bot = new(_channelAccessToken);

推送文字訊息

推送文字訊息,只需要將文字訊息傳入PushMessage方法。程式碼如下:

_bot.PushMessage(_userId, "推送文字訊息");

推送貼圖訊息

使用訊息Api可以發送貼圖,貼圖的ID及貼圖包ID可以在下面的網址查詢: Stickers。 一般用戶只能夠推送Message Api所定義的貼圖,若需要發送其他貼圖,需要先將Line bot升級為開發者帳號,並向Line官方提交貼圖申請。 貼圖推送程式碼如下:

_bot.PushMessage(_userId, 1, 3);

推送圖片訊息

推送圖片訊息須將圖片先上傳至雲端空間,並取得圖片網址,再將圖片網址傳入PushMessage方法。程式碼如下:

var url = new Uri("--- 你的圖片網址 ---");
_bot.PushMessage(_userId, url);

推送語音訊息

推送語音訊息須將語音先上傳至雲端空間,並取得語音網址,再將語音網址及duration(ms)傳入PushMessage方法。程式碼如下:

var imgUrl = new Uri("--- 你的語音網址 ---");
var audioMsg = new AudioMessage(imgUrl, duration); //  duration為語音長度,單位為毫秒
_bot.PushMessage(_userId, audioMsg);

推送影片訊息

推送影片訊息須將影片及封面圖片上傳至雲端空間,並取得影片網址及影片封面圖網址,再將影片網址及影片封面圖網址傳入PushMessage方法。程式碼如下:

var videoUrl = new Uri("--- 你的影片網址 ---");
var videoPreviewUrl = new Uri("--- 你的影片封面圖網址 ---");
var videoMsg = new VideoMessage(videoUrl, videoPreviewUrl);
_bot.PushMessage(_userId, videoMsg);

推送位置(GPS)訊息

推送位置訊息需要的資訊就比較多了,需要提供地點名稱、地址、緯度及經度。 這些資訊都可以在Google地圖中取得,若是地點沒有直接顯示座標的話,點選地點後就可以從網址上看到經緯度座標。 程式碼如下:

var title = @"大安森林公園";
var address = @"台北市大安區新生南路二段1號";
var latitude = 25.030000;
var longitude = 121.535833;
var locationMsg = new LocationMessage(title, address, latitude, longitude);
_bot.PushMessage(_userId, locationMsg);

執行結果

程式碼調整好後直接執行執行,Line bot就會推送訊息出來,去Line bot的聊天室就能看到推送的結果了。

圖:Line bot聊天室

Git傳送門

An unhandled error has occurred. Reload 🗙