Skip to content

Instantly share code, notes, and snippets.

@alphaKAI
Last active April 10, 2016 04:07
Show Gist options
  • Save alphaKAI/5d8bea1e637e3720617033aa5148fa0c to your computer and use it in GitHub Desktop.
Save alphaKAI/5d8bea1e637e3720617033aa5148fa0c to your computer and use it in GitHub Desktop.
Sample of LINE echo bot in D Programming Language.
import vibe.d;
import std.stdio,
std.conv,
std.json;
import std.net.curl;
enum LINE_CHANNEL_ID = "YOUR CHANNNEL ID",
LINE_CHANNEL_SECRET = "YOUR CHANNNEL SECRET",
LINE_CHANNEL_MID = "YOUR CHANNNEL MID";
void sendRequestWithJson(string sendJSON) {
enum serverURL = "https://trialbot-api.line.me/v1/events";
auto http = HTTP();
foreach (key, value;
[
"Content-Type" : "application/json; charset=UTF-8",
"X-Line-ChannelID" : LINE_CHANNEL_ID,
"X-Line-ChannelSecret" : LINE_CHANNEL_SECRET,
"X-Line-Trusted-User-With-ACL" : LINE_CHANNEL_MID
]) {
http.addRequestHeader(key, value);
}
writeln("send -> ", sendJSON);
post(serverURL, sendJSON, http);
}
void sendMessageTo(string to, string message) {
writeln("to -> ", to);
writeln("messagee -> ", message);
string sendJSON = `{"to": [` ~ "\"" ~ to ~ "\"" ~ `], "toChannel": 1383378250, "eventType": "138311608800106203", "content":{"contentType": 1, "toType": 1, "text": "` ~ message ~ `" }}`;
sendRequestWithJson(sendJSON);
}
void botProc(HTTPServerRequest req, HTTPServerResponse res) {
writeln("Receive!");
foreach (result; parseJSON(req.json.to!string).object["result"].array) {
auto content = result.object["content"];
string from = content.object["from"].str;
string text = content.object["text"].str;
sendMessageTo(from, "さーばーえこーにゃん! : " ~ text);
// or : sendMessageTo(from, "server echo : " ~ text);
}
}
shared static this() {
auto router = new URLRouter;
router.post("/", &botProc);
auto settings = new HTTPServerSettings;
settings.port = 3000;
listenHTTP(settings, router);
logInfo("Boot!");
}

Installation of this code

Pre-requirements

Note: Currently, LINE bot API is TRIAL, limited to the first 10,000 developers.

Installation

  1. Create vibe.d application skeleton with dub
$ mkdir lineBotInD && cd !^
$ dub init -t vibe.d
  1. Clone or copy this code and paste to lineBotInD/source/app.d (you must replace LINE_CHANNNEL_ ID, SECRET, MID)
  2. Configure your reverse proxy server to forward a port 443 to 3000
  3. Finish. You can build and run this bot with : $ dub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment