発言に反応するDiscord Botの既存実装があり、そいつにブラウザとかから入力した内容を喋らせたくなったのでLaravelアプリにのっけた実装のメモ。
Setup
$ composer require restcord/restcord
Test
test.php
$discord = new DiscordClient(['token' => config('services.discord.token')]);
$discord->channel->createMessage(['channel.id' => 613584569618399251, 'content' => 'Foo Bar Baz']);
exit;
チャンネル一覧の実装
// controller
public function index()
{
$client = new DiscordClient(['token' => config('services.discord.token')]);
$channels = $client->guild->getGuildChannels(['guild.id' => 319818715971715073]);
return view('Channel.index', compact('channels'));
}
// blade
@foreach($channels as $channel)
<ul>
<li>{{ $channel->name }}</li>
</ul>
@endforeach
チャンネル詳細からメッセージ送れるようにする実装
// index.blade.php
@foreach($channels as $channel)
<ul>
<li><a href="{{ route('channels.show', ['channel' => $channel->id]) }}">{{ $channel->name }}</a></li>
</ul>
@endforeach
// show.blade.php
<h2>Post Message</h2>
<form action="{{ route('channels.store') }}" method="post">
{{ csrf_field() }}
<input type="hidden" name="channel_id" value="{{ $channelModel->id }}">
<textarea name="content"></textarea>
<button type="submit">submit</button>
</form>
<h2>Get Messages</h2>
<ul>
@foreach($messages as $message)
<li>{{ $message->author['username'] }}:{{ $message->content }}</li>
@endforeach
</ul>
// controller
class ChannelController extends Controller
{
/** @var DiscordClient */
private $discordClient;
public function __construct()
{
$this->discordClient = new DiscordClient(['token' => config('services.discord.token')]);
}
public function index()
{
$channels = $this->discordClient->guild->getGuildChannels(['guild.id' => 319818715971715073]);
return view('Channel.index', compact('channels'));
}
public function show(int $channel)
{
$channelModel = $this->discordClient->channel->getChannel(['channel.id' => $channel]);
$messages = $this->discordClient->channel->getChannelMessages(['channel.id' => $channel]);
return view('Channel.show', compact('channelModel', 'messages'));
}
public function store()
{
$params = [
"channel.id" => (int)request()->input('channel_id'),
"content" => (string)request()->input('content')
];
$this->discordClient->channel->createMessage($params);
return redirect(route('channels.show', ['channel' => (int)$params['channel.id']]));
}
}
VCチャンネルに参加させて何か喋らせる
追記予定
成果物
チャンネル一覧
https://www.ta9to.com/chimney/channels
チャンネル詳細(メッセージ投稿フォーム)
https://www.ta9to.com/chimney/channels/732386754056683651