# Telegram bot setup (Vercel + channel)

This app sends visitor alerts and **inline buttons** (redirects, hire decisions, login steps) to Telegram.  
For buttons and commands to work, Telegram must call **your deployed Vercel URL** — not `localhost`.

---

## How it works

| What | Where it runs |
|------|----------------|
| Visitor site, hire gate, login capture | Your Vercel app |
| Outgoing messages (alerts, hire check) | Vercel → Telegram API |
| **Button clicks & `/sessions`** | Telegram → **Vercel webhook** (`/api/telegram/webhook`) |

If you run `npm run dev` locally but the webhook still points at an old deployment (or another project), button taps show **“Unknown action”** even though messages arrive in the channel.

---

## 1. Create the bot

1. Open [@BotFather](https://t.me/BotFather) in Telegram.
2. Send `/newbot`, follow the prompts, save the **bot token** (looks like `123456789:AAH...`).

---

## 2. Use a **channel** (recommended)

This project is built for a **private admin channel**, not DMs with the bot.

### Create the channel

1. Telegram → **New Channel** → name it (e.g. `Red Bull Careers Admin`).
2. Set it **Private** if you only want invited admins.

### Add the bot as channel admin

1. Open the channel → **Manage channel** → **Administrators**.
2. **Add administrator** → search for your bot.
3. Enable at least:
   - **Post messages**
   - **Edit messages of others** (so the bot can update messages after you tap a button)

Without admin rights, the bot can post alerts but **inline buttons may not work reliably**.

### Get the channel chat ID

`TELEGRAM_CHAT_ID` must be the **channel id**, not your personal user id.

**Option A — @RawDataBot**

1. Forward any message from the channel to [@RawDataBot](https://t.me/RawDataBot).
2. Copy `"chat":{"id":-100xxxxxxxxxx}` → that number is `TELEGRAM_CHAT_ID`.

**Option B — post as channel**

1. Post `/help` in the channel (as a channel admin).
2. If the bot replies, your id is already correct in env.

Channel ids usually look like `-1001234567890`.

---

## 3. Environment variables on Vercel

In **Vercel → Project → Settings → Environment Variables**, add:

| Variable | Required | Example |
|----------|----------|---------|
| `TELEGRAM_BOT_TOKEN` | Yes | `123456789:AAH...` from BotFather |
| `TELEGRAM_CHAT_ID` | Yes | `-1001234567890` (channel id) |
| `NEXT_PUBLIC_APP_URL` | Yes | `https://your-app.vercel.app` (no trailing slash) |
| `NEXT_PUBLIC_SUPABASE_URL` | Yes | Supabase project URL |
| `NEXT_PUBLIC_SUPABASE_ANON_KEY` | Yes | Supabase anon key |
| `SUPABASE_SERVICE_ROLE_KEY` | Yes* | For server-side session updates |
| `TELEGRAM_ADMIN_USER_ID` | Optional | Your Telegram user id — allows callbacks if chat id mismatch |

\* Use whatever Supabase keys your project already expects.

**Do not swap** token and chat id. Token contains a `:`; chat id is numeric only.

Redeploy after changing env vars.

---

## 4. Deploy on Vercel

1. Push this repo to GitHub (or import into Vercel).
2. Deploy — you need a stable **HTTPS** URL (Vercel provides this).
3. Set `NEXT_PUBLIC_APP_URL` to that URL.

Telegram webhooks **require HTTPS**. Local `http://localhost:3000` cannot receive webhooks unless you use a tunnel (ngrok, etc.).

---

## 5. Register the webhook (after deploy)

**If you see `"url": ""` and commands do nothing, the webhook was never registered.**

Open this URL **in your browser** on the **live Vercel domain** (not localhost):

```
https://YOUR-APP.vercel.app/api/telegram/set-webhook?register=1
```

You should get JSON like:

```json
{
  "ok": true,
  "webhookUrl": "https://YOUR-APP.vercel.app/api/telegram/webhook",
  "hint": "Webhook registered. Post /help in your Telegram channel to test."
}
```

Then check status:

```
https://YOUR-APP.vercel.app/api/telegram/set-webhook
```

`webhook.url` must **not** be empty.

Alternative (curl):

```bash
curl -X POST "https://YOUR-APP.vercel.app/api/telegram/set-webhook"
```

If you had many failed deliveries, clear the queue when registering:

```
https://YOUR-APP.vercel.app/api/telegram/set-webhook?register=1&drop_pending=1
```

### Verify deployment version

Open:

```
https://YOUR-VERCEL-DOMAIN.vercel.app/api/telegram/webhook
```

You should see JSON like:

```json
{
  "ok": true,
  "v": "channel-cmd-4-hire",
  "hireCallbacks": ["hy1", "hy0", "hyr"]
}
```

If `"v"` is older (e.g. `channel-cmd-3`) or `hireCallbacks` is missing, redeploy the latest code and register the webhook again.

---

## 6. Test in the channel

All commands and buttons must be used **in the configured channel** (or group matching `TELEGRAM_CHAT_ID`).

1. Post **`/help`** in the channel → bot should reply with the command list.
2. Open the site on Vercel, start a session → post **`/sessions`** → active visitor with redirect buttons.
3. **Hire gate** (home page without invite link):
   - Visitor submits email → channel gets **“Hire check · email gate”** with **Hired / Not hired**.
   - Tap **Hired** → visitor sees “We found you” and gets `/invite/...`.
   - Tap **Not hired** → visitor sees 404 / application not found.

### Connection smoke test

```
GET https://YOUR-VERCEL-DOMAIN.vercel.app/api/telegram
```

Sends a test message to the channel if env vars are correct.

---

## 7. Commands reference

Post these **in the channel**:

| Command | Action |
|---------|--------|
| `/help` | Show admin guide |
| `/sessions` | List active visitors + inline redirect buttons |
| `/panel` | Web admin link + session picker |

Login/2FA alerts also include inline buttons for the same redirect menu.

---

## 8. Local development vs Vercel

| Scenario | Telegram buttons |
|----------|-------------------|
| `npm run dev` on localhost, webhook on Vercel | **Works** if webhook URL matches the Vercel project you deployed |
| `npm run dev`, webhook still on old domain | **Broken** — update webhook or deploy latest code to that domain |
| Everything on Vercel, webhook registered | **Works** |

**Rule:** The codebase that handles `/api/telegram/webhook` on the webhook URL must include hire + redirect handlers.  
Deploy **this project** to Vercel and register the webhook to **that** deployment.

Optional local testing with a tunnel:

1. Run `ngrok http 3000`
2. `POST https://YOUR-NGROK.ngrok.io/api/telegram/set-webhook?url=https://YOUR-NGROK.ngrok.io/api/telegram/webhook`
3. Remember to set webhook back to Vercel when done.

---

## 9. Troubleshooting

### `"url": ""` and `pending_update_count` > 0

Telegram has **no webhook URL**. Outgoing alerts can still work, but **commands and buttons never reach your app**.

**Fix:** open on your Vercel site:

`/api/telegram/set-webhook?register=1`

### “Unknown action” on button tap

- Webhook domain is running **old code** → redeploy, verify `"v": "channel-cmd-4-hire"`.
- Webhook points at a **different project** than the one sending hire messages.
- Test with a **new** hire-check message after deploy (old messages may have stale buttons).

### “Unauthorized chat”

- `TELEGRAM_CHAT_ID` does not match the channel where you clicked.
- Fix the id, redeploy, use the correct channel.

### Bot sends messages but ignores `/help`

- Commands must be posted **in the channel**, not in a private chat with the bot (unless that chat id is `TELEGRAM_CHAT_ID`).
- Bot must be **channel admin**.

### Visitor not redirecting after you tap a button

- Supabase **Realtime** enabled on `user_sessions` (for instant updates).
- Same Supabase project in Vercel env as the visitor site.
- Visitor tab still open on the site.

### `TELEGRAM_BOT_TOKEN` / `TELEGRAM_CHAT_ID` errors in logs

- Token format: `digits:letters` from BotFather.
- Chat id: numeric only, usually negative for channels (`-100...`).

---

## 10. Checklist

- [ ] Bot created in BotFather  
- [ ] Private admin **channel** created  
- [ ] Bot added as **channel administrator**  
- [ ] `TELEGRAM_BOT_TOKEN` and `TELEGRAM_CHAT_ID` set on Vercel  
- [ ] `NEXT_PUBLIC_APP_URL` set to Vercel URL  
- [ ] Project deployed on Vercel  
- [ ] Webhook registered via `/api/telegram/set-webhook`  
- [ ] `GET /api/telegram/webhook` shows `channel-cmd-4-hire`  
- [ ] `/help` works when posted **in the channel**  
- [ ] Hire **Hired / Not hired** tested with a fresh email submit  

---

## Summary

**Run the app on Vercel, register the webhook to that URL, and operate the bot from your admin channel.**  
Local dev can send Telegram messages, but button callbacks always go to whatever URL is registered in the webhook — keep that URL on your latest Vercel deployment.
