discord-botdiscord-client.js22 matches
45/**
6* Discord client that fetches direct messages between users
7*/
8export class DiscordClient {
2829/**
30* Fetch DMs between the user and their spouse
31* @returns {Promise<Array>} - Array of message objects
32*/
33async fetchDMsBetweenUsers() {
34try {
35const myUserId = process.env.DISCORD_USER_ID;
4142// Get the DM channel with spouse
43const spouse = await this.client.users.fetch(spouseUserId);
44const dmChannel = await spouse.createDM();
45
46// Fetch messages from the DM channel
47const messages = [];
48let lastId;
49let keepFetching = true;
50
51// Fetch messages in batches of 100 (Discord API limit)
52while (keepFetching) {
53const options = { limit: 100 };
54if (lastId) {
56}
57
58const fetchedMessages = await dmChannel.messages.fetch(options);
59
60if (fetchedMessages.size === 0) {
61keepFetching = false;
62break;
63}
64
65// Process and store fetched messages
66fetchedMessages.forEach(msg => {
67// Only store messages from the two users we care about
68if (msg.author.id === myUserId || msg.author.id === spouseUserId) {
79
80// Get the ID of the last message for pagination
81lastId = fetchedMessages.last().id;
82
83// If we got fewer messages than requested, we've reached the end
84if (fetchedMessages.size < 100) {
85keepFetching = false;
86}
87}
88
89console.log(`Fetched ${messages.length} messages`);
90
91// Save messages to database
94return messages;
95} catch (error) {
96console.error('Error fetching DMs:', error);
97throw error;
98}
108109/**
110* Function to run the message fetching process
111*/
112export async function fetchAndStoreDMs() {
113const client = new DiscordClient();
114try {
115await client.login();
116await client.fetchDMsBetweenUsers();
117} catch (error) {
118console.error('Error in fetch and store process:', error);
119} finally {
120client.disconnect();
discord-botinteractions-endpoint.js2 matches
140});
141} catch (error) {
142console.error('Error fetching categories:', error);
143return res.json({
144type: 4,
145data: { content: 'Sorry, I encountered an error fetching categories.' }
146});
147}
discord-botpackage.json1 match
8"start": "node index.js",
9"dev": "node index.js",
10"fetch": "node val-town-cron.js",
11"register": "node discord-commands.js",
12"interactions": "node interactions-endpoint.js",
discord-botREADME.md4 matches
10- **Furniture Focus**: Special features for tracking furniture links and discussions
11- **Val.town Integration**: Runs on Val.town for easy deployment and scheduling
12- **Periodic Updates**: Automatically fetches new messages on a schedule
1314## Use Cases
58```
59606. Test the DM fetching process
61```
62node val-town-cron.js
84- Add the same environment variables from your `.env` file
85865. Set up a scheduled task on Val.town for periodic DM fetching
87- Create a new scheduled task using the Val.town dashboard
88- Use the `discordDMBotCron` function
108109- `GET /health`: Health check endpoint
110- `POST /api/fetch-dms`: Manually trigger DM fetching
111- `POST /api/process-links`: Manually trigger link processing
112- `POST /api/query`: Submit a query about your message history
discord-bot.cursorrules3 matches
239
240// Inject data to avoid extra round-trips
241const initialData = await fetchInitialData();
242const dataScript = `<script>
243window.__INITIAL_DATA__ = ${JSON.stringify(initialData)};
2862875. **API Design:**
288- `fetch` handler is the entry point for HTTP vals
289- Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`
290291
discord-botindex.js7 matches
1import { initializeDatabase } from './database.js';
2import { fetchAndStoreDMs } from './discord-client.js';
3import { batchProcessLinks } from './link-analyzer.js';
4import express from 'express';
20});
2122// Manual trigger for fetching DMs
23app.post('/api/fetch-dms', async (req, res) => {
24try {
25console.log('Manually triggering DM fetch...');
26await fetchAndStoreDMs();
27res.json({ success: true, message: 'DM fetch completed successfully' });
28} catch (error) {
29console.error('Error fetching DMs:', error);
30res.status(500).json({ success: false, error: error.message });
31}
discord-botlink-analyzer.js1 match
119export async function extractLinkMetadata(url) {
120try {
121// In a production system, you'd want to actually fetch the page content
122// For simplicity, we'll make an educated guess based on the URL
123
discord-botREADME.md4 matches
15- **AI Integration**: Leverages Anthropic's Claude API for analysis
16- **Discord Integration**:
17- Bot token for fetching messages
18- Slash commands for user interactions
19- Webhook endpoint for Discord interactions
502. Copy the contents of the backend directory
513. Set up the required environment variables
524. Create a cron schedule for periodically fetching messages and processing links
5354## Usage
58- `GET /health`: Check if the service is running
59- `POST /api/interactions`: Discord interactions endpoint
60- `POST /api/fetch-dms`: Manually trigger DM fetching
61- `POST /api/process-links`: Manually trigger link processing
62- `POST /api/query`: Process a query about your messages
63- `POST /api/commands/search`: Endpoint for search commands
64- `POST /api/register-commands`: Register Discord slash commands
65- `GET /api/cron/fetch-dms`: Cron endpoint for fetching DMs
66- `GET /api/cron/process-links`: Cron endpoint for processing links
67
discord-botlink-analyzer.ts1 match
142export async function extractLinkMetadata(url: string): Promise<MetadataResult> {
143try {
144// In a production system, you'd want to actually fetch the page content
145// For simplicity, we'll make an educated guess based on the URL
146
discord-botindex.ts18 matches
3import { cors } from "https://esm.sh/@hono/cors@0.0.8";
4import { initializeDatabase } from "./database.ts";
5import { fetchAndStoreDMs } from "./discord-client.ts";
6import { handleDiscordInteractionRequest } from "./discord-interactions.ts";
7import { batchProcessLinks } from "./link-analyzer.ts";
85});
8687// Manual trigger for fetching DMs
88app.post("/api/fetch-dms", async c => {
89try {
90log("Manually triggering DM fetch...", "info");
91const messages = await fetchAndStoreDMs();
92return c.json({
93success: true,
94message: "DM fetch completed successfully",
95count: messages.length,
96timestamp: new Date().toISOString()
97});
98} catch (error) {
99log(`Error fetching DMs: ${error instanceof Error ? error.message : String(error)}`, "error");
100return c.json({
101success: false,
247248/**
249* Handles the scheduled DM fetch cron job
250*/
251export async function cronFetchDMs() {
252try {
253log("Running scheduled DM fetch...", "info");
254await initializeServices(); // Ensure services are initialized
255const messages = await fetchAndStoreDMs();
256
257log(`Scheduled DM fetch completed successfully. Fetched ${messages.length} messages.`, "info");
258return {
259success: true,
260message: "Scheduled DM fetch completed successfully",
261count: messages.length,
262timestamp: new Date().toISOString()
263};
264} catch (error) {
265log(`Error in DM fetch cron job: ${error instanceof Error ? error.message : String(error)}`, "error");
266return {
267success: false,
297298// Expose cron endpoints via HTTP as well
299app.get("/api/cron/fetch-dms", async c => {
300const result = await cronFetchDMs();
301return c.json(result, result.success ? 200 : 500);
302});
313});
314315// Export the fetch handler for Val.town HTTP vals
316export default app.fetch;