# Welcome DM

> Greets new members by direct message, answers what they write back, and offers /dm-me.

When someone joins, the bot sends them a welcome in a [direct message](/docs/guide/bots/direct-messages/) and answers what they write there. It needs the `members` capability (to hear joins) and `dms`.

Source in zaun-bot: [`examples/ts/welcome-dm`](https://github.com/zaunchat/zaun-bot/tree/main/examples/ts/welcome-dm) (TypeScript) and [`examples/rust/welcome-dm`](https://github.com/zaunchat/zaun-bot/tree/main/examples/rust/welcome-dm) (Rust).

## The code

**TypeScript:**

```ts title="src/index.ts"
// Welcomes every new member with a direct message, answers what they write back, and offers
// `/dm-me` to open the conversation on demand.

const bot = new Bot();
let greeted = 0;

bot.on('ready', (me) => bot.log.info(`welcome bot ${me.memberId} is up`));

bot.on('memberAdd', (member, ctx) => {
  if (member.botId) return;
  try {
    ctx.dm(member.memberId, `Welcome, ${member.displayName}! Reply here if you have a question, or type \`rules\` to see them.`);
    greeted += 1;
  } catch (e) {
    // The member turned DMs from bots off: respect it.
    bot.log.info(`no welcome DM for ${member.memberId}: ${e instanceof ZaunError ? e.code : e}`);
  }
});

bot.on('messageCreate', (message, ctx) => {
  if (!message.isDM || ctx.isMe(message.authorId)) return;
  const answer = message.content.trim().toLowerCase() === 'rules'
    ? '1. Be kind. 2. No spam. 3. Have fun.'
    : 'Thanks! A moderator will read this soon.';
  ctx.reply(message, answer);
});

bot.command(new SlashCommandBuilder().setName('dm-me').setDescription('Get a direct message from the welcome bot'), (i) => {
  try {
    bot.messages.dm(i.member.memberId, 'Hi! What can I help you with?');
    i.reply({ content: 'Check your direct messages.', ephemeral: true });
  } catch {
    i.reply({ content: "I can't message you: you have direct messages from bots turned off.", ephemeral: true });
  }
});

bot.command(new SlashCommandBuilder().setName('greeted').setDescription('How many members I welcomed'), (i) => {
  i.reply({ content: `I welcomed ${greeted} member(s) since I started.`, ephemeral: true });
});

export const { init, onEvent, onInteraction, onAutocomplete, onTimer, onVoiceEvent } = bot.exports();
```

**Rust:**

```rust title="src/lib.rs"
//! Welcomes every new member with a direct message, answers what they write back, and offers
//! `/dm-me` to open the conversation on demand.

use zaun_bot::prelude::*;

#[derive(Default)]
struct Welcome {
    /// How many members this instance greeted.
    greeted: u32,
}

impl Bot for Welcome {
    fn commands(&mut self, _: &Config) -> Vec<ApplicationCommand> {
        vec![SlashCommand::new("dm-me", "Get a direct message from the welcome bot").build()]
    }

    fn on_ready(&mut self, _: EventContext, me: Ready) {
        log_info!("welcome bot {} is up", me.member_id);
    }

    fn on_member_join(&mut self, ctx: EventContext, member: Member) {
        if member.bot_id.is_some() {
            return;
        }
        let text = format!(
            "Welcome, {}! Reply here if you have a question, or type `rules` to see them.",
            member.display_name
        );
        match ctx.dm(&member.member_id, text) {
            Ok(_) => self.greeted += 1,
            // The member turned DMs from bots off: respect it.
            Err(e) => log_info!("no welcome DM for {}: {}", member.member_id, e.code),
        }
    }

    fn on_message_create(&mut self, ctx: EventContext, message: Message, is_dm: bool) {
        if !is_dm || ctx.is_me(&message.author_id) {
            return;
        }
        let answer = if message.content.trim().eq_ignore_ascii_case("rules") {
            "1. Be kind. 2. No spam. 3. Have fun."
        } else {
            "Thanks! A moderator will read this soon."
        };
        let _ = ctx.reply_to(&message, answer);
    }

    fn on_command(&mut self, ctx: Context, command: CommandData) {
        if command.name != "dm-me" {
            return;
        }
        let member_id = ctx.member.member_id.clone();
        let answer = match ctx.dm(&member_id, "Hi! What can I help you with?") {
            Ok(_) => "Check your direct messages.",
            Err(_) => "I can't message you: you have direct messages from bots turned off.",
        };
        let _ = ctx.reply_ephemeral(answer);
    }
}

export_bot!(Welcome);
```

## The manifest

**TypeScript:**

```toml title="zaun-bot.toml"
app_id = "org.zaun.examples.ts-welcome-dm"
version = "0.1.0"
name = "Welcome"
description = "Greets new members by direct message and answers their replies."
permissions = ["VIEW_CHANNEL", "SEND_MESSAGES"]
# `members` for member joins (needs the `members` capability), `dms` for the DM's own
# events, `messages` for the replies (DMs to a bot always arrive whole).
events = ["members", "dms", "messages"]

[capabilities]
members = true
dms = true
```

**Rust:**

```toml title="zaun-bot.toml"
app_id = "org.zaun.examples.welcome-dm"
version = "0.1.0"
name = "Welcome"
description = "Greets new members by direct message and answers their replies."
permissions = ["VIEW_CHANNEL", "SEND_MESSAGES"]
# `members` for member.joined (needs the `members` capability), `dms` for the DM's own
# events, `messages` for the replies (DMs to a bot always arrive whole).
events = ["members", "dms", "messages"]

[capabilities]
members = true
dms = true
```

## How it works

- `events` asks for `members`, `dms` and `messages`; DMs to a bot always arrive whole, so it needs no `message_content`.
- The member-join handler opens the DM and sends the welcome in one call (`ctx.dm(..)`). A member who turned DMs from bots off makes the call fail with `dms_closed`; the bot just logs it.
- Message events in a DM are marked (`isDM` / `is_dm`), so the bot only answers there, never in public channels, and never itself.

## Run it

**TypeScript:**

```sh
git clone https://github.com/zaunchat/zaun-bot && cd zaun-bot/examples/ts/welcome-dm
npm install
zbot build && zbot pack --unsigned
zaun-host bot install --community <ID> *.zbot   # on a host with allow_unsigned = true
```

**Rust:**

```sh
git clone https://github.com/zaunchat/zaun-bot && cd zaun-bot/examples/rust/welcome-dm
zbot build && zbot pack --unsigned
zaun-host bot install --community <ID> *.zbot   # on a host with allow_unsigned = true
```
