はじめに
discordrbの記事が少ない!
rubyでbotが書きたい!
今回作るもの
タイトル通り
手順
discordrbのインストール
$ gem install discordrb
Discord botのtokenを取得
ここにアクセスし「Create an application」を押して1つapplicationを作る
CLIENT IDを取得
https://discordapp.com/oauth2/authorize?client_id=ここに取得したClientID&scope=bot&permissions=0
にアクセスしbotをServerに接続させる
するとさきほどのページのbotページからTOKENを取得することができる.
botを作る
とりあえずソースコード
bot.rb
TOKEN = '自分で取得してね'
CLIENT_ID = ID(数字)
# 通知用のチャンネルID
inform_channel = チャンネルID または '#チャンネルname'
# bot
bot = Discordrb::Commands::CommandBot.new token: TOKEN, client_id: CLIENT_ID, prefix:'/'
# 誰かがvoice channelに出入りしたら発火
bot.voice_state_update do |event|
# 発火させたユーザー名を取得
user = event.user.name
# もしデータが空だと抜けていったチャンネルを取得
if event.channel == nil then
# チャンネル名を取得
channel_name = event.old_channel.name
# 退出したことをinform_channelに通知
bot.send_message(inform_channel, "@everyone #{user} が #{channel_name}を出たで~")
else
# チャンネル名を取得
channel_name = event.channel.name
# 入室したことをinform_channelに通知
bot.send_message(inform_channel, "@everyone #{user} が #{channel_name}に入ったで~")
end
end
# botを起動
bot.run
説明?
voice_state_update
:ボイスチャンネルで変更があれば発火するイベント
event.user.name
:発生されたユーザ名を取得
event.channel
:ボイスチャンネルに入室したとき情報が入る.退出したときはnilが入る
bot.send_message(channel_id, '送りたい内容')
:channel_id(#channel_nameでも可)にメッセージを送信する
テスト
$ ruby bot.rb