Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
version: 2
updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: weekly
time: "11:00"
open-pull-requests-limit: 10
versioning-strategy: increase-if-necessary
groups:
patch-deps-updates-main:
update-types:
- "patch"
minor-deps-updates-main:
update-types:
- "minor"
major-deps-updates-main:
update-types:
- "major"
- package-ecosystem: github-actions
directory: "/"
schedule:
interval: weekly
time: "11:00"
open-pull-requests-limit: 10
groups:
patch-deps-updates:
update-types:
- "patch"
minor-deps-updates:
update-types:
- "minor"
major-deps-updates:
update-types:
- "major"
6 changes: 3 additions & 3 deletions .github/workflows/notify.yml
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,16 @@ jobs:
steps:

- name: Checkout repository
uses: actions/checkout@v3
uses: actions/checkout@v4
with:
# Persist credentials so git push works
persist-credentials: true
fetch-depth: 0

- name: Setup Node.js
uses: actions/setup-node@v3
uses: actions/setup-node@v4
with:
node-version: '22'
node-version-file: .nvmrc

- name: Install dependencies
run: npm ci
Expand Down
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v22.15.0
20 changes: 20 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
Copyright (c) OpenJS Foundation and other contributors

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
101 changes: 101 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# WDIO Discord Bot

A Node.js bot that bridges Stack Overflow and Discord for the WebdriverIO community.

## Features

- **Monitors Stack Overflow** for new questions tagged with a configurable tag (default: `webdriver-io`).
- **Posts new questions** as rich embeds to a specified Discord channel via webhook.
- **Prevents duplicate notifications** by persisting sent question IDs.
- **Configurable** via environment variables.
- **Easy to extend** for other tags or notification channels.

## Getting Started

### Prerequisites

- Node.js v22+ (for native fetch and ESM support)
- npm
- Access to a Discord server where you can create a webhook

### Installation

1. **Clone the repository:**
```sh
git clone <repo-url>
cd wdio-discord-bot
```

2. **Install dependencies:**
```sh
npm install
```

3. **Configure environment variables:**

Create a `.env` file in the project root with the following content:

```
DISCORD_WEBHOOK_ID=your_discord_webhook_id
DISCORD_WEBHOOK_TOKEN=your_discord_webhook_token
TAG_TO_MONITOR=webdriver-io
# Optional: STACKEXCHANGE_KEY=your_stackexchange_api_key
```

- `DISCORD_WEBHOOK_ID` and `DISCORD_WEBHOOK_TOKEN` are from your Discord channel webhook.
- `TAG_TO_MONITOR` is the Stack Overflow tag to monitor.
- `STACKEXCHANGE_KEY` is optional but recommended for higher API rate limits.

4. **Run the bot:**

- For development (with TypeScript):
```sh
npm run dev
```
- For production:
```sh
npm start
```

## How It Works

- On each run, the bot:
1. Loads the list of previously notified question IDs from `data/sentIds.json`.
2. Fetches the latest questions from Stack Overflow tagged with your configured tag.
3. Filters out questions already sent.
4. Formats and posts new questions to Discord as embeds.
5. Updates `sentIds.json` and auto-commits/pushes the file (if using git).

## Development Advice

- **TypeScript:** The project is written in TypeScript. Use `npm run dev` for live development.
- **Persistence:** Sent question IDs are stored in `data/sentIds.json`. To reset notifications, delete or clear this file.
- **Auto-commit:** Each time new questions are sent, the bot auto-commits and pushes the updated `sentIds.json`. Ensure your environment has git configured and permissions set.
- **Extending:** To monitor a different tag, change `TAG_TO_MONITOR` in your `.env`.
- **Formatting:** The embed includes a snippet of the question body, with code blocks formatted for Discord.
- **Error Handling:** If the bot fails to send a message or update sent IDs, errors are logged to the console.
- **API Limits:** For higher Stack Exchange API limits, set `STACKEXCHANGE_KEY` in your `.env`.

## Project Structure

```
src/
config/ # Environment variable validation
services/ # Stack Overflow, Discord, and persistence logic
utils/ # HTML formatting for Discord
index.ts # Entry point
data/
sentIds.json # Tracks sent question IDs
```

## Troubleshooting

- **No new questions:** If there are no new questions, the bot will log "No new questions."
- **Webhook errors:** Double-check your Discord webhook credentials.
- **Git errors:** Ensure your environment has git installed and configured for auto-commits.

## License

MIT

Feel free to further customize this README for your community or deployment environment!
9 changes: 4 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
{
"name": "wdio-discord-bot",
"author": "Rondleysg",
"license": "MIT",
"description": "",
"version": "1.0.0",
"main": "index.js",
"private": true,
"scripts": {
"build": "tsc",
"start": "npm run build && node dist/index.js",
"dev": "ts-node src/index.ts"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"@octokit/rest": "^21.1.1",
"discord.js": "^14.19.3",
Expand Down
29 changes: 13 additions & 16 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,20 @@
import { env } from './config/env';
import { fetchLatestQuestions } from './services/stackoverflow';
import { formatBody } from './utils/htmlFormatter';
import { sendQuestion } from './services/notifier';
import { loadSentIds, saveSentIds } from './services/persistence';

(async () => {
const sent = await loadSentIds();
const questions = await fetchLatestQuestions();
const newQs = questions.filter(q => !sent.has(q.question_id));
const sent = await loadSentIds();
const questions = await fetchLatestQuestions();
const newQs = questions.filter((q) => !sent.has(q.question_id));

for (const q of newQs.reverse()) {
const snippet = formatBody(q.body).split('\n').slice(0, 10).join('\n').substring(0, 1024);
await sendQuestion(q, snippet);
sent.add(q.question_id);
}
for (const q of newQs.reverse()) {
const snippet = formatBody(q.body).split('\n').slice(0, 10).join('\n').substring(0, 1024);
await sendQuestion(q, snippet);
sent.add(q.question_id);
}

if (newQs.length > 0) {
await saveSentIds(sent);
} else {
console.log('No new questions.');
}
})();
if (newQs.length > 0) {
await saveSentIds(sent);
} else {
console.log('No new questions.');
}
3 changes: 2 additions & 1 deletion src/services/notifier.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { WebhookClient, EmbedBuilder } from "discord.js";
import { env } from "../config/env";

import { Question } from "./stackoverflow";
import { env } from "../config/env";

const webhook = new WebhookClient({
id: env.DISCORD_WEBHOOK_ID,
Expand Down
30 changes: 19 additions & 11 deletions src/services/persistence.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,35 @@
import fs from 'fs/promises';
import { exec } from 'child_process';
import path from 'path';
import fs from 'node:fs/promises';
import cp from 'node:child_process';
import path from 'node:path';

const DATA_FILE = path.resolve(__dirname, '../../data/sentIds.json');

export async function loadSentIds(): Promise<Set<number>> {
try {
const raw = await fs.readFile(DATA_FILE, 'utf-8');
return new Set<number>(JSON.parse(raw));
} catch {
const isExisting = await fs.access(DATA_FILE).then(() => true).catch(() => false);
if (!isExisting) {
await fs.writeFile(DATA_FILE, JSON.stringify([], null, 2));
return new Set();
}

const raw = await fs.readFile(DATA_FILE, 'utf-8');
return new Set<number>(JSON.parse(raw));
}

export async function saveSentIds(ids: Set<number>) {
const arr = Array.from(ids);
await fs.writeFile(DATA_FILE, JSON.stringify(arr, null, 2));

// Auto‑commit and push
exec(
return new Promise<void>((resolve, reject) => cp.exec(
`git add ${DATA_FILE} && git commit -m "chore: update sent question IDs" && git push`,
(err, stdout, stderr) => {
if (err) console.error('Git commit failed:', stderr, stdout);
else console.log('Sent IDs file committed.');
if (err) {
console.error('Git commit failed:', stderr, stdout);
return reject(err);
}

console.log('Sent IDs file committed.');
resolve();
}
);
));
}
5 changes: 4 additions & 1 deletion src/services/stackoverflow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ export async function fetchLatestQuestions(): Promise<Question[]> {
pagesize: "10",
filter: "withbody",
});
if (env.STACKEXCHANGE_KEY) params.append("key", env.STACKEXCHANGE_KEY);

if (env.STACKEXCHANGE_KEY) {
params.append("key", env.STACKEXCHANGE_KEY)
};

const url = `https://api.stackexchange.com/2.3/questions?${params}`;
const res = await fetch(url);
Expand Down
6 changes: 3 additions & 3 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "commonjs",
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"strict": true,
"esModuleInterop": true,
"outDir": "dist",
"rootDir": "src",
"resolveJsonModule": true,
"skipLibCheck": true
}
}