Skip to content

Commit

Permalink
wip 2: even more in progress
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisdickinson committed Jul 12, 2024
1 parent 137ec0a commit 74d99d4
Show file tree
Hide file tree
Showing 11 changed files with 236 additions and 86 deletions.
3 changes: 2 additions & 1 deletion LOUDBOT/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@ declare module "main" {
}
declare module "extism:host" {
interface user {
sendMessage(ptr: I64): I64;
react(ptr: I64): I64;
request(ptr: I64): I64;
sendMessage(ptr: I64): I64;
watchMessage(ptr: I64): I64;
}
}
4 changes: 2 additions & 2 deletions LOUDBOT/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import {
IncomingEvent,
OutgoingMessage,
OutgoingReaction,
Result,
IncomingReaction,
OutgoingRequest,
OutgoingMessage,
} from "./pdk";

import * as main from "./main";
Expand Down
16 changes: 14 additions & 2 deletions LOUDBOT/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,18 @@ import { sendMessage, react, request } from "./pdk";
* @param input An incoming event
*/
export function handleImpl(input: IncomingEvent) {
sendMessage({} as any)
console.log('received message ' + JSON.stringify(input))
if (input.message) {
react({ messageId: input.message.id, channel: input.channel, with: '🎤' } as any)
const result = sendMessage({
message: 'WOW TURN IT DOWN OKAY'
})

if (result.id) {
react({ messageId: result.id, channel: input.channel, with: '🎤' } as any)
} else {
console.log(JSON.stringify(result))
}
} else {
console.log('received message ' + JSON.stringify(input))
}
}
39 changes: 17 additions & 22 deletions LOUDBOT/src/pdk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,6 @@ export class IncomingEvent {
*/
// @ts-expect-error TS2564
channel: string;
/**
* The server the message was received in
*/
// @ts-expect-error TS2564
guild: string;
}

/**
Expand Down Expand Up @@ -113,13 +108,11 @@ export class IncomingMessage {
/**
* The message text
*/
// @ts-expect-error TS2564
message: string;
content?: string;
/**
* The author of the message
*/
// @ts-expect-error TS2564
author: string;
author: any;
}

/**
Expand All @@ -134,13 +127,7 @@ export class OutgoingMessage {
/**
* The channel the message was received in
*/
// @ts-expect-error TS2564
channel: string;
/**
* The server the message was received in
*/
// @ts-expect-error TS2564
guild: string;
channel?: string;
}

/**
Expand All @@ -157,26 +144,34 @@ export class Result {
errorCode?: number;
}

export function sendMessage(input: OutgoingMessage): Result {
export function react(input: OutgoingReaction): Result {
const mem = Memory.fromJsonObject(input as any);

const ptr = hostFunctions.sendMessage(mem.offset);
const ptr = hostFunctions.react(mem.offset);

return Memory.find(ptr).readJsonObject();
}

export function react(input: IncomingReaction): Result {
export function request(input: OutgoingRequest): Result {
const mem = Memory.fromJsonObject(input as any);

const ptr = hostFunctions.react(mem.offset);
const ptr = hostFunctions.request(mem.offset);

return Memory.find(ptr).readJsonObject();
}

export function request(input: OutgoingRequest): Result {
export function sendMessage(input: OutgoingMessage): Result {
const mem = Memory.fromJsonObject(input as any);

const ptr = hostFunctions.request(mem.offset);
const ptr = hostFunctions.sendMessage(mem.offset);

return Memory.find(ptr).readJsonObject();
}

export function watchMessage(input: string): Result {
const mem = Memory.fromString(input);

const ptr = hostFunctions.watchMessage(mem.offset);

return Memory.find(ptr).readJsonObject();
}
4 changes: 2 additions & 2 deletions migrations/0005-interests.sql
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
create table if not exists "handlers" (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references "users" ("id") on delete cascade,
guild text not null,
user_id uuid not null references "users" ("id") on delete cascade,
plugin_name text not null default 'default',
allowed_channels jsonb not null default '[]'::jsonb,
allowed_hosts jsonb not null default '[]'::jsonb,
commands jsonb not null default '[]'::jsonb,

ratelimiting_max_tokens int,
ratelimiting_current_tokens int,
Expand All @@ -14,6 +13,7 @@ create table if not exists "handlers" (
created_at timestamp(3) not null default now(),
updated_at timestamp(3) not null default now()
);
create unique index "handlers_uniq" on "handlers" ("guild", "user_id", "plugin_name");

create table if not exists "interest_message_content" (
id uuid primary key default gen_random_uuid(),
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 4 additions & 10 deletions plugin.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,14 @@ imports:
input:
type: string
description: the id of a message to watch
contentType: text/plain
contentType: text/plain; charset=UTF-8
output:
$ref: "#/schemas/Result"

schemas:
- name: IncomingEvent
description: An incoming event
required: ['channel', 'guild']
required: ['channel']
contentType: application/json
properties:
- name: message
Expand All @@ -50,9 +50,6 @@ schemas:
- name: channel
type: string
description: The channel the message was received in
- name: guild
type: string
description: The server the message was received in

- name: OutgoingRequest
description: An HTTP request
Expand All @@ -76,7 +73,7 @@ schemas:

- name: OutgoingReaction
description: send a reaction
required: ['messageId', 'emoji']
required: ['messageId', 'channel', 'emoji']
contentType: application/json
properties:
- name: messageId
Expand Down Expand Up @@ -138,7 +135,7 @@ schemas:

- name: OutgoingMessage
description: An outgoing message
required: ['message', 'channel', 'guild']
required: ['message']
contentType: application/json
properties:
- name: message
Expand All @@ -147,9 +144,6 @@ schemas:
- name: channel
type: string
description: The channel the message was received in
- name: guild
type: string
description: The server the message was received in

- name: Result
description: a result
Expand Down
59 changes: 30 additions & 29 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,20 @@
import { ChannelType, Client, CommandInteraction, GatewayIntentBits, REST, Routes } from 'discord.js';
import safe from 'safe-regex';

import { DISCORD_BOT_TOKEN, DISCORD_BOT_CLIENT_ID, DISCORD_GUILD_FILTER, DISCORD_CHANNEL_FILTER } from './config';
import { DISCORD_BOT_TOKEN, DISCORD_BOT_CLIENT_ID, DISCORD_GUILD_FILTER } from './config';
import { findUserByUsername, getXtpData, registerUser } from './domain/users';
import { executeHandlers, fetchByContentInterest } from './domain/interests';
import { registerMessageHandler } from './domain/message-handlers';
import { executeHandlers, fetchByContentInterest, registerMessageContentInterest } from './domain/interests';
import { getLogger } from './logger';

export async function startDiscordClient() {
type Logger = ReturnType<typeof getLogger>

export async function startDiscordClient(logger: Logger) {
if (!DISCORD_BOT_TOKEN) {
return;
}

const rest = new REST({ version: '9' }).setToken(DISCORD_BOT_TOKEN);
await refreshCommands(rest);
await refreshCommands(rest, logger);

const client = new Client({
intents: [
Expand All @@ -25,7 +27,7 @@ export async function startDiscordClient() {
});

client.on('ready', () => {
console.log(`Logged in as ${client.user!.tag}!`);
logger.info(`Logged in as ${client.user!.tag}!`);
});

client.on('messageCreate', async message => {
Expand All @@ -36,31 +38,26 @@ export async function startDiscordClient() {
const guild = message.guild || { name: "", id: "" };

if (message.channel.type !== ChannelType.GuildText) {
console.log(`skipping message; channel type was not GuildText`)
logger.info(`skipping message; channel type was not GuildText`)
return
}

if (DISCORD_GUILD_FILTER.size && !DISCORD_GUILD_FILTER.has(guild.name)) {
console.log(`skipping message; not in guild filter (got="${guild.name}"; valid="${[...DISCORD_GUILD_FILTER].join('", "')}")`)
logger.info(`skipping message; not in guild filter (got="${guild.name}"; valid="${[...DISCORD_GUILD_FILTER].join('", "')}")`)
return
}

if (DISCORD_CHANNEL_FILTER.size && !DISCORD_CHANNEL_FILTER.has(message.channel.name)) {
console.log(`skipping message; not in channel filter (guild="${guild.name}"; channel="${message.channel.name}")`)
return
}

console.log(`Incoming message in "${guild.name}" "#${message.channel.name}" (${guild.id}): `, message.content);
logger.info(`Incoming message in "${guild.name}" "#${message.channel.name}" (${guild.id}): `, message.content);
const handlers = await fetchByContentInterest({ guild: guild.id, channel: message.channel.name, content: message.content });
await executeHandlers(client, handlers, {
channel: message.channel.name,
guild: guild.name,
guild: guild.id,
message: {
id: message.id,
content: message.content,
author: message.author
}
}, {})
}, {}, message.channel.name)
});

/*
Expand Down Expand Up @@ -129,8 +126,10 @@ export async function startDiscordClient() {
await handleRegisterCommand(command);

break;

case 'subscribe':
await handleSubscribeCommand(command);
case 'listen':
await handleListenCommand(command);
break;
}
})
Expand Down Expand Up @@ -182,7 +181,7 @@ async function handleRegisterCommand(command: CommandInteraction) {
});
}

async function refreshCommands(rest: REST) {
async function refreshCommands(rest: REST, logger: Logger) {
if (!DISCORD_BOT_CLIENT_ID) {
return;
}
Expand All @@ -209,8 +208,8 @@ async function refreshCommands(rest: REST) {
description: 'Register your account with the bot'
},
{
name: 'subscribe',
description: 'Subscribes to messages',
name: 'listen',
description: 'Listen for message content',
options: [
{
name: 'regex',
Expand All @@ -229,19 +228,19 @@ async function refreshCommands(rest: REST) {
];

try {
console.log('Started refreshing application (/) commands.');
logger.info('Started refreshing application (/) commands.');

await rest.put(
Routes.applicationCommands(DISCORD_BOT_CLIENT_ID),
{ body: commands },
);

console.log('Successfully reloaded application (/) commands.');
logger.info('Successfully reloaded application (/) commands.');
} catch (error) {
console.error(error);
logger.error(error);
}
}
async function handleSubscribeCommand(command: CommandInteraction) {
async function handleListenCommand(command: CommandInteraction) {
const regex = command.options.get('regex')?.value as string;
const plugin = command.options.get('plugin')?.value as string;
const guild = command.guildId;
Expand Down Expand Up @@ -279,15 +278,17 @@ async function handleSubscribeCommand(command: CommandInteraction) {
return;
}

await registerMessageHandler({
plugin_name: plugin,
console.log(command.channel)
await registerMessageContentInterest({
pluginName: plugin,
regex: regex,
user_id: dbUser.id,
guild: guild,
userId: dbUser.id,
guild,
isAdmin: false
});

await command.reply({
content: `Subscribed to messages matching \`${regex}\` with plugin \`${plugin}\``,
content: `Subscribed for messages matching \`${regex}\` with plugin \`${plugin}\``,
ephemeral: true,
});
}
Expand Down
Loading

0 comments on commit 74d99d4

Please sign in to comment.