Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

feat(automations): add any-comment rules and the followers-only option to the app

spacesdrive49fb2ce7bcbb
diff --git a/frontend/src/features/automations/AutomationAccounts.tsx b/frontend/src/features/automations/AutomationAccounts.tsx
index 79fc296..800ccd0 100644
--- a/frontend/src/features/automations/AutomationAccounts.tsx
+++ b/frontend/src/features/automations/AutomationAccounts.tsx
@@ -5,26 +5,29 @@ import { Spinner } from '@/components/ui/spinner';
import { Switch } from '@/components/ui/switch';
import SurfaceBox from '@/components/SurfaceBox';
import { AccountAvatar } from '@/components/platform';
-import { accountStatus } from './automationData.ts';
-import type { AutomationAccountState } from '@shared/types/automation.ts';
+import { accountStatus, needsMessageEvents } from './automationData.ts';
+import type { AutomationAccountState, AutomationRule } from '@shared/types/automation.ts';
import type { AppAccount } from '../../utils/formatters';
import type { AutomationsState } from './useAutomations';
interface AutomationAccountsProps {
accounts: AutomationAccountState[];
+ rules: AutomationRule[];
appAccounts: AppAccount[];
automations: AutomationsState;
}
interface AccountRowProps {
account: AutomationAccountState;
+ needsMessages: boolean;
appAccount: AppAccount | undefined;
busy: boolean;
automations: AutomationsState;
}
-function AccountRow({ account, appAccount, busy, automations }: AccountRowProps) {
- const status = accountStatus(account, automations.checkedAt);
+function AccountRow({ account, needsMessages, appAccount, busy, automations }: AccountRowProps) {
+ const status = accountStatus(account, automations.checkedAt, needsMessages);
+ const missingMessages = needsMessages && Boolean(account.subscribedAt) && !account.messagesSubscribed;
const switchId = `pause-${account.accountId}`;
return (
<li className="flex flex-col gap-3 py-4 first:pt-0 last:pb-0 sm:flex-row sm:items-center sm:justify-between">
@@ -39,10 +42,10 @@ function AccountRow({ account, appAccount, busy, automations }: AccountRowProps)
</div>
</div>
<div className="flex shrink-0 items-center gap-3">
- {!account.subscribedAt && (
+ {(!account.subscribedAt || missingMessages) && (
<Button size="sm" variant="outline" onClick={() => automations.subscribeAccount(account)} disabled={busy}>
{busy ? <Spinner className="size-4" /> : <Radio data-icon="inline-start" />}
- Turn on comment events
+ {missingMessages ? 'Turn on message events' : 'Turn on comment events'}
</Button>
)}
<label htmlFor={switchId} className="flex items-center gap-2 text-small text-ink-muted">
@@ -54,7 +57,7 @@ function AccountRow({ account, appAccount, busy, automations }: AccountRowProps)
);
}
-export default function AutomationAccounts({ accounts, appAccounts, automations }: AutomationAccountsProps) {
+export default function AutomationAccounts({ accounts, rules, appAccounts, automations }: AutomationAccountsProps) {
return (
<SurfaceBox title="Instagram accounts" subheader="Pause an account to hold its replies. Comments keep arriving and wait for you to resume.">
<ul className="flex flex-col divide-y divide-divider">
@@ -62,6 +65,7 @@ export default function AutomationAccounts({ accounts, appAccounts, automations
<AccountRow
key={account.accountId}
account={account}
+ needsMessages={needsMessageEvents(rules, account.accountId)}
appAccount={appAccounts.find(item => item.id === account.accountId)}
busy={automations.busyId === account.accountId}
automations={automations}
diff --git a/frontend/src/features/automations/AutomationActivity.tsx b/frontend/src/features/automations/AutomationActivity.tsx
index 7e69679..69a5851 100644
--- a/frontend/src/features/automations/AutomationActivity.tsx
+++ b/frontend/src/features/automations/AutomationActivity.tsx
@@ -9,7 +9,7 @@ import RowAction from '@/components/RowAction';
import SurfaceBox from '@/components/SurfaceBox';
import { EmptyState } from '@/components/StateViews';
import { fmtDate, timeAgo } from '../../utils/formatters';
-import { ACTIVITY_FILTERS, STATS_PERIODS, canRetry, statusDisplay } from './automationData.ts';
+import { ACTIVITY_FILTERS, STATS_PERIODS, canRetry, gateDetail, statusDisplay } from './automationData.ts';
import type { ActivityFilter, StatsPeriod } from './automationData.ts';
import type { AutomationAccountState, AutomationActivityItem, AutomationRule } from '@shared/types/automation.ts';
import type { AutomationActivityState } from './useAutomationActivity';
@@ -47,11 +47,15 @@ function ActivityRow({ item, now, ruleName, username, retrying, onRetry }: Activ
<TableCell className="whitespace-nowrap text-small text-ink-muted">{ruleName ?? '-'}</TableCell>
<TableCell><Badge variant={status.tone}>{status.label}</Badge></TableCell>
<TableCell className="min-w-64 max-w-md whitespace-normal text-small text-ink-muted">
- {item.errorMessage ?? waitingUntil ?? (item.acceptedAt ? `Accepted ${fmtDate(item.acceptedAt)}` : '-')}
+ {gateDetail(item) ?? item.errorMessage ?? waitingUntil ?? (item.acceptedAt ? `Accepted ${fmtDate(item.acceptedAt)}` : '-')}
</TableCell>
<TableCell className="text-right">
{canRetry(item, now) && (
- <RowAction label={item.status === 'needs_review' ? 'Send again after checking Instagram' : 'Try again'} onClick={() => onRetry(item)} disabled={retrying}>
+ <RowAction
+ label={item.status === 'needs_review' || item.followup?.status === 'needs_review' ? 'Send again after checking Instagram' : 'Try again'}
+ onClick={() => onRetry(item)}
+ disabled={retrying}
+ >
{retrying ? <Spinner /> : <RotateCcw />}
</RowAction>
)}
diff --git a/frontend/src/features/automations/AutomationRules.tsx b/frontend/src/features/automations/AutomationRules.tsx
index 8a192a9..b549ee3 100644
--- a/frontend/src/features/automations/AutomationRules.tsx
+++ b/frontend/src/features/automations/AutomationRules.tsx
@@ -37,7 +37,10 @@ function RuleRow({ rule, username, busy, automations, onEdit, onDelete }: RuleRo
<span className="text-caption text-ink-faint">@{username}</span>
</div>
<div className="flex flex-wrap gap-1.5" aria-label="Keywords">
- {rule.keywords.map(keyword => <Badge key={keyword} variant="secondary">{keyword}</Badge>)}
+ {rule.matchMode === 'any'
+ ? <Badge variant="warning">Any comment</Badge>
+ : rule.keywords.map(keyword => <Badge key={keyword} variant="secondary">{keyword}</Badge>)}
+ {rule.requireFollow && <Badge variant="info">Followers only</Badge>}
</div>
<p className="text-small text-ink-muted">
{matchModeLabel(rule)} &middot; {ruleScopeLabel(rule)}{rule.hourlyLimit ? ` · at most ${rule.hourlyLimit} an hour` : ''}
diff --git a/frontend/src/features/automations/Automations.tsx b/frontend/src/features/automations/Automations.tsx
index 139776a..ed58791 100644
--- a/frontend/src/features/automations/Automations.tsx
+++ b/frontend/src/features/automations/Automations.tsx
@@ -70,7 +70,7 @@ export default function Automations() {
{header}
<AutomationNotices settings={overview.settings} />
<AutomationMetrics summary={activity.summary} loading={activity.loading && !activity.summary} />
- <AutomationAccounts accounts={overview.accounts} appAccounts={igAccounts} automations={automations} />
+ <AutomationAccounts accounts={overview.accounts} rules={overview.rules} appAccounts={igAccounts} automations={automations} />
<AutomationRules
rules={overview.rules}
accounts={overview.accounts}
diff --git a/frontend/src/features/automations/RuleDialog.tsx b/frontend/src/features/automations/RuleDialog.tsx
index 9d12e03..90b9d32 100644
--- a/frontend/src/features/automations/RuleDialog.tsx
+++ b/frontend/src/features/automations/RuleDialog.tsx
@@ -1,3 +1,5 @@
+import { Megaphone, UserCheck } from 'lucide-react';
+import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Input } from '@/components/ui/input';
@@ -22,6 +24,7 @@ interface RuleDialogProps {
const MATCH_MODES: { value: AutomationMatchMode; label: string }[] = [
{ value: 'contains', label: 'Anywhere in the comment, as a whole word' },
{ value: 'exact', label: 'The whole comment, nothing else' },
+ { value: 'any', label: 'Any comment, no keyword needed' },
];
const SCOPES: { value: RuleScope; label: string }[] = [
@@ -36,7 +39,7 @@ export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {
<DialogContent className="max-h-[calc(100dvh-2rem)] overflow-y-auto sm:max-w-3xl">
<DialogHeader>
<DialogTitle>{rule.ruleId ? 'Edit rule' : 'New rule'}</DialogTitle>
- <DialogDescription>When a comment contains a keyword, Twiligent sends its author this private reply on Instagram.</DialogDescription>
+ <DialogDescription>When a comment matches, Twiligent sends its author this private reply on Instagram.</DialogDescription>
</DialogHeader>
<form id="automation-rule-form" onSubmit={rule.handleSubmit} className="grid gap-6 md:grid-cols-[minmax(0,1fr)_minmax(0,0.9fr)]">
<div className="flex flex-col gap-5">
@@ -46,9 +49,6 @@ export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {
<FieldRow label="Name" htmlFor="rule-name" hint="Only you see this.">
<Input id="rule-name" value={form.name} maxLength={80} onChange={e => setField('name', e.target.value)} placeholder="Free guide" />
</FieldRow>
- <FieldRow label="Keywords" htmlFor="rule-keywords" hint="Separate keywords with commas. Up to 10.">
- <Input id="rule-keywords" value={form.keywordsText} onChange={e => setField('keywordsText', e.target.value)} placeholder="GUIDE, LINK" />
- </FieldRow>
<FieldRow label="Match">
<Select value={form.matchMode} onValueChange={value => value && setField('matchMode', value as AutomationMatchMode)} items={MATCH_MODES}>
<SelectTrigger className="w-full" aria-label="Match"><SelectValue /></SelectTrigger>
@@ -58,11 +58,28 @@ export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {
</SelectGroup>
</SelectContent>
</Select>
- <label htmlFor="rule-case" className="flex items-center justify-between gap-3 text-small text-ink-muted">
- Match the letter case exactly
- <Switch id="rule-case" checked={form.caseSensitive} onCheckedChange={checked => setField('caseSensitive', checked)} />
- </label>
+ {form.matchMode !== 'any' && (
+ <label htmlFor="rule-case" className="flex items-center justify-between gap-3 text-small text-ink-muted">
+ Match the letter case exactly
+ <Switch id="rule-case" checked={form.caseSensitive} onCheckedChange={checked => setField('caseSensitive', checked)} />
+ </label>
+ )}
</FieldRow>
+ {form.matchMode === 'any' ? (
+ <Alert variant="warning">
+ <Megaphone />
+ <AlertTitle>Every comment gets this reply</AlertTitle>
+ <AlertDescription>
+ Everyone who comments receives a private message, including people who did not ask for one, and a busy post reaches the
+ hourly limits sooner. Each person gets at most a few replies a day. Aim the rule at chosen posts to keep it small. A
+ keyword rule for the same post still answers first.
+ </AlertDescription>
+ </Alert>
+ ) : (
+ <FieldRow label="Keywords" htmlFor="rule-keywords" hint="Separate keywords with commas. Up to 10.">
+ <Input id="rule-keywords" value={form.keywordsText} onChange={e => setField('keywordsText', e.target.value)} placeholder="GUIDE, LINK" />
+ </FieldRow>
+ )}
<FieldRow label="Posts">
<Select value={form.scope} onValueChange={value => value && setField('scope', value as RuleScope)} items={SCOPES}>
<SelectTrigger className="w-full" aria-label="Posts"><SelectValue /></SelectTrigger>
@@ -74,7 +91,28 @@ export default function RuleDialog({ rule, igAccounts }: RuleDialogProps) {
</Select>
{form.scope === 'selected' && <RuleMediaPicker media={rule.media} loading={rule.mediaLoading} selected={form.mediaIds} onToggle={rule.toggleMedia} />}
</FieldRow>
- <FieldRow label="Reply" htmlFor="rule-reply">
+ <div className="flex flex-col gap-3 rounded-card border border-line p-4">
+ <label htmlFor="rule-follow" className="flex items-center justify-between gap-3 text-sm font-medium text-ink">
+ <span className="flex items-center gap-2"><UserCheck className="size-4 text-ink-muted" />Send the link only to followers</span>
+ <Switch id="rule-follow" checked={form.requireFollow} onCheckedChange={checked => setField('requireFollow', checked)} />
+ </label>
+ <p className="text-small text-ink-muted">
+ Instagram tells Twiligent whether someone follows you only after they message you. With this on, the first reply asks them
+ to follow and reply. When they reply, Twiligent asks Instagram, then sends the reply and link to followers and a reminder to
+ everyone else, twice at most. If Instagram cannot say, nothing is sent.
+ </p>
+ {form.requireFollow && (
+ <>
+ <FieldRow label="First reply" htmlFor="rule-follow-prompt" hint="Sent to everyone who comments. It has no link.">
+ <Textarea id="rule-follow-prompt" rows={3} maxLength={1000} value={form.followPromptText} onChange={e => setField('followPromptText', e.target.value)} />
+ </FieldRow>
+ <FieldRow label="Reminder" htmlFor="rule-follow-reminder" hint="Sent when they reply but do not follow yet.">
+ <Textarea id="rule-follow-reminder" rows={3} maxLength={1000} value={form.notFollowingText} onChange={e => setField('notFollowingText', e.target.value)} />
+ </FieldRow>
+ </>
+ )}
+ </div>
+ <FieldRow label={form.requireFollow ? 'Reply for followers' : 'Reply'} htmlFor="rule-reply">
<Textarea id="rule-reply" rows={4} maxLength={1000} value={form.replyText} onChange={e => setField('replyText', e.target.value)} placeholder="Here is your guide. Enjoy it." />
</FieldRow>
<FieldRow label="Link" htmlFor="rule-link" hint="Optional. Added on its own line after the reply. Must start with https://">
diff --git a/frontend/src/features/automations/RulePreview.tsx b/frontend/src/features/automations/RulePreview.tsx
index 5c0527a..ef53905 100644
--- a/frontend/src/features/automations/RulePreview.tsx
+++ b/frontend/src/features/automations/RulePreview.tsx
@@ -10,18 +10,32 @@ interface RulePreviewProps {
rule: RuleFormState;
}
-// the private reply as the commenter would see it, and a keyword test that sends nothing
+function Bubble({ text, placeholder }: { text: string; placeholder: string }) {
+ return (
+ <div className="max-w-[85%] self-start rounded-card rounded-bl-row bg-surface-raised px-3.5 py-2.5 text-sm whitespace-pre-wrap text-ink shadow-xs">
+ {text || <span className="text-ink-faint">{placeholder}</span>}
+ </div>
+ );
+}
+
+// the private reply as the commenter would see it, and a match test that sends nothing
export default function RulePreview({ rule }: RulePreviewProps) {
const { form, testResult } = rule;
const message = composeReply(form.replyText, form.linkUrl);
const bytes = messageBytes(message);
+ const canTest = rule.sampleComment.trim() && (form.matchMode === 'any' || form.keywordsText.trim());
return (
<div className="flex flex-col gap-4 self-start rounded-card border border-line bg-surface-sunken p-4 md:sticky md:top-0">
<div className="flex flex-col gap-2">
<p className="text-small font-medium text-ink">Preview</p>
- <div className="max-w-[85%] self-start rounded-card rounded-bl-row bg-surface-raised px-3.5 py-2.5 text-sm whitespace-pre-wrap text-ink shadow-xs">
- {message || <span className="text-ink-faint">Your reply appears here</span>}
- </div>
+ {form.requireFollow && (
+ <>
+ <p className="text-caption text-ink-faint">First reply, to everyone who comments</p>
+ <Bubble text={form.followPromptText.trim()} placeholder="Your request to follow appears here" />
+ <p className="text-caption text-ink-faint">After they reply, if Instagram says they follow</p>
+ </>
+ )}
+ <Bubble text={message} placeholder="Your reply appears here" />
<p className={cn('text-caption', bytes > MAX_MESSAGE_BYTES ? 'text-danger' : 'text-ink-faint')}>
{bytes} of {MAX_MESSAGE_BYTES} bytes. Instagram sends one private reply per comment, within 7 days of it.
</p>
@@ -30,7 +44,7 @@ export default function RulePreview({ rule }: RulePreviewProps) {
<label htmlFor="rule-test" className="text-small font-medium text-ink">Test a comment</label>
<div className="flex gap-2">
<Input id="rule-test" value={rule.sampleComment} onChange={e => rule.setSampleComment(e.target.value)} placeholder="Send me the guide" />
- <Button type="button" variant="outline" onClick={rule.runTest} disabled={rule.testing || !rule.sampleComment.trim() || !form.keywordsText.trim()}>
+ <Button type="button" variant="outline" onClick={rule.runTest} disabled={rule.testing || !canTest}>
{rule.testing ? <Spinner className="size-4" /> : <FlaskConical data-icon="inline-start" />}
Test
</Button>
@@ -38,11 +52,11 @@ export default function RulePreview({ rule }: RulePreviewProps) {
{testResult && (
<p role="status" className={cn('text-small', testResult.matched ? 'text-success' : 'text-ink-muted')}>
{testResult.matched
- ? `Matches the keyword ${testResult.keyword}. This comment would get the reply above.`
+ ? `${testResult.keyword ? `Matches the keyword ${testResult.keyword}.` : 'This rule answers any comment.'} This comment would get the ${form.requireFollow ? 'first reply' : 'reply'} above.`
: 'No keyword matches this comment, so it would get no reply.'}
</p>
)}
- <p className="text-caption text-ink-faint">The test checks the keywords only. Nothing is sent.</p>
+ <p className="text-caption text-ink-faint">The test checks the match only. Nothing is sent.</p>
</div>
</div>
);
diff --git a/frontend/src/features/automations/automationData.ts b/frontend/src/features/automations/automationData.ts
index 07d260a..089a288 100644
--- a/frontend/src/features/automations/automationData.ts
+++ b/frontend/src/features/automations/automationData.ts
@@ -49,6 +49,12 @@ export const STATS_PERIODS: Record<StatsPeriod, { label: string; ms: number }> =
export const MAX_MESSAGE_BYTES = 1000;
const MAX_KEYWORDS = 10;
const MAX_HOURLY_LIMIT = 750;
+// Instagram allows a message for 24 hours after the person's reply, so a follow-up can be retried only inside it
+const FOLLOWUP_WINDOW_MS = 24 * HOUR_MS;
+
+// where a followers-only rule starts; the owner edits both before saving
+export const DEFAULT_FOLLOW_PROMPT = 'Thanks for your comment. Follow this account, then reply to this message and the link is on its way.';
+export const DEFAULT_NOT_FOLLOWING = 'It looks like you do not follow this account yet. Follow it, then reply here again and the link is on its way.';
export interface AutomationSummary {
received: number;
@@ -74,15 +80,36 @@ export interface RuleForm {
linkUrl: string;
hourlyLimit: string;
enabled: boolean;
+ requireFollow: boolean;
+ followPromptText: string;
+ notFollowingText: string;
}
export function periodStart(period: StatsPeriod, now: number): string {
return new Date(now - STATS_PERIODS[period].ms).toISOString();
}
-export function statusDisplay(item: Pick<AutomationActivityItem, 'status' | 'statusReason'>): StatusDisplay {
+type ActivityStatus = Pick<AutomationActivityItem, 'status' | 'statusReason'> & Partial<Pick<AutomationActivityItem, 'gateStatus' | 'followup'>>;
+
+// a followers-only reply that Instagram accepted shows where the wait for the person stands, not just the first message
+export function statusDisplay(item: ActivityStatus): StatusDisplay {
if (item.status === 'queued' && item.statusReason === 'paused') return { label: 'Held', tone: 'warning' };
- return STATUS_DISPLAY[item.status];
+ if (item.status !== 'accepted' || !item.gateStatus) return STATUS_DISPLAY[item.status];
+ if (item.gateStatus === 'completed') return { label: 'Link sent', tone: 'success' };
+ if (item.gateStatus === 'closed') return { label: 'Not following', tone: 'secondary' };
+ if (item.followup?.status === 'needs_review') return { label: 'Needs review', tone: 'warning' };
+ if (item.followup?.status === 'failed') return { label: 'Follow-up failed', tone: 'destructive' };
+ return { label: 'Asked to follow', tone: 'info' };
+}
+
+// the sentence under a followers-only reply; null for any other item
+export function gateDetail(item: Pick<AutomationActivityItem, 'status' | 'gateStatus' | 'followup'>): string | null {
+ if (item.status !== 'accepted' || !item.gateStatus) return null;
+ if (item.gateStatus === 'completed') return 'Instagram confirmed they follow the account, and accepted the reply with the link.';
+ if (item.gateStatus === 'closed') return 'They did not follow after the reminders, so the link was not sent.';
+ if (item.followup?.errorMessage) return item.followup.errorMessage;
+ if (item.followup?.kind === 'reminder') return 'Reminded them to follow. Their next reply is checked again.';
+ return 'Asked them to follow and reply. When they reply, Instagram says whether they follow, and the link goes out if they do.';
}
function count(stats: AutomationStats, statuses: AutomationCommentStatus[]): number {
@@ -108,13 +135,19 @@ export function ruleScopeLabel(rule: Pick<AutomationRule, 'mediaIds'>): string {
}
export function matchModeLabel(rule: Pick<AutomationRule, 'matchMode' | 'caseSensitive'>): string {
+ if (rule.matchMode === 'any') return 'Any comment';
const mode = rule.matchMode === 'exact' ? 'Whole comment' : 'Anywhere in the comment';
return rule.caseSensitive ? `${mode}, same letter case` : mode;
}
-// failed, skipped and review items can be tried again until Instagram's 7 days run out
-export function canRetry(item: Pick<AutomationActivityItem, 'status' | 'expiresAt'>, now: number): boolean {
- return ['failed', 'needs_review', 'skipped'].includes(item.status) && Date.parse(item.expiresAt) > now;
+const RETRYABLE = ['failed', 'needs_review', 'skipped'];
+
+// failed, skipped and review items can be tried again until Instagram's 7 days run out; on an accepted followers-only
+// reply, a failed follow-up can be tried again inside the 24 hours after the person's answer
+export function canRetry(item: Pick<AutomationActivityItem, 'status' | 'expiresAt'> & Partial<Pick<AutomationActivityItem, 'followup'>>, now: number): boolean {
+ if (RETRYABLE.includes(item.status)) return Date.parse(item.expiresAt) > now;
+ const followup = item.followup;
+ return item.status === 'accepted' && !!followup && RETRYABLE.includes(followup.status) && Date.parse(followup.createdAt) + FOLLOWUP_WINDOW_MS > now;
}
// comma or line separated, trimmed, without blanks or repeats
@@ -143,6 +176,7 @@ export function emptyRuleForm(accountId: string): RuleForm {
return {
accountId, name: '', keywordsText: '', matchMode: 'contains', caseSensitive: false, scope: 'all', mediaIds: [],
replyText: '', linkUrl: '', hourlyLimit: '', enabled: true,
+ requireFollow: false, followPromptText: DEFAULT_FOLLOW_PROMPT, notFollowingText: DEFAULT_NOT_FOLLOWING,
};
}
@@ -159,6 +193,9 @@ export function ruleToForm(rule: AutomationRule): RuleForm {
linkUrl: rule.linkUrl ?? '',
hourlyLimit: rule.hourlyLimit === null ? '' : String(rule.hourlyLimit),
enabled: rule.enabled,
+ requireFollow: rule.requireFollow,
+ followPromptText: rule.followPromptText ?? DEFAULT_FOLLOW_PROMPT,
+ notFollowingText: rule.notFollowingText ?? DEFAULT_NOT_FOLLOWING,
};
}
@@ -166,7 +203,8 @@ export function formToRequest(form: RuleForm): AutomationRuleRequest {
return {
accountId: form.accountId,
name: form.name.trim(),
- keywords: parseKeywords(form.keywordsText, form.caseSensitive),
+ // an any-comment rule takes no keywords, so ones typed before switching to it are not sent
+ keywords: form.matchMode === 'any' ? [] : parseKeywords(form.keywordsText, form.caseSensitive),
matchMode: form.matchMode,
caseSensitive: form.caseSensitive,
mediaIds: form.scope === 'selected' ? form.mediaIds : [],
@@ -174,6 +212,9 @@ export function formToRequest(form: RuleForm): AutomationRuleRequest {
linkUrl: form.linkUrl.trim() || null,
enabled: form.enabled,
hourlyLimit: form.hourlyLimit.trim() ? Number(form.hourlyLimit) : null,
+ requireFollow: form.requireFollow,
+ followPromptText: form.followPromptText.trim() || null,
+ notFollowingText: form.notFollowingText.trim() || null,
};
}
@@ -194,9 +235,11 @@ function linkProblem(linkUrl: string): string | null {
export function ruleFormProblem(form: RuleForm): string | null {
if (!form.accountId) return 'Choose the Instagram account';
if (!form.name.trim()) return 'Give the rule a name';
- const keywords = parseKeywords(form.keywordsText, form.caseSensitive);
- if (keywords.length === 0) return 'Add at least one keyword';
- if (keywords.length > MAX_KEYWORDS) return `A rule can have at most ${MAX_KEYWORDS} keywords`;
+ if (form.matchMode !== 'any') {
+ const keywords = parseKeywords(form.keywordsText, form.caseSensitive);
+ if (keywords.length === 0) return 'Add at least one keyword';
+ if (keywords.length > MAX_KEYWORDS) return `A rule can have at most ${MAX_KEYWORDS} keywords`;
+ }
if (form.scope === 'selected' && form.mediaIds.length === 0) return 'Choose at least one post, or answer comments on every post';
if (!form.replyText.trim()) return 'Write the reply to send';
const link = linkProblem(form.linkUrl);
@@ -207,22 +250,43 @@ export function ruleFormProblem(form: RuleForm): string | null {
}
const bytes = messageBytes(composeReply(form.replyText, form.linkUrl));
if (bytes > MAX_MESSAGE_BYTES) return `The reply with its link is ${bytes} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}`;
+ if (form.requireFollow) {
+ if (!form.followPromptText.trim()) return 'Write the message that asks people to follow you and reply';
+ if (!form.notFollowingText.trim()) return 'Write the reminder for people who do not follow you yet';
+ const longest = Math.max(messageBytes(form.followPromptText.trim()), messageBytes(form.notFollowingText.trim()));
+ if (longest > MAX_MESSAGE_BYTES) return `A followers-only message is ${longest} bytes; Instagram accepts at most ${MAX_MESSAGE_BYTES}`;
+ }
return null;
}
+// a followers-only rule that is on needs Instagram to send the account's messages as well as its comments
+export function needsMessageEvents(rules: Pick<AutomationRule, 'accountId' | 'enabled' | 'requireFollow'>[], accountId: string): boolean {
+ return rules.some(rule => rule.accountId === accountId && rule.enabled && rule.requireFollow);
+}
+
export interface AccountStatus {
label: string;
tone: BadgeTone;
detail: string;
}
-// what an account's automation is doing right now, from its controls
-export function accountStatus(account: AutomationAccountState, now: number): AccountStatus {
+// what an account's automation is doing right now, from its controls; needsMessages when a followers-only rule is on
+export function accountStatus(account: AutomationAccountState, now: number, needsMessages = false): AccountStatus {
if (account.paused && account.cooldownReason) return { label: 'Held', tone: 'destructive', detail: account.cooldownReason };
if (account.paused) return { label: 'Paused', tone: 'secondary', detail: 'Comments are still recorded; replies wait until you resume, within Instagram\'s 7 days.' };
if (account.cooldownUntil && Date.parse(account.cooldownUntil) > now) {
return { label: 'Cooling down', tone: 'warning', detail: account.cooldownReason ?? 'Instagram is limiting replies from this account for now.' };
}
+ if (account.limitedUntil && Date.parse(account.limitedUntil) > now) {
+ return { label: 'At its hourly limit', tone: 'warning', detail: 'This account sent its hourly number of replies. The rest go out as the hour frees up, within Instagram\'s 7 days.' };
+ }
if (!account.subscribedAt) return { label: 'Not receiving comments', tone: 'warning', detail: 'Turn on comment events so Instagram sends this account\'s comments to Twiligent.' };
+ if (needsMessages && !account.messagesSubscribed) {
+ return {
+ label: 'Follow checks off',
+ tone: 'warning',
+ detail: 'A followers-only rule needs this account\'s messages. Select messages in the Meta dashboard webhook settings, then turn on message events. Until then, people who reply never get the link.',
+ };
+ }
return { label: 'Receiving comments', tone: 'success', detail: 'New comments that match an active rule get a reply.' };
}
diff --git a/frontend/src/features/automations/useRuleForm.ts b/frontend/src/features/automations/useRuleForm.ts
index 12d0220..0c8e54b 100644
--- a/frontend/src/features/automations/useRuleForm.ts
+++ b/frontend/src/features/automations/useRuleForm.ts
@@ -69,10 +69,11 @@ export function useRuleForm({ saveRule }: RuleFormDeps) {
const request = formToRequest(form);
setTesting(true);
try {
- // the test checks the keywords; which posts the rule covers applies to real comments only
+ // the test checks the match; which posts the rule covers applies to real comments only
setTestResult(await api.testAutomationRule({
keywords: request.keywords, matchMode: request.matchMode, caseSensitive: request.caseSensitive,
replyText: request.replyText || TEST_REPLY_PLACEHOLDER, linkUrl: request.linkUrl, comment: sampleComment,
+ requireFollow: request.requireFollow, followPromptText: request.followPromptText,
}));
} catch (err) {
showToast(`Couldn't test the rule. ${(err as Error).message}`, 'error');
diff --git a/frontend/tests/features/automations/automationData.test.ts b/frontend/tests/features/automations/automationData.test.ts
index 05f2669..a45d40e 100644
--- a/frontend/tests/features/automations/automationData.test.ts
+++ b/frontend/tests/features/automations/automationData.test.ts
@@ -1,8 +1,9 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
- ACTIVITY_FILTERS, MAX_MESSAGE_BYTES, accountStatus, canRetry, composeReply, emptyRuleForm, formToRequest, matchModeLabel, messageBytes,
- parseKeywords, periodStart, ruleFormProblem, ruleScopeLabel, ruleToForm, statusDisplay, summarizeStats,
+ ACTIVITY_FILTERS, DEFAULT_FOLLOW_PROMPT, DEFAULT_NOT_FOLLOWING, MAX_MESSAGE_BYTES, accountStatus, canRetry, composeReply, emptyRuleForm,
+ formToRequest, gateDetail, matchModeLabel, messageBytes, needsMessageEvents, parseKeywords, periodStart, ruleFormProblem, ruleScopeLabel,
+ ruleToForm, statusDisplay, summarizeStats,
} from '../../../src/features/automations/automationData.ts';
import type { RuleForm } from '../../../src/features/automations/automationData.ts';
import type { AutomationAccountState, AutomationRule } from '../../../../shared/types/automation.ts';
@@ -15,7 +16,8 @@ function form(overrides: Partial<RuleForm> = {}): RuleForm {
const rule: AutomationRule = {
id: 'r1', accountId: 'ig1', name: 'Guide', keywords: ['GUIDE', 'LINK'], matchMode: 'exact', caseSensitive: true, mediaIds: ['1', '2'],
- replyText: 'Here it is', linkUrl: 'https://example.com', enabled: false, hourlyLimit: 30, createdAt: 'c', updatedAt: 'u',
+ replyText: 'Here it is', linkUrl: 'https://example.com', enabled: false, hourlyLimit: 30, requireFollow: true, followPromptText: 'Follow and reply',
+ notFollowingText: 'Follow first', createdAt: 'c', updatedAt: 'u',
};
test('accepted replies say Instagram accepted them, never that they were delivered or read', () => {
@@ -24,6 +26,19 @@ test('accepted replies say Instagram accepted them, never that they were deliver
assert.equal(statusDisplay({ status: 'needs_review', statusReason: 'no_answer' }).label, 'Needs review');
});
+test('an accepted followers-only reply shows where the wait for the person stands', () => {
+ const accepted = { status: 'accepted' as const, statusReason: null };
+ assert.equal(statusDisplay({ ...accepted, gateStatus: null }).label, 'Accepted by Instagram');
+ assert.deepEqual(statusDisplay({ ...accepted, gateStatus: 'awaiting_reply', followup: null }), { label: 'Asked to follow', tone: 'info' });
+ assert.deepEqual(statusDisplay({ ...accepted, gateStatus: 'completed' }), { label: 'Link sent', tone: 'success' });
+ assert.deepEqual(statusDisplay({ ...accepted, gateStatus: 'closed' }), { label: 'Not following', tone: 'secondary' });
+ const failed = { status: 'failed' as const, kind: null, errorMessage: 'Instagram did not say', createdAt: 'x' };
+ assert.deepEqual(statusDisplay({ ...accepted, gateStatus: 'awaiting_reply', followup: failed }), { label: 'Follow-up failed', tone: 'destructive' });
+ assert.equal(gateDetail({ status: 'accepted', gateStatus: 'awaiting_reply', followup: failed }), 'Instagram did not say');
+ assert.match(gateDetail({ status: 'accepted', gateStatus: 'awaiting_reply', followup: null })!, /link goes out if they do/);
+ assert.equal(gateDetail({ status: 'accepted', gateStatus: null, followup: null }), null);
+});
+
test('the status filters cover every status exactly once, apart from All', () => {
const covered = Object.values(ACTIVITY_FILTERS).flatMap(filter => filter.statuses ?? []);
assert.equal(new Set(covered).size, covered.length);
@@ -49,6 +64,15 @@ test('rule summaries name the posts covered and how keywords match', () => {
assert.equal(ruleScopeLabel({ mediaIds: ['1', '2'] }), '2 selected posts');
assert.equal(matchModeLabel({ matchMode: 'contains', caseSensitive: false }), 'Anywhere in the comment');
assert.equal(matchModeLabel({ matchMode: 'exact', caseSensitive: true }), 'Whole comment, same letter case');
+ assert.equal(matchModeLabel({ matchMode: 'any', caseSensitive: true }), 'Any comment');
+});
+
+test('a failed follow-up on an accepted reply can be retried inside the 24 hours after the person\'s answer', () => {
+ const future = new Date(NOW + 1000).toISOString();
+ const followup = (status: 'failed' | 'accepted', hoursAgo: number) => ({ status, kind: null, errorMessage: null, createdAt: new Date(NOW - hoursAgo * 3600_000).toISOString() });
+ assert.equal(canRetry({ status: 'accepted', expiresAt: future, followup: followup('failed', 1) }, NOW), true);
+ assert.equal(canRetry({ status: 'accepted', expiresAt: future, followup: followup('failed', 25) }, NOW), false);
+ assert.equal(canRetry({ status: 'accepted', expiresAt: future, followup: followup('accepted', 1) }, NOW), false);
});
test('only failed, skipped and review items inside the 7 days offer a retry', () => {
@@ -75,9 +99,27 @@ test('a rule turns into its form and back without losing a field', () => {
assert.deepEqual(editing, {
accountId: 'ig1', name: 'Guide', keywordsText: 'GUIDE, LINK', matchMode: 'exact', caseSensitive: true, scope: 'selected', mediaIds: ['1', '2'],
replyText: 'Here it is', linkUrl: 'https://example.com', hourlyLimit: '30', enabled: false,
+ requireFollow: true, followPromptText: 'Follow and reply', notFollowingText: 'Follow first',
+ });
+ const { accountId, name, keywords, matchMode, caseSensitive, mediaIds, replyText, linkUrl, enabled, hourlyLimit, requireFollow, followPromptText, notFollowingText } = rule;
+ assert.deepEqual(formToRequest(editing), {
+ accountId, name, keywords, matchMode, caseSensitive, mediaIds, replyText, linkUrl, enabled, hourlyLimit, requireFollow, followPromptText, notFollowingText,
});
- const { accountId, name, keywords, matchMode, caseSensitive, mediaIds, replyText, linkUrl, enabled, hourlyLimit } = rule;
- assert.deepEqual(formToRequest(editing), { accountId, name, keywords, matchMode, caseSensitive, mediaIds, replyText, linkUrl, enabled, hourlyLimit });
+});
+
+test('a new rule starts with editable followers-only messages, used only when the option is on', () => {
+ const fresh = emptyRuleForm('ig1');
+ assert.deepEqual([fresh.requireFollow, fresh.followPromptText, fresh.notFollowingText], [false, DEFAULT_FOLLOW_PROMPT, DEFAULT_NOT_FOLLOWING]);
+ assert.equal(ruleFormProblem(form({ requireFollow: true })), null);
+ assert.equal(ruleFormProblem(form({ requireFollow: true, followPromptText: ' ' })), 'Write the message that asks people to follow you and reply');
+ assert.equal(ruleFormProblem(form({ requireFollow: true, notFollowingText: '' })), 'Write the reminder for people who do not follow you yet');
+ assert.match(ruleFormProblem(form({ requireFollow: true, notFollowingText: 'é'.repeat(501) }))!, /followers-only message is 1002 bytes/);
+ assert.equal(ruleFormProblem(form({ requireFollow: false, followPromptText: '' })), null);
+});
+
+test('an any-comment rule needs no keywords and sends none, even ones typed before switching', () => {
+ assert.equal(ruleFormProblem(form({ matchMode: 'any', keywordsText: '' })), null);
+ assert.deepEqual(formToRequest(form({ matchMode: 'any', keywordsText: 'GUIDE' })).keywords, []);
});
test('a rule for every post sends no post ids, and blank optional fields become null', () => {
@@ -100,13 +142,27 @@ test('the form names the first thing to fix, in the order of the fields', () =>
assert.match(ruleFormProblem(form({ replyText: 'é'.repeat(MAX_MESSAGE_BYTES / 2 + 1) }))!, /is 1002 bytes; Instagram accepts at most 1000/);
});
-test('an account shows held, paused, cooling down, not receiving or receiving, in that order', () => {
+test('an account shows held, paused, cooling down, at its limit, not receiving, follow checks off or receiving, in that order', () => {
const base: AutomationAccountState = {
accountId: 'ig1', username: 'me', profilePictureUrl: '', paused: false, cooldownUntil: null, cooldownReason: null, subscribedAt: 'x',
+ limitedUntil: null, messagesSubscribed: false,
};
assert.equal(accountStatus({ ...base, paused: true, cooldownReason: 'Reconnect it' }, NOW).label, 'Held');
assert.equal(accountStatus({ ...base, paused: true }, NOW).label, 'Paused');
assert.equal(accountStatus({ ...base, cooldownUntil: new Date(NOW + 1000).toISOString() }, NOW).label, 'Cooling down');
+ assert.equal(accountStatus({ ...base, limitedUntil: new Date(NOW + 1000).toISOString() }, NOW).label, 'At its hourly limit');
assert.equal(accountStatus({ ...base, cooldownUntil: new Date(NOW - 1000).toISOString() }, NOW).label, 'Receiving comments');
assert.equal(accountStatus({ ...base, subscribedAt: null }, NOW).label, 'Not receiving comments');
+ assert.equal(accountStatus(base, NOW, true).label, 'Follow checks off');
+ assert.equal(accountStatus({ ...base, messagesSubscribed: true }, NOW, true).label, 'Receiving comments');
+});
+
+test('an account needs message events only while one of its followers-only rules is on', () => {
+ const rules = [
+ { accountId: 'ig1', enabled: true, requireFollow: false },
+ { accountId: 'ig1', enabled: false, requireFollow: true },
+ { accountId: 'ig2', enabled: true, requireFollow: true },
+ ];
+ assert.equal(needsMessageEvents(rules, 'ig1'), false);
+ assert.equal(needsMessageEvents(rules, 'ig2'), true);
});