soukouki’s diary

誰かの役に立つ記事をかけたらいいなあ

LispでDiscordBotを作る!

wispというaltJSの方言(clojureに近い)を使い、discord.jsというライブラリを使って楽をします。

discord.jsは活発なライブラリなので、新機能とかが出てきても安心ですね!

まずは、node.jsをインストール。

それぞれのライブラリをインストール npm install discord.js npm install wisp

そしてプログラムを入力

test.wisp

(def token "*****TOKEN*****")

(def Discord (require "discord.js"))

(def client (Discord.Client.))

(client.on "message"
  (fn [msg]
      (let [args (msg.content.split " ")]
        (console.log args)
        (cond
          (== (get args 0) "!dice")
            (let [num (let [n (parse-int (get args 1) 10)]
                           (if (naN? n) 6 n))]
                 (msg.channel.send (+ (num.->string 10)
                                      "面ダイズを振った。\nカランコロン....\n__"
                                      (+ 1 (Math.floor(* (Math.random) num))) "__")))))))

(client.login token)

(wisp初心者なので間違っているところなどありましたらコメントにお願いします ><)

(naN?問題()) (連続let・・・)

Discord側の設定や、トークンについては discordapp.com ここから

イチからDiscord Bot 。for Ruby - Qiita

Discord Bot の 簡単な作り方 – Asamac blog

ここらを適当に参考にしてください。

cat test.wisp | node_modules/.bin/wisp --no-map > test.js

すると、こんなソースコードが出力されます。

test.js

var token = exports.token = '*****TOKEN*****';
var Discord = exports.Discord = require('discord.js');
var client = exports.client = new Discord.Client();
client.on('message', function (msg) {
    return function () {
        var argsø1 = msg.content.split(' ');
        console.log(argsø1);
        return (argsø1 || 0)[0] == '!dice' ? function () {
            var numø1 = function () {
                var nø1 = parseInt((argsø1 || 0)[1], 10);
                return isNaN(nø1) ? 6 : nø1;
            }.call(this);
            return msg.channel.send(numø1.toString(10) + '面ダイズを振った\u3002\nカランコロン....\n__' + (1 + Math.floor(Math.random() * numø1)) + '__');
        }.call(this) : void 0;
    }.call(this);
});
client.login(token);

node test.js

f:id:soukouki:20171115222912p:plain

あなたに快適なBOTライフを!

node v8.9.1 discord.js@11.2.1 wisp@0.10.0