# Direct messages with bots

> Open, read, send in and close direct messages with bots, and let members turn DMs from bots off.

A **direct message** (DM) is a private channel between one bot and one member, relayed by the host.
Only those two can see it: not the owner, not administrators. Members can open a DM with any bot
that has the `dms` capability; bots can open one with a member who allows DMs from bots.

## Opening and sending

**JavaScript:**

```js
const bot = community.member(botMemberId);
const dm = await bot.dm();                 // the DM channel, opened if needed
await dm.send("hi!");
await bot.send("hi again");                // the same, in one call

for (const channel of community.dms) {     // this member's open DMs
  console.log(channel.recipient?.displayName, channel.isDM);
}
await dm.closeDm();                        // hides it for this member
```

**Rust:**

```rust
let bot = community.member(bot_member_id);
let dm = bot.dm()?;                        // the DM channel, opened if needed
dm.send("hi!")?;
bot.send("hi again")?;

for channel in community.dms() {
    println!("{:?} {}", channel.recipient(), channel.is_dm());
}
dm.close_dm()?;
```

A DM is a channel: messages, replies, reactions, embeds, a bot's components and modals, and that
bot's slash commands all work in it. Message events in a DM are marked as such.

## Events

**JavaScript:**

```js
client.on("dmCreate", (channel, recipient) => { /* opened by either side, or found at load */ });
client.on("dmDelete", (channel) => { /* this member closed it */ });
client.on("messageCreate", (message) => {
  if (message.channel.isDM) { /* a message in a DM */ }
});
```

**Rust:**

`Event::DmCreate { channel, recipient }` and `Event::DmDelete(channel)`; messages in DMs come as
`Event::MessageCreate` like any other.

## The member decides

Each member chooses, per community, whether bots may open DMs with them:

**JavaScript:**

```js
const { dms_from_bots } = await community.dmSettings();
await community.setDmsFromBots(false);
```

**Rust:**

```rust
let settings = community.dm_settings()?;
community.set_dms_from_bots(false)?;
```

A closed DM stays closed to the bot until the member writes in it or opens it again. Bots are also
rate limited (at most 10 new DMs a minute, and 5 messages an hour into a DM the member never wrote
in). Errors your app may show: `FORBIDDEN` with reason `dms_closed`, `RATE_LIMITED` with category
`dms`, and `NOT_FOUND` for a DM the member isn't part of.
