Implement pause and resume

This commit is contained in:
Roman 2023-06-06 17:01:17 -04:00
parent a8551a2ba7
commit ae27515e1c
2 changed files with 68 additions and 0 deletions

View file

@ -1,6 +1,7 @@
defmodule Sergei.Consumer do defmodule Sergei.Consumer do
use Nostrum.Consumer use Nostrum.Consumer
require Logger
alias Nostrum.Api alias Nostrum.Api
# Translate params to list of maps # Translate params to list of maps
@ -15,6 +16,8 @@ defmodule Sergei.Consumer do
@slash_commands [ @slash_commands [
{"ping", "Pong", []}, {"ping", "Pong", []},
{"pause", "Pause media playback", []},
{"resume", "Resume media playback", []},
{"play", "Play some tunes", @play_opts} {"play", "Play some tunes", @play_opts}
] ]
@ -99,4 +102,28 @@ defmodule Sergei.Consumer do
{:error, "You are not in a voice channel."} {:error, "You are not in a voice channel."}
end end
end end
# /pause
def do_command(%{guild_id: guild_id, data: %{name: "pause"}}) do
case Sergei.Player.pause(guild_id) do
:ok ->
{:ok, "Pausing..."}
{:error, err} ->
Logger.error("Failed to pause media: #{err}")
{:error, "This is embarrasing..."}
end
end
# /resume
def do_command(%{guild_id: guild_id, data: %{name: "resume"}}) do
case Sergei.Player.resume(guild_id) do
:ok ->
{:ok, "Resuming..."}
{:error, err} ->
Logger.error("Failed to resume media: #{err}")
{:error, "This is embarrasing..."}
end
end
end end

View file

@ -20,6 +20,14 @@ defmodule Sergei.Player do
GenServer.call(__MODULE__, {:play, guild_id, channel_id, url}) GenServer.call(__MODULE__, {:play, guild_id, channel_id, url})
end end
def pause(guild_id) do
GenServer.call(__MODULE__, {:pause, guild_id})
end
def resume(guild_id) do
GenServer.call(__MODULE__, {:resume, guild_id})
end
# Server # Server
@impl true @impl true
def handle_info(:tick, state) do def handle_info(:tick, state) do
@ -47,6 +55,39 @@ defmodule Sergei.Player do
{:reply, res, state} {:reply, res, state}
end end
@impl true
def handle_call({_, guild_id}, _from, state) when not is_map_key(state, guild_id) do
{:reply, {:error, "I'm not playing anything right now"}, state}
end
@impl true
def handle_call({:pause, guild_id}, _from, state) do
%{url: url} = Map.fetch!(state, guild_id)
Voice.pause(guild_id)
state =
Map.put(state, guild_id, %{
url: url,
paused: true
})
{:reply, :ok, state}
end
@impl true
def handle_call({:resume, guild_id}, _from, state) do
%{url: url} = Map.fetch!(state, guild_id)
Voice.resume(guild_id)
state =
Map.put(state, guild_id, %{
url: url,
paused: false
})
{:reply, :ok, state}
end
def play_music(guild_id, channel_id, url) do def play_music(guild_id, channel_id, url) do
cond do cond do
Voice.get_channel_id(guild_id) != channel_id -> Voice.get_channel_id(guild_id) != channel_id ->