A Wisconsin teenager was sentenced on Thursday to 40 years in a psychiatric hospital for trying to kill a friend to gain the favor of Slender Man, a fictional internet character.

The girl, Morgan Geyser, 15, pleaded guilty last year to attempted first-degree intentional homicide as part of a deal in which prosecutors agreed not to seek prison time. Her lawyers and doctors said that when she and another friend, Anissa Weier, who were both 12 at the time, committed the crime, Ms. Geyser was delusional as a result of schizophrenia and psychotic spectrum disorder. (Ms. Weier pleaded guilty to a lesser charge — being a party to attempted second-degree intentional homicide — and was sentenced in December to 25 years in a psychiatric hospital.)

Ms. Geyser’s lawyers had argued for a shorter commitment in a less restrictive facility, saying she no longer showed symptoms of psychosis. Two doctors called by the defense testified to that effect. But another doctor testified for the prosecution that Ms. Geyser still posed a danger to the public, and that she had described hearing voices as recently as September.

In handing down the sentence, Judge Michael O. Bohren, of Waukesha County Circuit Court, said he considered a 40-year commitment “reasonable and fair taking into account the unique circumstances of this case.” Ms. Geyser’s lawyers can petition for her release every six months.