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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,6 @@ xcuserdata/
.vscode
.direnv
.envrc.local
/reminders.json
/reminders.json.corrupt
/data
4 changes: 2 additions & 2 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,13 +17,13 @@ swift format lint --strict --recursive --parallel Package.swift Sources Tests

CI runs the lint and test steps on Linux, so code must build without Apple-only frameworks. The Swift version of the nixpkgs revision pinned in `flake.lock` and `SWIFT_VERSION` in the `Dockerfile` must match; `nix flake check` verifies this, and CI runs it.

Tests use Swift Testing with [PropertyBased](https://github.com/x-sheep/swift-property-based) for property-based tests. They `@testable import` the executable target. Top-level code in `main.swift` does not run in tests, so the globals defined there (`httpClient`, `log`, `bot`) are never initialized and must not be used. Logic worth testing belongs in the helpers in `Utils/` or in a command's own pure functions.
Tests use Swift Testing with [PropertyBased](https://github.com/x-sheep/swift-property-based) for property-based tests. They `@testable import` the executable target. Top-level code in `main.swift` does not run in tests, so the globals defined there (`httpClient`, `log`, `bot`, `reminderStore`) are never initialized and must not be used. Logic worth testing belongs in the helpers in `Utils/` or in a command's own pure functions. Code under test must not cancel a sleeping task, which rules out the `.timeLimit` trait too: on x86_64 Linux, Swift Testing segfaults capturing a backtrace of the resulting throw, so the Nix build fails while macOS and aarch64 pass.

Pushes to `main` build and publish `ghcr.io/swiftde/swiftdebot:latest`, which `docker-compose.yml` deploys. The flake also exports the bot as `packages.default` and a NixOS module (`nix/module.nix`) that runs it as a systemd service. Its dependencies are pinned by a hash in `nix/package.nix`, so a `Package.resolved` change needs a new hash there; `nix flake check` fails until it has one and prints the right value. Foundation on Linux reads time zones only from `/usr/share/zoneinfo`: the Docker image has it, the module bind-mounts it on NixOS, and the Nix build's sandbox lacks it, so that build skips the suite that formats dates.

## Environment

`DISCORD_TOKEN` and `DISCORD_APP_ID` are required; the bot exits without them. `DISCORD_LOGS_WEBHOOK_URL` additionally forwards logs to a Discord webhook. `!summarize` needs `KAGI_API_TOKEN` for links and `OPENROUTER_API_KEY` for messages and images. `!factcheck` needs `OPENROUTER_API_KEY` and lets the model search the web through OpenRouter's web search tool, which costs extra per search. Both report a missing token in the channel instead of failing at startup.
`DISCORD_TOKEN` and `DISCORD_APP_ID` are required; the bot exits without them. `DISCORD_LOGS_WEBHOOK_URL` additionally forwards logs to a Discord webhook. `!summarize` needs `KAGI_API_TOKEN` for links and `OPENROUTER_API_KEY` for messages and images. `!factcheck` needs `OPENROUTER_API_KEY` and lets the model search the web through OpenRouter's web search tool, which costs extra per search. Both report a missing token in the channel instead of failing at startup. `!remindme` keeps pending reminders in the JSON file at `REMINDERS_PATH` (default `reminders.json` in the working directory) so they survive restarts. `docker-compose.yml` puts it on a volume and the NixOS module in its state directory.

## Architecture

Expand Down
195 changes: 195 additions & 0 deletions Sources/SwiftDEBot/Command/Message Commands/RemindMe.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
import DiscordBM
import Foundation

/// What a `!remindme` message asks for.
enum RemindMeRequest: Equatable {
static let minimumSeconds: Double = 30
static let maximumSeconds: Double = 30 * 86_400
static let maximumTextLength = 100

case list
case delete(number: Int)
case create(seconds: Double, text: String?)
/// The request cannot be fulfilled; the associated text tells the user why.
case invalid(String)

static let usage =
"Beispiele: `!remindme 2,5h Pizza aus dem Ofen`, `!remindme 10 min`, `!remindme 1h 30m Meeting`."

init(argument: String?) {
guard let argument else {
self = .list
return
}

let words = argument.split(whereSeparator: \.isWhitespace)
if let first = words.first, ["löschen", "loeschen", "delete"].contains(first.lowercased()) {
if words.count == 2, let number = Int(words[1]), number > 0 {
self = .delete(number: number)
} else {
self = .invalid("Gib die Nummer des Reminders an, z. B. `!remindme löschen 2`.")
}
return
}

guard let (seconds, rest) = parseLeadingDuration(argument) else {
self = .invalid("Ich verstehe die Dauer nicht. \(Self.usage)")
return
}
guard seconds >= Self.minimumSeconds else {
self = .invalid("Die Dauer muss mindestens 30 Sekunden betragen.")
return
}
guard seconds <= Self.maximumSeconds else {
self = .invalid("Die Dauer darf höchstens 30 Tage betragen.")
return
}
// Counted in scalars like Discord's message limit, since one visible character can be many of them.
guard rest.unicodeScalars.count <= Self.maximumTextLength else {
self = .invalid("Der Text darf höchstens \(Self.maximumTextLength) Zeichen lang sein.")
return
}
self = .create(seconds: seconds, text: rest.isEmpty ? nil : rest)
}
}

/// Who a due reminder pings: its author, then everyone who joined by reacting. Bots are skipped because the bot's own
/// reaction is among them.
func reminderRecipients(authorID: String, reactors: [DiscordUser]) -> [String] {
var recipients = [authorID]
for reactor in reactors where reactor.bot != true && !recipients.contains(reactor.id) {
recipients.append(reactor.id)
}
return recipients
}

/// The text of a delivered reminder. A reminder delivered more than a minute late says so.
func reminderDeliveryText(for reminder: Reminder, recipients: [String], now: Date) -> String {
let mentions = recipients.map { DiscordUtils.userMention(id: $0) }.joined(separator: " ")
var text = "⏰ \(mentions) Erinnerung"
text += reminder.text.map { ": \($0)" } ?? "!"
let delay = Int(now.timeIntervalSince(reminder.dueDate))
if delay > 60 {
text += " (verspätet um \(germanDurationDescription(seconds: delay)))"
}
if let url = reminder.referencedMessageURL {
text += "\n\(url)"
}
return text
}

/// The text listing a user's pending reminders. It spells out `Nr.` because Discord renders `2.` as a Markdown list and
/// renumbers it, while these numbers may be out of order.
func reminderListText(for reminders: [Reminder], now: Date) -> String {
guard !reminders.isEmpty else { return "Du hast keine offenen Reminder." }
let lines = reminders.map { reminder in
let remaining = germanDurationDescription(seconds: Int(reminder.dueDate.timeIntervalSince(now).rounded(.up)))
let link = reminder.referencedMessageURL.map { " \($0)" } ?? ""
return "Nr. \(reminder.number): in \(remaining) – \(reminder.text ?? "(ohne Text)")\(link)"
}
return "Deine Reminder:\n" + lines.joined(separator: "\n")
}

private let reminderEmoji = "⏰"

struct RemindMeCommand: MessageCommand {
let helpText =
"`!remindme <dauer> [text]`: Erinnert dich nach der Dauer, z. B. `!remindme 2,5h Pizza`. "
+ "Als Antwort verlinkt er die Nachricht, und wer mit ⏰ reagiert, wird mit erinnert. "
+ "`!remindme` listet deine Reminder, `!remindme löschen <nr>` löscht einen."

let store: ReminderStore

func run(client: DiscordClient, message: Gateway.MessageCreate) async throws {
guard let invocation = message.content.invocation(of: "!remindme"), let author = message.author else { return }

switch RemindMeRequest(argument: invocation.argument) {
case .list:
let text = reminderListText(for: await store.reminders(of: author.id), now: Date())
try await reply(text, to: message, client: client)
case .delete(let number):
let text: String
do {
let removed = try await store.remove(number: number, of: author.id) != nil
text = removed ? "Reminder \(number) gelöscht." : "Du hast keinen Reminder Nr. \(number)."
} catch {
text = "Ich konnte den Reminder nicht löschen, bitte versuch es später nochmal."
}
try await reply(text, to: message, client: client)
case .create(let seconds, let text):
let reminder = Reminder(
userID: author.id,
channelID: message.channel_id,
messageID: message.id,
guildID: message.guild_id,
referencedMessageID: message.type == .reply ? message.message_reference?.message_id : nil,
dueDate: Date().addingTimeInterval(seconds),
text: text
)
do {
try await store.add(reminder)
} catch ReminderStoreError.tooManyReminders {
try await reply(
"Du hast schon \(ReminderStore.maxRemindersPerUser) offene Reminder. "
+ "Mit `!remindme` siehst du sie, mit `!remindme löschen <nr>` löschst du einen.",
to: message, client: client)
return
} catch {
try await reply(
"Ich konnte den Reminder nicht speichern, bitte versuch es später nochmal.", to: message, client: client)
return
}
try await client.addReaction(.unicodeEmoji(reminderEmoji), to: message.id, in: message.channel_id).guardSuccess()
case .invalid(let explanation):
try await reply(explanation, to: message, client: client)
}
}

/// Replies without pinging anyone, since the text may repeat what users wrote.
private func reply(_ text: String, to message: Gateway.MessageCreate, client: DiscordClient) async throws {
try await client.createMessage(
channelId: message.channel_id,
payload: .init(
content: text,
allowed_mentions: .init(parse: [], roles: [], users: [], replied_user: false),
message_reference: .init(message_id: message.id, fail_if_not_exists: false)
)
).guardSuccess()
}
}

extension DiscordClient {
/// Delivers a due reminder as a reply to the message that set it, pinging only its recipients. If that message was
/// deleted, Discord sends it as a plain message instead.
func deliverReminder(_ reminder: Reminder) async throws {
let recipients = reminderRecipients(authorID: reminder.userID, reactors: await reminderReactors(of: reminder))
try await createMessage(
channelId: reminder.channelID,
payload: .init(
content: reminderDeliveryText(for: reminder, recipients: recipients, now: Date()),
allowed_mentions: .init(parse: [], roles: [], users: recipients, replied_user: true),
message_reference: .init(
message_id: reminder.messageID,
channel_id: reminder.channelID,
guild_id: reminder.guildID,
fail_if_not_exists: false
)
)
).guardSuccess()
}

/// Reads the reactions only at delivery, so taking one back or reacting while the bot is down just works and nothing
/// needs storing. DiscordBM drops the `limit` parameter, so this sees at most Discord's default of 25 users, which
/// also keeps the mentions within the message length limit. Failing to read them, for example because the message
/// was deleted, only narrows the reminder to its author.
private func reminderReactors(of reminder: Reminder) async -> [DiscordUser] {
do {
return try await listMessageReactionsByEmoji(
channelId: reminder.channelID, messageId: reminder.messageID, emoji: .unicodeEmoji(reminderEmoji)
).decode()
} catch {
log.warning("Could not read reactions for reminder \(reminder.id): \(error)")
return []
}
}
}
1 change: 1 addition & 0 deletions Sources/SwiftDEBot/Commands.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ let messageCommands: [MessageCommand] = [
SPICommand(),
SummarizeCommand(),
FactCheckCommand(),
RemindMeCommand(store: reminderStore),

CowsCommand(),

Expand Down
78 changes: 78 additions & 0 deletions Sources/SwiftDEBot/Utils/DurationParsing.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import Foundation

/// Seconds per duration unit, keyed by every spelling `parseLeadingDuration` accepts in lowercase.
private let unitSeconds: [String: Double] = {
let units: [(spellings: [String], seconds: Double)] = [
(["s", "sek", "sekunde", "sekunden"], 1),
(["m", "min", "minute", "minuten"], 60),
(["h", "std", "stunde", "stunden"], 3_600),
(["d", "t", "tag", "tage"], 86_400),
]
var table: [String: Double] = [:]
for unit in units {
for spelling in unit.spellings { table[spelling] = unit.seconds }
}
return table
}()

/// Reads a duration such as `2,5h`, `10 minuten` or `1h 30m` from the start of `text`. It reads as many number-unit
/// pairs as it can and returns their total with the remaining text, trimmed. A number needs a unit, and the unit must
/// be a whole word, so `10 Tee` and `5mal` are no durations. Decimals may use a comma or a point.
func parseLeadingDuration(_ text: String) -> (seconds: Double, rest: String)? {
var index = text.startIndex
var total: Double = 0
var foundComponent = false

func skipWhitespace(_ index: inout String.Index) {
while index < text.endIndex, text[index].isWhitespace { index = text.index(after: index) }
}

func scan(_ index: inout String.Index, while predicate: (Character) -> Bool) -> Substring {
let start = index
while index < text.endIndex, predicate(text[index]) { index = text.index(after: index) }
return text[start..<index]
}

while true {
var cursor = index
skipWhitespace(&cursor)

let isDigit: (Character) -> Bool = { $0.isASCII && $0.isNumber }
var number = String(scan(&cursor, while: isDigit))
guard !number.isEmpty else { break }
if cursor < text.endIndex, text[cursor] == "," || text[cursor] == "." {
var afterSeparator = text.index(after: cursor)
let fraction = scan(&afterSeparator, while: isDigit)
if !fraction.isEmpty {
number += "." + fraction
cursor = afterSeparator
}
}

skipWhitespace(&cursor)
let unit = scan(&cursor, while: \.isLetter).lowercased()
guard let seconds = unitSeconds[unit], let value = Double(number) else { break }

total += value * seconds
foundComponent = true
index = cursor
}

guard foundComponent else { return nil }
return (total, text[index...].trimmingCharacters(in: .whitespacesAndNewlines))
}

/// Describes a duration in German for people, such as `2 Std 14 Min` or `45 Sek`. It shows at most the two largest
/// non-zero units, and seconds only below ten minutes.
func germanDurationDescription(seconds: Int) -> String {
let total = max(seconds, 0)
let parts: [(value: Int, unit: String)] = [
(total / 86_400, total / 86_400 == 1 ? "Tag" : "Tage"),
(total % 86_400 / 3_600, "Std"),
(total % 3_600 / 60, "Min"),
(total < 600 ? total % 60 : 0, "Sek"),
]
let shown = parts.drop { $0.value == 0 }.prefix(2).filter { $0.value > 0 }
guard !shown.isEmpty else { return "0 Sek" }
return shown.map { "\($0.value) \($0.unit)" }.joined(separator: " ")
}
Loading
Loading