mirror of
https://github.com/PHIDIAS0303/ClusterChatSync.git
synced 2026-11-11 15:14:52 +09:00
1.0.6 RC3
This commit is contained in:
1 parent
bd7d027702
commit
6a51d36d14
4 files changed
+162
-117
No files matched your search
@@ -1,5 +1,13 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## v1.0.6
|
||||||
|
|
||||||
|
- Bidirectional
|
||||||
|
|
||||||
|
## v1.0.5
|
||||||
|
|
||||||
|
- Action and player count
|
||||||
|
|
||||||
## v1.0.3
|
## v1.0.3
|
||||||
|
|
||||||
- Changed to TS
|
- Changed to TS
|
||||||
|
|||||||
+62
-54
@@ -6,14 +6,20 @@ import {ChatEvent, ChatFromDiscordEvent} from './index.js';
|
|||||||
/* Controller-side halves of the chat relay.
|
/* Controller-side halves of the chat relay.
|
||||||
* Outbound (Factorio -> Discord) talks to the REST API directly: no socket, no intents.
|
* Outbound (Factorio -> Discord) talks to the REST API directly: no socket, no intents.
|
||||||
* Inbound (Discord -> Factorio) needs messageCreate, so it owns a real gateway Client.
|
* Inbound (Discord -> Factorio) needs messageCreate, so it owns a real gateway Client.
|
||||||
* Both come from the same token and are rebuilt by the same enqueue chain, so rotating
|
* Both are built from the same token and rebuilt by the same enqueue chain, so a token
|
||||||
* the token can't leave one half running on the old credential.
|
* rotation can't leave one half running on the old credential.
|
||||||
|
*
|
||||||
|
* Both directions read the single `discord_channel_mapping` field (instance name ->
|
||||||
|
* channel ID). The reverse lookup is built by inverting it, so the two directions can
|
||||||
|
* never disagree about which channel belongs to which instance.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Discord's hard limit is 2000; keep headroom for future decoration.
|
// Discord's hard limit is 2000; keep headroom for future decoration.
|
||||||
const MAX_MESSAGE_LENGTH = 1950;
|
const MAX_MESSAGE_LENGTH = 1950;
|
||||||
|
|
||||||
// Only break on a word boundary if it gets us at least this far into the window.
|
// Only break on a word boundary if it gets us at least this far into the window.
|
||||||
const MIN_WORD_BREAK_FILL = 0.5;
|
const MIN_WORD_BREAK_FILL = 0.5;
|
||||||
|
|
||||||
const ERROR_UNKNOWN_CHANNEL = 10003;
|
const ERROR_UNKNOWN_CHANNEL = 10003;
|
||||||
|
|
||||||
// Factorio chat scroll is a shared, scarce resource; be stricter than Discord is.
|
// Factorio chat scroll is a shared, scarce resource; be stricter than Discord is.
|
||||||
@@ -36,7 +42,7 @@ function splitMessage(text: string, limit: number): string[] {
|
|||||||
return text.length === 0 ? [] : [text];
|
return text.length === 0 ? [] : [text];
|
||||||
}
|
}
|
||||||
|
|
||||||
// Array.from, not slice, so we never cut an emoji's surrogate pair in half.
|
// Array.from, not slice, so we never cut a surrogate pair in half.
|
||||||
const chars = Array.from(text);
|
const chars = Array.from(text);
|
||||||
const chunks: string[] = [];
|
const chunks: string[] = [];
|
||||||
let offset = 0;
|
let offset = 0;
|
||||||
@@ -91,14 +97,15 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
let client: Client | null = null;
|
let client: Client | null = null;
|
||||||
let shuttingDown = false;
|
let shuttingDown = false;
|
||||||
|
|
||||||
// Log-once guards, cleared whenever the config field that feeds them changes.
|
// Log-once guards. A channel that is unmapped or unusable gets hit once per chat
|
||||||
|
// line, which is how a typo in the config turns into a 10k-line log file.
|
||||||
const warnedNoMapping = new Set<string>();
|
const warnedNoMapping = new Set<string>();
|
||||||
const warnedBadChannel = new Set<string>();
|
const warnedBadChannel = new Set<string>();
|
||||||
const warnedAmbiguous = new Set<string>();
|
const warnedAmbiguous = new Set<string>();
|
||||||
const warnedNoInstance = new Set<string>();
|
const warnedNoInstance = new Set<string>();
|
||||||
const warnedSendFail = new Set<string>();
|
const warnedSendFail = new Set<string>();
|
||||||
|
|
||||||
// Inbound channel -> instance names, rebuilt from config rather than inverted lazily.
|
// Inverted view of discord_channel_mapping, rebuilt rather than mutated in place.
|
||||||
let channelToInstances = new Map<string, string[]>();
|
let channelToInstances = new Map<string, string[]>();
|
||||||
const buckets = new Map<string, Bucket>();
|
const buckets = new Map<string, Bucket>();
|
||||||
|
|
||||||
@@ -113,16 +120,20 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
|
|
||||||
const getToken = () => controller.config.get('chat_relay.discord_bot_token') as string | undefined;
|
const getToken = () => controller.config.get('chat_relay.discord_bot_token') as string | undefined;
|
||||||
|
|
||||||
// ---------------------------------------------------------------- outbound
|
// --------------------------------------------------------------- outbound
|
||||||
|
|
||||||
const getChannelId = (instanceName: string): string | null => {
|
const getChannelId = (instanceName: string): string | null => {
|
||||||
const mapping = controller.config.get('chat_relay.discord_channel_mapping') as Record<string, string> | undefined;
|
const mapping = controller.config.get('chat_relay.discord_channel_mapping') as
|
||||||
|
Record<string, string> | undefined;
|
||||||
const channelId = mapping?.[instanceName];
|
const channelId = mapping?.[instanceName];
|
||||||
|
|
||||||
if (!channelId) {
|
if (!channelId) {
|
||||||
if (!warnedNoMapping.has(instanceName)) {
|
if (!warnedNoMapping.has(instanceName)) {
|
||||||
warnedNoMapping.add(instanceName);
|
warnedNoMapping.add(instanceName);
|
||||||
logger.warn(`[Chat Relay] No Discord channel mapped for instance ${instanceName}; dropping its messages.`);
|
logger.warn(
|
||||||
|
`[Chat Relay] No Discord channel mapped for instance ${instanceName};`
|
||||||
|
+ ' dropping its messages.',
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return null;
|
return null;
|
||||||
@@ -135,21 +146,25 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
if (shuttingDown) return;
|
if (shuttingDown) return;
|
||||||
|
|
||||||
const discord = rest;
|
const discord = rest;
|
||||||
// not configured, or the token was rejected; connect() logged it
|
// Not configured, or the token was rejected. connect() already logged it.
|
||||||
if (!discord) return;
|
if (!discord) return;
|
||||||
|
|
||||||
const channelId = getChannelId(instanceName);
|
const channelId = getChannelId(instanceName);
|
||||||
if (!channelId) return;
|
if (!channelId) return;
|
||||||
|
|
||||||
|
// Read the flag once, so it can't flip between chunks of one message.
|
||||||
let content = message;
|
let content = message;
|
||||||
if (controller.config.get('chat_relay.datetime_on_message')) {
|
if (controller.config.get('chat_relay.datetime_on_message')) {
|
||||||
content = `${datetime} ${content}`;
|
content = `${datetime} ${content}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// trim() here also means an empty chat line produces zero chunks rather than
|
||||||
|
// a 50006 'cannot send an empty message' from Discord.
|
||||||
const chunks = splitMessage(content.trim(), MAX_MESSAGE_LENGTH);
|
const chunks = splitMessage(content.trim(), MAX_MESSAGE_LENGTH);
|
||||||
|
|
||||||
for (const chunk of chunks) {
|
for (const chunk of chunks) {
|
||||||
try {
|
try {
|
||||||
|
// discord.js REST handles rate limits (429) and retries for us.
|
||||||
await discord.post(Routes.channelMessages(channelId), {
|
await discord.post(Routes.channelMessages(channelId), {
|
||||||
body: {content: chunk, allowedMentions: {parse: []}},
|
body: {content: chunk, allowedMentions: {parse: []}},
|
||||||
});
|
});
|
||||||
@@ -166,20 +181,24 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
logger.error(`[Chat Relay] Discord send failed for ${instanceName}:\n${stackOf(err)}`);
|
logger.error(`[Chat Relay] Discord send failed for ${instanceName}:\n${stackOf(err)}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Don't keep hammering a channel that just rejected us.
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ----------------------------------------------------------------- inbound
|
// ---------------------------------------------------------------- inbound
|
||||||
|
|
||||||
const rebuildInboundMap = () => {
|
const rebuildInboundMap = () => {
|
||||||
const mapping = controller.config.get('chat_relay.discord_to_factorio_channel_mapping') as
|
const mapping = controller.config.get('chat_relay.discord_channel_mapping') as
|
||||||
Record<string, string> | undefined;
|
Record<string, string> | undefined;
|
||||||
|
|
||||||
const next = new Map<string, string[]>();
|
const next = new Map<string, string[]>();
|
||||||
|
|
||||||
for (const [instanceName, channelId] of Object.entries(mapping ?? {})) {
|
for (const [instanceName, channelId] of Object.entries(mapping ?? {})) {
|
||||||
|
// A blank value would otherwise map the literal channel ''.
|
||||||
|
if (!channelId) continue;
|
||||||
|
|
||||||
const names = next.get(channelId) ?? [];
|
const names = next.get(channelId) ?? [];
|
||||||
names.push(instanceName);
|
names.push(instanceName);
|
||||||
next.set(channelId, names);
|
next.set(channelId, names);
|
||||||
@@ -189,8 +208,8 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
if (names.length > 1 && !warnedAmbiguous.has(channelId)) {
|
if (names.length > 1 && !warnedAmbiguous.has(channelId)) {
|
||||||
warnedAmbiguous.add(channelId);
|
warnedAmbiguous.add(channelId);
|
||||||
logger.warn(
|
logger.warn(
|
||||||
`[Chat Relay] Discord channel ${channelId} is mapped from ${names.length} instances`
|
`[Chat Relay] Discord channel ${channelId} is mapped by ${names.length} instances`
|
||||||
+ ` (${names.join(', ')}); messages are printed to all of them.`,
|
+ ` (${names.join(', ')}); its messages are printed in all of them.`,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -200,7 +219,7 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
|
|
||||||
const hasInboundMapping = () => channelToInstances.size > 0;
|
const hasInboundMapping = () => channelToInstances.size > 0;
|
||||||
|
|
||||||
/** Token bucket per channel. Discord is far chattier than Factorio chat ever is. */
|
/** Token bucket per channel: Discord is far chattier than Factorio chat ever is. */
|
||||||
const takeToken = (channelId: string): boolean => {
|
const takeToken = (channelId: string): boolean => {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
let bucket = buckets.get(channelId);
|
let bucket = buckets.get(channelId);
|
||||||
@@ -222,7 +241,7 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
if (bucket.tokens < 1) {
|
if (bucket.tokens < 1) {
|
||||||
if (!bucket.warned) {
|
if (!bucket.warned) {
|
||||||
bucket.warned = true;
|
bucket.warned = true;
|
||||||
logger.warn(`[Chat Relay] Rate limiting inbound chat from Discord channel ${channelId}; dropping.`);
|
logger.warn(`[Chat Relay] Rate limiting inbound chat from channel ${channelId}; dropping.`);
|
||||||
}
|
}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
@@ -232,62 +251,46 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
return true;
|
return true;
|
||||||
};
|
};
|
||||||
|
|
||||||
const findInstanceId = (instanceName: string): number | null => {
|
|
||||||
for (const [id, instance] of controller.instances) {
|
|
||||||
if (instance.name === instanceName) return id;
|
|
||||||
}
|
|
||||||
|
|
||||||
return null;
|
|
||||||
};
|
|
||||||
|
|
||||||
const onDiscordMessage = async (message: Message) => {
|
const onDiscordMessage = async (message: Message) => {
|
||||||
if (shuttingDown || !client) return;
|
if (shuttingDown) return;
|
||||||
|
|
||||||
// The loop guard. Our own outbound posts are authored by the bot, as are
|
// The loop guard. Our own outbound posts are authored by the bot, as are
|
||||||
// webhooks and other bots, so Factorio -> Discord -> Factorio dies here.
|
// webhooks and other bots, so Factorio -> Discord -> Factorio dies here.
|
||||||
if (message.author.bot) return;
|
if (message.author.bot) return;
|
||||||
if (!message.inGuild()) return; // DMs and group DMs aren't mapped to anything
|
|
||||||
|
// DMs, group DMs and other unmapped guilds have no instance behind them.
|
||||||
|
if (!message.inGuild()) return;
|
||||||
|
|
||||||
const instanceNames = channelToInstances.get(message.channelId);
|
const instanceNames = channelToInstances.get(message.channelId);
|
||||||
if (!instanceNames) return; // unmapped channel, another guild, or a thread
|
if (!instanceNames) return;
|
||||||
|
|
||||||
const text = sanitiseInbound(message.content);
|
|
||||||
if (!text) return;
|
|
||||||
|
|
||||||
|
if (!message.content) return;
|
||||||
if (!takeToken(message.channelId)) return;
|
if (!takeToken(message.channelId)) return;
|
||||||
|
|
||||||
const authorName = sanitiseInbound(message.member?.displayName ?? message.author.username, 40);
|
const datetime = message.createdAt.toISOString();
|
||||||
|
const authorName = message.member?.displayName ?? message.author.username;
|
||||||
|
|
||||||
for (const instanceName of instanceNames) {
|
for (const instanceName of instanceNames) {
|
||||||
const instanceId = findInstanceId(instanceName);
|
|
||||||
|
|
||||||
if (instanceId === null) {
|
|
||||||
if (!warnedNoInstance.has(instanceName)) {
|
|
||||||
warnedNoInstance.add(instanceName);
|
|
||||||
logger.warn(`[Chat Relay] Instance ${instanceName} is mapped for inbound chat but does not exist.`);
|
|
||||||
}
|
|
||||||
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
await controller.sendTo(instanceId, new ChatFromDiscordEvent({
|
await controller.sendTo(instanceName, new ChatFromDiscordEvent(
|
||||||
author_name: authorName,
|
authorName,
|
||||||
channel_id: message.channelId,
|
message.channelId,
|
||||||
datetime: message.createdAt.toISOString(),
|
datetime,
|
||||||
message: text,
|
message.content,
|
||||||
}));
|
));
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
// A stopped instance plus a busy channel would otherwise be a log flood.
|
// A stopped instance on a busy channel would otherwise be a log flood.
|
||||||
if (!warnedSendFail.has(instanceName)) {
|
if (!warnedSendFail.has(instanceName)) {
|
||||||
warnedSendFail.add(instanceName);
|
warnedSendFail.add(instanceName);
|
||||||
logger.error(`[Chat Relay] Failed to relay Discord chat to ${instanceName}:\n${stackOf(err)}`);
|
logger.error(
|
||||||
|
`[Chat Relay] Failed to relay Discord chat to ${instanceName}:\n${stackOf(err)}`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// ------------------------------------------------------------------ client
|
// ----------------------------------------------------------------- client
|
||||||
|
|
||||||
const closeGateway = async () => {
|
const closeGateway = async () => {
|
||||||
const old = client;
|
const old = client;
|
||||||
@@ -302,7 +305,7 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
/** Assumes `rest` is authenticated; the token it was built from is the live one. */
|
/** Requires an authenticated `rest`; only ever called from connect()/syncGateway(). */
|
||||||
const openGateway = async () => {
|
const openGateway = async () => {
|
||||||
const token = getToken();
|
const token = getToken();
|
||||||
if (!token || !rest || client) return;
|
if (!token || !rest || client) return;
|
||||||
@@ -318,6 +321,7 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
logger.error(`[Chat Relay] Inbound handler failed:\n${stackOf(err)}`);
|
logger.error(`[Chat Relay] Inbound handler failed:\n${stackOf(err)}`);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
newClient.on('error', err => logger.error(`[Chat Relay] Discord gateway error:\n${stackOf(err)}`));
|
newClient.on('error', err => logger.error(`[Chat Relay] Discord gateway error:\n${stackOf(err)}`));
|
||||||
newClient.on('shardDisconnect', () => logger.warn('[Chat Relay] Discord gateway disconnected.'));
|
newClient.on('shardDisconnect', () => logger.warn('[Chat Relay] Discord gateway disconnected.'));
|
||||||
|
|
||||||
@@ -336,7 +340,7 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
client = newClient;
|
client = newClient;
|
||||||
logger.info('[Chat Relay] Discord gateway connected (inbound chat enabled).');
|
logger.info('[Chat Relay] Discord gateway connected; inbound chat enabled.');
|
||||||
};
|
};
|
||||||
|
|
||||||
const syncGateway = async () => {
|
const syncGateway = async () => {
|
||||||
@@ -349,6 +353,8 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const connect = async () => {
|
const connect = async () => {
|
||||||
|
// Drop both halves first: the old REST client holds the previous token, and
|
||||||
|
// the old gateway is logged in with it.
|
||||||
rest = null;
|
rest = null;
|
||||||
await closeGateway();
|
await closeGateway();
|
||||||
|
|
||||||
@@ -361,6 +367,7 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
const newRest = new REST({version: '10'}).setToken(token);
|
const newRest = new REST({version: '10'}).setToken(token);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
// Fail fast at startup instead of silently on the first chat line.
|
||||||
const me = await newRest.get(Routes.user('@me')) as {id: string, username: string};
|
const me = await newRest.get(Routes.user('@me')) as {id: string, username: string};
|
||||||
logger.info(`[Chat Relay] Authenticated with Discord as ${me.username} (${me.id}).`);
|
logger.info(`[Chat Relay] Authenticated with Discord as ${me.username} (${me.id}).`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -374,7 +381,7 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
await syncGateway();
|
await syncGateway();
|
||||||
};
|
};
|
||||||
|
|
||||||
// ------------------------------------------------------------------ wiring
|
// ----------------------------------------------------------------- wiring
|
||||||
|
|
||||||
rebuildInboundMap();
|
rebuildInboundMap();
|
||||||
|
|
||||||
@@ -390,7 +397,6 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
} else if (field === 'chat_relay.discord_channel_mapping') {
|
} else if (field === 'chat_relay.discord_channel_mapping') {
|
||||||
warnedNoMapping.clear();
|
warnedNoMapping.clear();
|
||||||
warnedBadChannel.clear();
|
warnedBadChannel.clear();
|
||||||
} else if (field === 'chat_relay.discord_to_factorio_channel_mapping') {
|
|
||||||
warnedAmbiguous.clear();
|
warnedAmbiguous.clear();
|
||||||
warnedNoInstance.clear();
|
warnedNoInstance.clear();
|
||||||
warnedSendFail.clear();
|
warnedSendFail.clear();
|
||||||
@@ -403,6 +409,8 @@ export default async function(context: ControllerPluginContext) {
|
|||||||
});
|
});
|
||||||
|
|
||||||
controller.hooks.shutdown.attach(plugin.name, async () => {
|
controller.hooks.shutdown.attach(plugin.name, async () => {
|
||||||
|
// Nothing to tear down on the REST side; in-flight calls aren't cancellable
|
||||||
|
// and will finish or time out. The gateway does need an explicit destroy.
|
||||||
shuttingDown = true;
|
shuttingDown = true;
|
||||||
await closeGateway();
|
await closeGateway();
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,6 +1,11 @@
|
|||||||
import type * as lib from '@clusterio/lib';
|
import type * as lib from '@clusterio/lib';
|
||||||
import type {Instance, InstancePluginContext} from '@clusterio/host';
|
import {Type} from '@sinclair/typebox';
|
||||||
import {Type, Static} from '@sinclair/typebox';
|
import type {Static} from '@sinclair/typebox';
|
||||||
|
|
||||||
|
/* Shared declarations for the chat relay plugin.
|
||||||
|
* `sanitiseForFactorio` is used by both processes: the controller cleans text
|
||||||
|
* before it leaves, and the instance cleans it again before it reaches game.print.
|
||||||
|
*/
|
||||||
|
|
||||||
export const chatFromDiscord = Type.Object({
|
export const chatFromDiscord = Type.Object({
|
||||||
author_name: Type.String(),
|
author_name: Type.String(),
|
||||||
@@ -11,10 +16,25 @@ export const chatFromDiscord = Type.Object({
|
|||||||
|
|
||||||
export type ChatFromDiscord = Static<typeof chatFromDiscord>;
|
export type ChatFromDiscord = Static<typeof chatFromDiscord>;
|
||||||
|
|
||||||
// Mirror whatever base class / constructor shape your ChatEvent uses.
|
export class ChatFromDiscordEvent {
|
||||||
export class ChatFromDiscordEvent extends Event<typeof chatFromDiscord> {
|
declare ['constructor']: typeof ChatFromDiscordEvent;
|
||||||
constructor(data: ChatFromDiscord) {
|
static type = 'event' as const;
|
||||||
super(chatFromDiscord, data);
|
static src = 'controller' as const;
|
||||||
|
static dst = 'instance' as const;
|
||||||
|
static plugin = 'chat_relay' as const;
|
||||||
|
static permission = null;
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
public author_name: string,
|
||||||
|
public channel_id: string,
|
||||||
|
public datetime: string,
|
||||||
|
public message: string,
|
||||||
|
) {}
|
||||||
|
|
||||||
|
static jsonSchema = chatFromDiscord;
|
||||||
|
|
||||||
|
static fromJSON(json: Static<typeof ChatFromDiscordEvent.jsonSchema>) {
|
||||||
|
return new this(json.author_name, json.channel_id, json.datetime, json.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,68 +68,69 @@ export function sanitiseForFactorio(text: string, limit = MAX_INBOUND_LENGTH): s
|
|||||||
}
|
}
|
||||||
|
|
||||||
export class ChatEvent {
|
export class ChatEvent {
|
||||||
declare ['constructor']: typeof ChatEvent;
|
declare ['constructor']: typeof ChatEvent;
|
||||||
static type = 'event' as const;
|
static type = 'event' as const;
|
||||||
static src = 'instance' as const;
|
static src = 'instance' as const;
|
||||||
static dst = 'controller' as const;
|
static dst = 'controller' as const;
|
||||||
static plugin = 'chat_relay' as const;
|
static plugin = 'chat_relay' as const;
|
||||||
static permission = null;
|
static permission = null;
|
||||||
|
|
||||||
constructor(
|
constructor(
|
||||||
public instance_name: string,
|
public instance_name: string,
|
||||||
public datetime: string,
|
public datetime: string,
|
||||||
public message: string,
|
public message: string,
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
static jsonSchema = Type.Object({
|
static jsonSchema = Type.Object({
|
||||||
'instance_name': Type.String(),
|
'instance_name': Type.String(),
|
||||||
'datetime': Type.String(),
|
'datetime': Type.String(),
|
||||||
'message': Type.String(),
|
'message': Type.String(),
|
||||||
});
|
});
|
||||||
|
|
||||||
static fromJSON(json: Static<typeof ChatEvent.jsonSchema>) {
|
static fromJSON(json: Static<typeof ChatEvent.jsonSchema>) {
|
||||||
return new this(json.instance_name, json.datetime, json.message);
|
return new this(json.instance_name, json.datetime, json.message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
declare module '@clusterio/lib' {
|
declare module '@clusterio/lib' {
|
||||||
interface ControllerConfigFields {
|
interface ControllerConfigFields {
|
||||||
'chat_relay.discord_bot_token': string;
|
'chat_relay.discord_bot_token': string;
|
||||||
'chat_relay.datetime_on_message': boolean;
|
'chat_relay.datetime_on_message': boolean;
|
||||||
'chat_relay.discord_channel_mapping': Record<string, string>;
|
'chat_relay.discord_channel_mapping': Record<string, string>;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const plugin: lib.PluginDeclaration = {
|
export const plugin: lib.PluginDeclaration = {
|
||||||
name: 'chat_relay',
|
name: 'chat_relay',
|
||||||
title: 'Chat Relay',
|
title: 'Chat Relay',
|
||||||
description: 'One way chat relay to Discord.',
|
description: 'Bidirectional chat relay between Factorio and Discord.',
|
||||||
webEntrypoint: './web',
|
webEntrypoint: './web',
|
||||||
instanceEntrypoint: 'dist/node/instance.js',
|
instanceEntrypoint: 'dist/node/instance.js',
|
||||||
controllerEntrypoint: 'dist/node/controller.js',
|
controllerEntrypoint: 'dist/node/controller.js',
|
||||||
controllerConfigFields: {
|
controllerConfigFields: {
|
||||||
'chat_relay.discord_bot_token': {
|
'chat_relay.discord_bot_token': {
|
||||||
title: 'Discord Bot Token',
|
title: 'Discord Bot Token',
|
||||||
description: 'API Token',
|
description: 'API Token',
|
||||||
type: 'string',
|
type: 'string',
|
||||||
credential: ['controller']
|
credential: ['controller'],
|
||||||
},
|
},
|
||||||
'chat_relay.datetime_on_message': {
|
'chat_relay.datetime_on_message': {
|
||||||
title: 'Message Datetime',
|
title: 'Message Datetime',
|
||||||
description: 'Append datetime in front',
|
description: 'Append datetime in front',
|
||||||
type: 'boolean',
|
type: 'boolean',
|
||||||
initialValue: true
|
initialValue: true,
|
||||||
},
|
},
|
||||||
'chat_relay.discord_channel_mapping': {
|
'chat_relay.discord_channel_mapping': {
|
||||||
title: 'Discord Channels',
|
title: 'Discord Channels',
|
||||||
description: 'Instance and Discord channel ID relations',
|
description: 'Instance and Discord channel ID relations, used in both directions',
|
||||||
type: 'object',
|
type: 'object',
|
||||||
initialValue: {
|
initialValue: {
|
||||||
'S1': '123'
|
'S1': '123',
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
messages: [
|
messages: [
|
||||||
ChatEvent,
|
ChatEvent,
|
||||||
],
|
ChatFromDiscordEvent,
|
||||||
|
],
|
||||||
};
|
};
|
||||||
+13
-5
@@ -3,7 +3,7 @@ import {ChatEvent, ChatFromDiscordEvent, sanitiseForFactorio} from './index.js';
|
|||||||
|
|
||||||
interface ChatMessage {
|
interface ChatMessage {
|
||||||
datetime: string;
|
datetime: string;
|
||||||
message: string;
|
message: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function datetime(): string {
|
function datetime(): string {
|
||||||
@@ -25,8 +25,6 @@ function parse_save(line: string): number | null {
|
|||||||
return slot ? Number(slot[1]) : null;
|
return slot ? Number(slot[1]) : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Instance-side half of inbound chat: turn a relayed Discord message into a chat line. */
|
|
||||||
|
|
||||||
/** Escape a JS string for embedding in a double-quoted Lua literal. */
|
/** Escape a JS string for embedding in a double-quoted Lua literal. */
|
||||||
function luaString(text: string): string {
|
function luaString(text: string): string {
|
||||||
return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
return `"${text.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
|
||||||
@@ -37,11 +35,17 @@ export default async function(context: InstancePluginContext) {
|
|||||||
const queue: ChatMessage[] = [];
|
const queue: ChatMessage[] = [];
|
||||||
let flushing = false;
|
let flushing = false;
|
||||||
|
|
||||||
|
// Log-once guard: a busy channel plus a stopped instance or dead RCON would
|
||||||
|
// otherwise write one error per message. Re-armed on controller connect.
|
||||||
|
const warnedPrintFail = new Set<string>();
|
||||||
|
|
||||||
const flush = async () => {
|
const flush = async () => {
|
||||||
if (flushing || queue.length === 0 || !host.connector.connected) {
|
if (flushing || queue.length === 0 || !host.connector.connected) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
flushing = true;
|
flushing = true;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
while (queue.length > 0 && host.connector.connected) {
|
while (queue.length > 0 && host.connector.connected) {
|
||||||
try {
|
try {
|
||||||
@@ -59,6 +63,7 @@ export default async function(context: InstancePluginContext) {
|
|||||||
|
|
||||||
instance.hooks.controllerConnectionEvent.attach(plugin.name, async (event) => {
|
instance.hooks.controllerConnectionEvent.attach(plugin.name, async (event) => {
|
||||||
if (event === 'connect') {
|
if (event === 'connect') {
|
||||||
|
warnedPrintFail.clear();
|
||||||
await flush();
|
await flush();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -87,7 +92,7 @@ export default async function(context: InstancePluginContext) {
|
|||||||
|
|
||||||
await flush();
|
await flush();
|
||||||
} else if (output.type === 'log') {
|
} else if (output.type === 'log') {
|
||||||
let message = output.message.trim();
|
const message = output.message.trim();
|
||||||
const save_slot = parse_save(message);
|
const save_slot = parse_save(message);
|
||||||
|
|
||||||
if (!save_slot) {
|
if (!save_slot) {
|
||||||
@@ -114,7 +119,10 @@ export default async function(context: InstancePluginContext) {
|
|||||||
// so this cannot echo back out through the outbound half.
|
// so this cannot echo back out through the outbound half.
|
||||||
await instance.sendRcon(`/sc game.print(${luaString(line)})`);
|
await instance.sendRcon(`/sc game.print(${luaString(line)})`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
logger.error(`[Chat Relay] Failed to print Discord message in game:\n${(err as Error).stack}`);
|
if (!warnedPrintFail.has(instance.name)) {
|
||||||
|
warnedPrintFail.add(instance.name);
|
||||||
|
logger.error(`[Chat Relay] Failed to print Discord message in game:\n${(err as Error).stack}`);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user