Delphi拿Line Notify來當通知

  • 取得個人的TOKEN

進到網站 https://notify-bot.line.me/zh_TW/ ,右上角有一個登入,登入後選個人頁面

往下拉可以看到一個發行存取權杖(TOKEN),按發行權杖功能。按照步驟就可以取得權杖

複製權杖下來備用。

接下來在安裝ipwork的Delphi上,加入ipwhhtp的元件後,呼叫LINE NOTIFY的程式如下:

2021.06.12 更新 Delphi 版本 ipwork試用連結(官網)
https://www.nsoftware.com/download/download.aspx?sku=IPDF-A&type=demo

七行程式就可以了!

  ipwhttp1.Config(‘CodePage=65001’);

  ipwhttp1.Timeout := 10;

  ipwhttp1.ResetHeaders;

  ipwhttp1.OtherHeaders := ‘Authorization: Bearer +’這裡改成剛才的權杖';

  ipwhttp1.ContentType := ‘application/x-www-form-urlencoded;’;

  ipwhttp1.PostData:= ‘message=’+’這裡改成你要通知的內容';

  ipwhttp1.Post(‘https://notify-api.line.me/api/notify’);

C# ASP.net執行APPcmd/DNScmd實踐網站自動平台化

最近在測試,如果透過web申請帳號後,可不可以直接在DNS上一增子網域以及在IIS上增加站台的方式,直接申請後就有站台,在Windows 的網站主機上,似乎要透過appcmd與dnscmd達到。後來弄出了一個可以執行的方式,主要重點在於要有較高權限的帳密透過process執行cmd模式再去下指令。分享一下

/// <summary>

        /// 新增IIS站台

        /// </summary>

        /// <param name=”subdomain”>網站名稱</param>

        /// <param name=”domain”>網域</param>

        /// <param name=”webpath”>網頁位置</param>

        /// <returns></returns>

        public bool AddSite(string subdomain, string domain, string webpath)

        {

            using (Process p = new Process())

            {

                p.StartInfo.FileName = @”cmd.exe”;

                p.StartInfo.UseShellExecute = false;

                p.StartInfo.CreateNoWindow = true;

                p.StartInfo.RedirectStandardError = true;

                p.StartInfo.RedirectStandardInput = true;

                p.StartInfo.RedirectStandardOutput = true;

                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                p.StartInfo.UserName = “高權限帳號”;

                string pw = “高權限密碼”;

                SecureString ss = new SecureString();   

                foreach (char c in pw)

                {

                    ss.AppendChar(c);

                }

                p.StartInfo.Password = ss;

                //

                p.StartInfo.Arguments = “/c appcmd add site /name:”+subdomain+” /bindings:\”http/*:80:”+subdomain+”.”+domain+”,https/*:443:”+subdomain+”.”+domain+”\” /physicalPath:\””+webpath+”\””;

                p.Start();

                p.WaitForExit();

                StreamReader sr = p.StandardOutput;

                p.Close();

                string message = sr.ReadToEnd().Replace(“\n”, “<br />”);

                if (message.Contains(“ERROR”))

                {

                    return false;

                }

                else

                {

                    return true;

                }

            }

        }

        /// <summary>

        /// 透過指令新增子網域(如: levin.ksi.com.tw)

        /// </summary>

        /// <param name=”subdomain”>子網域名稱</param>

        /// <param name=”domain”>主網域</param>

        /// <param name=”ip”>主機IP</param>

        /// <returns></returns>

        public bool AddDNS(string subdomain,string domain,string ip)

        {

            using (Process p = new Process())

            {

                p.StartInfo.FileName = @”cmd.exe”;

                p.StartInfo.UseShellExecute = false;

                p.StartInfo.CreateNoWindow = true;

                p.StartInfo.RedirectStandardError = true;

                p.StartInfo.RedirectStandardInput = true;

                p.StartInfo.RedirectStandardOutput = true;

                p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;

                p.StartInfo.UserName = “高權限帳號”;

                string pw = “高權限密碼”;

                SecureString ss = new SecureString();

                foreach (char c in pw)

                {

                    ss.AppendChar(c);

                }

                p.StartInfo.Password = ss;

                p.StartInfo.Arguments = @”/c dnscmd /recordadd ” + domain + ” ” + subdomain + ” A ” + ip;

                p.Start();

                p.WaitForExit();

                StreamReader sr = p.StandardOutput;

                p.Close();

                string message = sr.ReadToEnd().Replace(“\n”, “<br />”);

                if (message.Contains(“成功”)){

                    return true;

                }

                else

                {

                    return false;

                }

            }

        }

初探 ASP.net Core 打造 LINE BOT

程式下載: https://drive.google.com/file/d/1rmz910QWqQxLa8XOMWrFG1fjSTPoTLFd/view?usp=sharing
本篇學會
– LOG的撰寫以及追蹤
– ngrok 讓本機可以debug webhook
– JSON 的基本運用
– LINE BOT初步瞭解(回應訊息)


準備篇

– Visual Studio 

– ngrok(localhost 對應到https public domain的服務)

下載連結:
https://ngrok.com/download

– LINE Developers 帳號(免費)

https://developers.line.biz/en/ “https://developers.line.biz/en/

開發步驟

–  新增asp.net Core web應用程式後按下一步


–  設定專案名稱LINEBOT,建立



–  選擇.NET Core → ASP.NET Core 3.1 →API→建立



–  首先安裝 *serilog.extensions.logging*



–  在Startup.cs加上  ILoggerFactory ,並設定檔名



–  在預設的WeatherForecastController.cs試著加上LOG



–  開啟程式後,到logs目錄下確定LOG正常



–  新增API控制器


–  修改route為 api/linebot ,程式如下

           // 記得using Microsoft.Extensions.Logging;
        readonly ILogger<LINEBOTController> _log;

        public LINEBOTController(ILogger<LINEBOTController> log)
        {
            _log = log;
        }
        [HttpPost]
        public async Task<IActionResult> Post(dynamic request
        {
            string x = Convert.ToString(request);
            _log.LogInformation(x);             
            return Ok(request);
        }



– 執行程式後,打開IIS Express,確認PORT號



– 打開命令提示字元,切換到ngrok目錄下



– 執行命令(記得Port號改成自己對應)
`!ngrok http 33766 -host-header=”localhost:33766″`



– 執行後,會取到一個https開頭網址,記下來後(不要關閉視窗)



– 進到LINE Developer網址,新增Provi![]



– 新增一個 Messaging API的Channel



– 設定名稱與描述、目錄、子目錄後勾選允許相關條款後按Create



– 最後同意使用資訊



– 建立完成後進到MessagingAPI頁籤



– 修改以下內容



– 允許加入群組或多人聊天室



– 停用加入好友訊息以及自動回應訊息,啟用webhook功能





– 加webhook URL輸入



– 輸入確定後按Verify

– 出現 307 Temporary Redirect



– Startup.cs中的 app.UseHttpsRedirection() 註解,重新開啟程式



– 重新驗證後成功!



– 從LOG看到LINE傳來的驗證訊息



## 回聲蟲

– 從開發者網站中的Messaging API得知如何做[回應reply](https://developers.line.biz/en/docs/messaging-api/sending-messages/#reply-messages)



– 安裝 NewtonSoft.Json



– 到LINE DEVELOPER中取得TOKEN複製



– 加上程式如下

    public class LineReceivedMessage
    {
        public List<Event> events;
        public LineReceivedMessage()
        {
          events = new List<Event>();
        }
    }
    public class Event
    {
            public string type { get; set; }
           public Source source { get; set; }
         public EventMessage message { get; set; }
         public string replyToken { get; set; }
         public Event()
         {
           source = new Source();
           message = new EventMessage();
         }
    }
    public class Source
    {
         public string userId { get; set; }
    }
    public class EventMessage
    {
        public string id { get; set; }
        public string type { get; set; }
        public string text { get; set; }
    }


– 修改POST函數如下

        public async Task<IActionResult> Post(dynamic request)
        {
            string x = Convert.ToString(request);
            _log.LogInformation(x);               
            var channelAccessToken = “你的TOKEN”;
            var receivedMessage = JsonConvert.DeserializeObject<LineReceivedMessage>(x); // 收到訊息解成物件
            string userid = receivedMessage.events[0].source.userId;  // 取得使用者ID
            string message = receivedMessage.events[0].message.text;  // 取得文字訊息
            var replyToken = receivedMessage.events[0].replyToken;  // 取得回應TOKEN
            var replyMessage = new
            {
                replyToken = replyToken,
                messages = new object[] { new {
                    type = “text”,
                    text = message
                }
                }
            };
            string s = JsonConvert.SerializeObject(replyMessage);  // 轉為JSON字串
            byte[] bytes = Encoding.UTF8.GetBytes(s);
            WebClient webClient = new WebClient();
            webClient.Headers.Clear();
            webClient.Headers.Add(“Content-Type”, “application/json”);
            webClient.Headers.Add(“Authorization”, “Bearer ” + channelAccessToken);
            webClient.UploadData(“https://api.line.me/v2/bot/message/reply”, bytes);
            return Ok(request);
        }


– 結果



##參考資料:

LINE DEVELOPER API文件

[https://developers.line.biz/zh-hant/docs/messaging-api/](https://developers.line.biz/zh-hant/docs/messaging-api/ “https://developers.line.biz/zh-hant/docs/messaging-api/”)

C# ASP.net Core開發line bot使用ngrok出現307 Temporary Redirect

使用asp.net core 開發LINE BOT時,使用ngrok做本機的服務器時,驗證Webhook出現錯誤。ngrok出現 307 Temporary Redirect的錯誤!

解決方式:

Starup.cs中有一句app.UseHttpsRedirection(); 前面加上 // 註解掉就可以了

參考:

ngrok http [port] -host-header="localhost:[port]"

Delphi 新的VCL元件TEdgeBrowser

2018年12月6日,微軟宣布Microsoft Edge未來將基於Chromium開發後,微軟在新的作業系統中已逐步移除存在已久的IE瀏覽器,取而代之預設為Edge瀏覽器。

10.4也新增了以Edge瀏覽器為主的webbrowser元件來處理,並取代了早先的TWebBrowser。不過,TWebBrowser仍然保留在VCL元件中,但新增了SelectedEngine可以選取Edge的WebView2瀏覽器。

而新增的Edge使用方式也與先前相同

EdgeBrowser1.Navigate('http://superlevin.ifengyuan.tw/');

來源: https://community.idera.com/developer-tools/b/blog/posts/new-vcl-tedgebrowser-component-coming-rad-studio-10-4?fbclid=IwAR3QOllGOkKev4Y22ILbr0A2l7rquKRHKVeq9F1nx78g7832vS5WzNBbdss

Delphi | POS收銀系統實現客顯播放mp4影片

Delphi內建的mediaplayer似乎無法播放MP4的影片!只好透過系統內的mediaplayer來實作了~
一、Component→Import Component然後選擇ActiveX Control

二、搜尋media,找到Windows Meida Player

三、原則上就是下一步安裝完成就好

接下來程式的部份

在畫面上放上WindowsMediaPlayer1、Button、Timer、OpenDialog、ProgressBar1。

程式碼如下:

一、

procedure TForm1.FormCreate(Sender: TObject);
begin
WindowsMediaplayer1.uiMode := ‘none’;  //不顯示按鈕
end;

二、

procedure TForm1.FormCloseQuery(Sender: TObject; var CanClose: Boolean);
begin
WindowsMediaPlayer1.controls.stop;
end;

三、

procedure TForm1.Button1Click(Sender: TObject);
begin
if opendialog1.Execute then begin
WindowsMediaPlayer1.URL := ‘file://’+opendialog1.FileName;
WindowsMediaplayer1.uiMode := ‘none’;
WindowsMediaPlayer1.controls.play;
end;
end;

四、

procedure TForm1.WindowsMediaPlayer1PlayStateChange(ASender: TObject;
NewState: Integer);
begin
case NewState of
wmppsPlaying: begin
Timer1.Enabled := True;
end;
wmppsStopped,
wmppsPaused: begin
Timer1.Enabled := False;
end;
end;
end;

五、

procedure TForm1.Timer1Timer(Sender: TObject);
var
Duration: double;
Position: double;
begin

Form1.Caption := WindowsMediaPlayer1.controls.currentPositionString
+ ‘ of ‘
+ WindowsMediaPlayer1.currentMedia.durationString;

Duration := WindowsMediaPlayer1.currentMedia.duration;
Position := WindowsMediaPlayer1.controls.currentPosition;
ProgressBar1.Position := Trunc( Position*(Duration/ProgressBar1.Max) );
end;