“You don’t need to be so tense,” one of the men told them. “We will not kill Bengalis. We will only kill foreigners.” At that, Mr. Barai’s gaze flicked to the floor of the restaurant, where he could see six or seven bodies, apparently shot and then sliced with machetes. All appeared to be foreigners.

The gunmen, he said, seemed eager to see their actions amplified on social media: After killing the patrons, they asked the staff to turn on the restaurant’s wireless network. Then they used customers’ telephones to post images of the bodies on the internet…

Even as they killed the foreigners, the attackers were unfailingly polite and solicitous with the restaurant staff and other Bangladeshis, Mr. Barai said.

They took the staff into their confidence, complaining that foreigners, with their skimpy clothes and taste for alcohol, were impeding the spread of Islam. “Their lifestyle is encouraging local people to do the same thing,” a militant said.