time zone shit sucks

This commit is contained in:
Julian 2023-08-15 17:32:24 -04:00
parent 62dcf651cc
commit 137456a1d8
Signed by: NotNite
GPG Key ID: BD91A5402CCEB08A
15 changed files with 1377 additions and 142 deletions

View File

@ -1,6 +1,6 @@
MIT License MIT License
Copyright (c) 2022 NotNite Copyright (c) 2023 NotNet
Permission is hereby granted, free of charge, to any person obtaining a copy Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal of this software and associated documentation files (the "Software"), to deal

1096
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -1,28 +1,26 @@
{ {
"name": "violet", "name": "violet",
"version": "1.0.0", "description": "everyone's favorite discord robot friend",
"description": "", "author": "NotNet",
"license": "MIT",
"main": "dist/index.js", "main": "dist/index.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1" "prisma-migrate": "prisma migrate deploy",
}, "prisma-generate": "prisma generate",
"keywords": [], "build": "tsc"
"author": "NotNite",
"license": "MIT",
"devDependencies": {
"@types/bunyan": "^1.8.8",
"@types/node": "^18.7.10",
"prisma": "^4.2.1",
"typescript": "^4.7.4"
}, },
"dependencies": { "dependencies": {
"@prisma/client": "^4.2.1", "@prisma/client": "^4.2.1",
"eris": "^0.17.1", "@projectdysnomia/dysnomia": "github:projectdysnomia/dysnomia#dev",
"chrono-node": "^2.6.4",
"parse-duration": "^1.0.2", "parse-duration": "^1.0.2",
"pino": "^8.4.2", "pino": "^8.4.2",
"pino-pretty": "^9.1.0" "pino-pretty": "^9.1.0",
"timezone-support": "^3.1.0"
}, },
"scripts": { "devDependencies": {
"build": "prisma generate && tsc" "@types/node": "^18.7.10",
"prisma": "^4.2.1",
"typescript": "^4.7.4"
} }
} }

View File

@ -0,0 +1,5 @@
-- CreateTable
CREATE TABLE "Timezone" (
"user" TEXT NOT NULL PRIMARY KEY,
"tz" TEXT
);

View File

@ -18,3 +18,8 @@ model Reminder {
sendAt DateTime sendAt DateTime
message String? message String?
} }
model Timezone {
user String @id
tz String?
}

View File

@ -1,4 +1,7 @@
import { ApplicationCommandOptions, CommandInteraction } from "eris"; import {
ApplicationCommandOptions,
CommandInteraction
} from "@projectdysnomia/dysnomia";
type Command = { type Command = {
name: string; name: string;

View File

@ -3,11 +3,13 @@ import Command from "./command";
import ping from "./ping"; import ping from "./ping";
import remind from "./remind"; import remind from "./remind";
import reminders from "./reminders"; import reminders from "./reminders";
import timezone from "./timezone";
const commands: { [key: string]: Command } = { const commands: { [key: string]: Command } = {
ping, ping,
remind, remind,
reminders reminders,
timezone
}; };
export default commands; export default commands;

View File

@ -3,8 +3,11 @@ import Command from "./command";
import db from "../things/db"; import db from "../things/db";
import bot from "../things/bot"; import bot from "../things/bot";
import { Constants, InteractionDataOptionsString } from "eris"; import {
import parse from "parse-duration"; Constants,
InteractionDataOptionsString
} from "@projectdysnomia/dysnomia";
import * as chrono from "chrono-node";
import logger from "../things/logger"; import logger from "../things/logger";
import { import {
@ -12,6 +15,23 @@ import {
unravelOption, unravelOption,
unravelOptionalOption unravelOptionalOption
} from "../utils/options"; } from "../utils/options";
import { getCurrentOffset, getTimeOffsetFor } from "../utils/time";
function parse(str: string, offset: number) {
const when = chrono.parse(
str,
{
instant: new Date(),
timezone: offset
},
{
forwardDate: true
}
);
if (when.length <= 0) return null;
return when[0].start.date();
}
const remind: Command = { const remind: Command = {
name: "remind", name: "remind",
@ -31,7 +51,7 @@ const remind: Command = {
], ],
command: async (interaction) => { command: async (interaction) => {
// i love abusing types // i love abusing types
const options = interaction.data.options!; const options = interaction.data.options ?? [];
const whenOption = unravelOption<InteractionDataOptionsString>( const whenOption = unravelOption<InteractionDataOptionsString>(
"when", "when",
options options
@ -40,31 +60,36 @@ const remind: Command = {
Optional<InteractionDataOptionsString> Optional<InteractionDataOptionsString>
>("what", options); >("what", options);
const when = parse(whenOption.value); const user = (interaction.member || interaction.user)!.id;
const what = whatOption?.value; const now = new Date();
if (when === null) { const offset = (await getTimeOffsetFor(user)) ?? 0;
const when = parse(whenOption.value, offset);
if (when == null) {
let msg =
":warning: I didn't understand that time. Try something like `3h` or `2 days`.";
if (offset != 0) {
msg += "\nNote: This may be a bug due to your set time zone.";
}
await interaction.createMessage({ await interaction.createMessage({
content: content: msg,
"I didn't understand that time. Try something like `3h` or `2 days`.",
flags: Constants.MessageFlags.EPHEMERAL flags: Constants.MessageFlags.EPHEMERAL
}); });
return; return;
} }
const sendAt = new Date(Date.now() + when);
await db.reminder.create({ await db.reminder.create({
data: { data: {
user: (interaction.member || interaction.user)!.id, user,
createdAt: new Date(), createdAt: now,
sendAt, sendAt: when,
message: what message: whatOption?.value
} }
}); });
await interaction.createMessage({ await interaction.createMessage({
content: `Reminder set <t:${Math.floor(sendAt.getTime() / 1000)}:R>.`, content: `Reminder set <t:${Math.floor(when.getTime() / 1000)}:R>.`,
flags: Constants.MessageFlags.EPHEMERAL flags: Constants.MessageFlags.EPHEMERAL
}); });
} }

View File

@ -7,7 +7,7 @@ import {
Constants, Constants,
InteractionDataOptionsNumber, InteractionDataOptionsNumber,
InteractionDataOptionsSubCommand InteractionDataOptionsSubCommand
} from "eris"; } from "@projectdysnomia/dysnomia";
import { import {
Optional, Optional,

100
src/commands/timezone.ts Normal file
View File

@ -0,0 +1,100 @@
import {
CommandInteraction,
Constants,
InteractionDataOptionsString,
TextableChannel
} from "@projectdysnomia/dysnomia";
import Command from "./command";
import { findTimeZone } from "timezone-support";
import { getTimeFor, updateTimeFor } from "../utils/time";
import { Optional, unravelOptionalOption } from "../utils/options";
async function failMessage(interaction: CommandInteraction<TextableChannel>) {
await interaction.createMessage({
content:
":warning: I didn't understand that time zone. Try an [IANA time zone code](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).",
flags: Constants.MessageFlags.EPHEMERAL
});
}
const timezone: Command = {
name: "timezone",
description: "Set your time zone.",
options: [
{
name: "tz",
description:
"The time zone from the IANA time zone database - e.g. 'America/New_York'.",
type: Constants.ApplicationCommandOptionTypes.STRING
}
],
command: async (interaction) => {
const options = interaction.data.options ?? [];
const tzOption = unravelOptionalOption<
Optional<InteractionDataOptionsString>
>("tz", options);
const user = (interaction.member || interaction.user)!.id;
if (tzOption == null) {
const worked = await updateTimeFor(user, null);
if (!worked) {
await failMessage(interaction);
return;
}
await interaction.createMessage({
content: ":white_check_mark: Unset your time zone.",
flags: Constants.MessageFlags.EPHEMERAL
});
return;
}
let tz: string;
try {
tz = findTimeZone(tzOption.value).name;
} catch (err) {
await failMessage(interaction);
return;
}
const worked = await updateTimeFor(user, tz);
if (!worked) {
await failMessage(interaction);
return;
}
const time = await getTimeFor(user);
if (time == null) {
await failMessage(interaction);
return;
}
const hour = time.getHours();
const minutes = time.getMinutes();
const amPM = hour >= 12 ? "PM" : "AM";
const hourStr = hour % 12 || 12;
const minutesStr = minutes.toString().padStart(2, "0");
const timeStr = `${hourStr}:${minutesStr} ${amPM}`;
let greetingStr = "morning";
if (hour >= 12 && hour < 18) {
greetingStr = "afternoon";
} else if (hour >= 18 && hour < 22) {
greetingStr = "evening";
} else if (hour >= 22 || hour < 4) {
greetingStr = "night";
}
await interaction.createMessage({
content: `:white_check_mark: Good ${greetingStr}! It's ${timeStr} for you.`,
flags: Constants.MessageFlags.EPHEMERAL
});
}
};
export default timezone;

View File

@ -3,7 +3,7 @@ import logger from "./things/logger";
import bot from "./things/bot"; import bot from "./things/bot";
import commands from "./commands/index"; import commands from "./commands/index";
import Eris, { Constants } from "eris"; import { Constants, CommandInteraction } from "@projectdysnomia/dysnomia";
bot.on("ready", () => { bot.on("ready", () => {
const cmds = Object.values(commands).map((x) => { const cmds = Object.values(commands).map((x) => {
@ -35,7 +35,7 @@ bot.on("ready", () => {
bot.on("interactionCreate", async (interaction) => { bot.on("interactionCreate", async (interaction) => {
logger.debug(`Handling interaction ${interaction.id}`); logger.debug(`Handling interaction ${interaction.id}`);
if (interaction instanceof Eris.CommandInteraction) { if (interaction instanceof CommandInteraction) {
const commandName = interaction.data.name; const commandName = interaction.data.name;
const command = commands[commandName]; const command = commands[commandName];
if (command) { if (command) {
@ -48,7 +48,7 @@ bot.on("interactionCreate", async (interaction) => {
); );
await interaction.createMessage({ await interaction.createMessage({
content: ":warn: Something went wrong running this command.", content: ":warning: Something went wrong running this command.",
flags: Constants.MessageFlags.EPHEMERAL flags: Constants.MessageFlags.EPHEMERAL
}); });
} }
@ -59,7 +59,7 @@ bot.on("interactionCreate", async (interaction) => {
}); });
bot.on("error", (e) => { bot.on("error", (e) => {
logger.error("Error in bot", e); logger.error(e, "Error in bot");
}); });
bot.connect(); bot.connect();

View File

@ -1,9 +1,11 @@
import Eris from "eris"; import { Client, Constants } from "@projectdysnomia/dysnomia";
import config from "./config"; import config from "./config";
const bot = new Eris.Client("Bot " + config.token, { const bot = new Client("Bot " + config.token, {
restMode: true, restMode: true,
intents: Eris.Constants.Intents.allNonPrivileged gateway: {
intents: Constants.Intents.allNonPrivileged
}
}); });
export default bot; export default bot;

View File

@ -1,4 +1,4 @@
import { InteractionDataOptions, InteractionDataOptionsSubCommand } from "eris"; import { InteractionDataOptions } from "@projectdysnomia/dysnomia";
export type Optional<T> = T | undefined; export type Optional<T> = T | undefined;

91
src/utils/time.ts Normal file
View File

@ -0,0 +1,91 @@
import { findTimeZone, getUTCOffset } from "timezone-support";
import db from "../things/db";
export function getCurrentOffset() {
// negative offset = west
return -new Date().getTimezoneOffset();
}
export async function updateTimeFor(
user: string,
tzName: string | null
): Promise<boolean> {
if (tzName == null) {
await db.timezone.upsert({
where: { user },
create: { user, tz: null },
update: { tz: null }
});
return true;
}
try {
const tz = findTimeZone(tzName).name;
await db.timezone.upsert({
where: { user },
create: { user, tz },
update: { tz }
});
return true;
} catch (err) {
return false;
}
}
export async function getTimeNameFor(user: string): Promise<string | null> {
try {
const lookup = await db.timezone.findUnique({
where: {
user
}
});
const tzName = lookup?.tz;
if (tzName == null) return null;
const tz = findTimeZone(tzName);
return tz.name;
} catch (err) {
return null;
}
}
export async function getTimeOffsetFor(user: string): Promise<number | null> {
try {
const lookup = await db.timezone.findUnique({
where: {
user
}
});
const tzName = lookup?.tz;
if (tzName == null) return null;
const tz = findTimeZone(tzName);
const offsetObj = getUTCOffset(new Date(), tz);
return -offsetObj.offset;
} catch (err) {
return 0;
}
}
export async function getTimeFor(user: string): Promise<Date | null> {
try {
const tzName = await getTimeNameFor(user);
if (tzName == null) return null;
const now = new Date();
const tz = findTimeZone(tzName);
const offsetMinutes = getUTCOffset(now, tz).offset;
const offsetMs = offsetMinutes * 60 * 1000;
const nowOffset = getCurrentOffset() * 60 * 1000;
return new Date(now.getTime() - offsetMs - nowOffset);
} catch (err) {
return null;
}
}

View File

@ -1,103 +1,11 @@
{ {
"compilerOptions": { "compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */ "target": "es2016",
"module": "commonjs",
/* Projects */ "outDir": "./dist/",
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ "esModuleInterop": true,
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ "forceConsistentCasingInFileNames": true,
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ "strict": true,
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ "skipLibCheck": true
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */
"target": "es2016", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */
"module": "commonjs", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */
// "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
// "types": [], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
"outDir": "./dist/", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */
} }
} }