Delphi 實現 圖靈機器人API(IDHTTP POST )


      此功能所需的 Key及接口文檔,都可以在圖靈機器人的官網下載, 小伙伴們需要申請自己的圖靈機器人賬號。

      申請方法請自行百度“圖靈機器人”  。

      登錄賬號后,在左側的[機器人接入],獲取需要的信息,記得一定要關閉 secret,開啟的話,需要對請求進行特殊處理,具體處理方法可以看接口文檔中的“數據加密Demo”,當然Java 開發的小伙伴可以直接使用Demo(流行的語言真好,東西都是現成的)

     

      下面貼出的是POST請求,實現圖靈機器人的方法。

unit Demo;

interface

uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls,IdHTTP;

type
  TForm1 = class(TForm)
    Memo1: TMemo;
    Edit1: TEdit;
    Button1: TButton;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    function SendMsg(Msg : string) : string;
  end;

var
  Form1: TForm1;

implementation

{$R *.dfm}

{ TForm1 }

function TForm1.SendMsg(Msg : string) : string;
var
  idhttp :  TIdHTTP;
  url,ResquestStr,ResponseStr : string;
  ResquestStream,ResponseStream : TStringStream;
begin
  Result := '';
  idhttp := TIdHTTP.Create(nil);
  idhttp.Request.ContentType := '';

  //info 傳遞信息需要 UTF8 加密,否則機器人不能正確識別
  ResquestStr := '{"key":"你的KEY","info":"'+ UTF8Encode(Msg) +'","userid":"demo1"}';

  //將傳遞的信息,寫入請求流
  ResquestStream := TStringStream.Create(ResquestStr);
  ResponseStream := TStringStream.Create('');
  url := 'http://www.tuling123.com/openapi/api';
  try
    try
      //發起請求
      idhttp.Post(url,ResquestStream,ResponseStream);
    except
      on e: Exception do
      begin
        ShowMessage('出現異常:' + e.Message);
      end;
    end;
    //獲取響應的信息
    ResponseStr := ResponseStream.DataString;
    //響應的信息需要進行 UTF8 解密 
    ResponseStr := UTF8Decode(ResponseStr);
    Result := ResponseStr;
  finally
    idhttp.Free;
    ResquestStream.Free;
    ResponseStream.Free;
  end;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  acceptInfo : string;
begin
  //向圖靈機器人發送信息,並獲取返回
  acceptInfo := SendMsg(Edit1.Text);
  //將信息在界面上顯示
  Memo1.Lines.Add(acceptInfo);
end;

end.

大概的方法就是這樣了

題外話:雖然實現了圖靈機器人API,圖靈機器人有自己的NLP知識庫,但是如何活用知識庫,擴充我們的機器人,實在是沒啥好的方向,哪位小伙伴有興趣可以指教下

     

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM