  We consider a triangle diagram for $B^0\to (J/\psi\pi^+\pi^-) K^+\pi^-$ where
an $X(3872)$ peak has been observed experimentally. We demonstrate that a
triangle singularity inherent in the triangle diagram creates a sharp peak in
the $J/\psi\pi^+\pi^-$ invariant mass distribution when the final
$(J/\psi\pi^+\pi^-)\pi$ invariant mass is at and around the $D^*\bar D^*$
threshold. The position and width of the peak is 3871.68 MeV (a few keV above
the $D^{*0}\bar{D}^0$ threshold) and $\sim$0.4 MeV, respectively, in perfect
agreement with the precisely measured $X(3872)$ mass and width: $3871.69\pm
0.17$ MeV and $< 1.2$ MeV. This remarkable agreement is virtually
parameter-free. The result indicates that the considered mechanism has to be
understood in advance when separating an $X(3872)$-pole contribution from
$B^0\to (J/\psi\pi^+\pi^-) K^+\pi^-$ data; the separation yields an
$X(3872)\pi$ lineshape that could be used to determine the $X(3872)$ mass. We
suggest a method to set a constraint on the triangle mechanism by analyzing a
charge analogous process $B^0\to (J/\psi\pi^0\pi^-) K^+\pi^0$ where a similar
triangle singularity generates an $X^-(3876)$-like peak.
