Skip to content

Commit

Permalink
feat: migrate to Deno (#219)
Browse files Browse the repository at this point in the history
Co-authored-by: Dunkan <[email protected]>
Co-authored-by: Arnab Paryali <[email protected]>
  • Loading branch information
3 people committed Jul 21, 2022
1 parent 408474d commit 2597dd8
Show file tree
Hide file tree
Showing 52 changed files with 1,361 additions and 11,332 deletions.
5 changes: 0 additions & 5 deletions .commitlintrc

This file was deleted.

19 changes: 0 additions & 19 deletions .eslintrc

This file was deleted.

42 changes: 10 additions & 32 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,63 +5,41 @@ on:
branches-ignore:
- gh-pages
paths-ignore:
- '**.md'
- "**.md"
tags:
- '*'
- "*"

jobs:
lint:
runs-on: ubuntu-latest
if: "!contains(github.event.head_commit.message, '#skip-lint')"
steps:
- uses: actions/checkout@v3

- uses: actions/setup-node@v3
- uses: denoland/setup-deno@v1
with:
cache: npm
node-version: '17.x'
deno-version: vx.x.x

- run: npm ci
- run: deno lint

- run: npm run lint

build:
fmt:
runs-on: ubuntu-latest
needs: lint
if: "!contains(github.event.head_commit.message, '#skip-build')"
steps:
- uses: actions/checkout@v3

- uses: actions/setup-node@v3
- uses: denoland/setup-deno@v1
with:
cache: npm
node-version: '17.x'

- run: npm ci
deno-version: vx.x.x

- run: npm run build
- run: deno fmt --check

release:
runs-on: ubuntu-latest
needs: build
needs: fmt
if: startsWith(github.ref, 'refs/tags/')
steps:
- uses: actions/checkout@v3

- uses: actions/setup-node@v3
with:
cache: npm
node-version: '17.x'

- run: npm ci

- run: npm run build

- run: |
ARCHIVE=$(npm pack)
mv $ARCHIVE archive.tgz
- uses: softprops/action-gh-release@v1
with:
files: archive.tgz
generate_release_notes: true
5 changes: 2 additions & 3 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
.env
dist/
externals/
node_modules/
downloads/
downloads/
test*
4 changes: 0 additions & 4 deletions .husky/commit-msg

This file was deleted.

4 changes: 0 additions & 4 deletions .husky/pre-commit

This file was deleted.

7 changes: 0 additions & 7 deletions .npmignore

This file was deleted.

10 changes: 0 additions & 10 deletions .prettierrc

This file was deleted.

4 changes: 4 additions & 0 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"deno.enable": true,
"deno.importMap": "./import_map.json"
}
1 change: 1 addition & 0 deletions constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export const version = "0.0.8";
6 changes: 6 additions & 0 deletions deno.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"importMap": "./import_map.json",
"tasks": {
"run": "deno run -A main.ts"
}
}
11 changes: 11 additions & 0 deletions deps.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Internal dependencies
export { config } from "https://deno.land/[email protected]/dotenv/mod.ts";
export { cleanEnv, num, str } from "https://deno.land/x/[email protected]/mod.ts";
export {
dirname,
fromFileUrl,
join,
resolve,
toFileUrl,
} from "https://deno.land/[email protected]/path/mod.ts";
export * from "https://deno.land/x/[email protected]/mod.ts";
9 changes: 9 additions & 0 deletions env.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import { cleanEnv, config, num, str } from "./deps.ts";

await config({ export: true });

export default cleanEnv(Deno.env.toObject(), {
STRING_SESSION: str(),
APP_ID: num(),
APP_HASH: str(),
});
71 changes: 71 additions & 0 deletions handlers/command_handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
import { HandlerFuncParams } from "./handler.ts";
import { MessageHandler } from "./message_handler.ts";

export interface CommandHandlerFuncParams {
args: string[];
input: string;
}

// deno-lint-ignore ban-types
export type CommandHandlerFunc<T extends object> = ({
client,
event,
...rest
}: HandlerFuncParams & T) => Promise<void>;

export interface CommandHandlerOpts {
aliases?: string[];
rawArgs?: boolean;
rawInput?: boolean;
}

export class CommandHandler extends MessageHandler<CommandHandlerFuncParams> {
opts: CommandHandlerOpts;

constructor(
public name: string,
public func: CommandHandlerFunc<CommandHandlerFuncParams>,
opts?: CommandHandlerOpts,
) {
super(func);
this.opts = opts ?? {};
this.opts.rawInput = this.opts.rawInput ?? true;
}

async check({ client, event }: HandlerFuncParams) {
if (!(await super.check({ client, event }))) {
return false;
}
const { text } = event.message;
if (!["\\", ">"].includes(text[0])) {
return false;
}
const command = text.split(/\s/)[0].slice(1);
return this.name == command || !!this.opts?.aliases?.includes(command);
}

async handle({ client, event }: HandlerFuncParams) {
const { text, message } = event.message;
const args = (this.opts?.rawArgs ? message : text)
.split("\n")[0]
.split(/\s/)
.slice(1);
let input = "";
const inputType = message[0];
const reply = await event.message.getReplyMessage();
switch (inputType) {
case "\\":
input = (this.opts?.rawInput ? message : text)
.split("\n")
.slice(1)
.join("\n")
.trim();
break;
case ">":
if (reply && reply.text) {
input = this.opts?.rawInput ? reply.message : reply.text;
}
}
await this.func({ client, event, args, input });
}
}
14 changes: 14 additions & 0 deletions handlers/handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { NewMessageEvent, TelegramClient } from "$grm";

export interface HandlerFuncParams {
client: TelegramClient;
event: NewMessageEvent;
}

export abstract class Handler {
abstract check(
{ client, event }: HandlerFuncParams,
): Promise<boolean> | boolean;

abstract handle({ client, event }: HandlerFuncParams): Promise<void>;
}
46 changes: 46 additions & 0 deletions handlers/message_handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Handler, HandlerFuncParams } from "./handler.ts";

// deno-lint-ignore ban-types
export type MessageHandlerFunc<T extends object> = ({
client,
event,
...rest
}: HandlerFuncParams & T) => Promise<void>;

// deno-lint-ignore ban-types
export class MessageHandler<T extends object> extends Handler {
out?: boolean;
scope?: "all" | "group" | "private" | "channel";
allowForward?: boolean;

constructor(public func: MessageHandlerFunc<T>) {
super();
}

// deno-lint-ignore require-await
async check({ event }: HandlerFuncParams) {
if (this.out !== undefined && this.out !== event.message.out) {
return false;
}
if (!event.message.out) {
return false;
}
if (this.allowForward != false && event.message.forward !== undefined) {
return false;
}
if (this.scope !== undefined && this.scope !== "all") {
if (this.scope == "group" && !event.isGroup) {
return false;
} else if (this.scope == "private" && !event.isPrivate) {
return false;
} else if (!event.isChannel) {
return false;
}
}
return true;
}

handle({ client, event, ...rest }: HandlerFuncParams & T) {
return this.func({ client, event, ...(rest as T) });
}
}
3 changes: 3 additions & 0 deletions handlers/mod.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export * from "./handler.ts";
export * from "./message_handler.ts";
export * from "./command_handler.ts";
47 changes: 47 additions & 0 deletions helpers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
// This file will include helpers for all modules (built-in and externals).
import { CustomFile, NewMessageEvent, SendMessageParams } from "$grm";
import { Buffer } from "$grm-deps";
import { fmt, pre, type Stringable } from "./deps.ts";

export async function wrap(
event: NewMessageEvent,
func: () => Promise<void>,
) {
try {
await func();
} catch (err) {
console.error(err);
try {
let message = String(err);
message = message.length <= 1000 ? message : "An error occurred.";
await event.message.reply({ message });
} catch (_err) {
//
}
}
}

export async function updateMessage(
event: NewMessageEvent,
text: Stringable,
) {
return await event.message.edit(
fmt`${event.message.text}\n${text}`.edit,
);
}

export function longText(
text: string,
name?: string,
): SendMessageParams {
return text.length > 4096
? {
file: new CustomFile(
name ?? crypto.randomUUID(),
text.length,
"",
Buffer.from(text),
),
}
: pre(text.trim(), "").send;
}
7 changes: 7 additions & 0 deletions import_map.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"imports": {
"$grm": "https://deno.land/x/[email protected]/mod.ts",
"$grm-deps": "https://deno.land/x/[email protected]/deps.ts",
"$xor": "./xor.ts"
}
}
28 changes: 28 additions & 0 deletions main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { NewMessage, StringSession, TelegramClient } from "$grm";
import { dirname, fromFileUrl, join } from "./deps.ts";
import env from "./env.ts";
import { managerModule, ModuleManager } from "./module_manager.ts";

const client = new TelegramClient(
new StringSession(env.STRING_SESSION),
env.APP_ID,
env.APP_HASH,
{ logLevel: "none" },
);
const manager = new ModuleManager(client);
client.setParseMode(undefined);
try {
await Deno.mkdir("externals");
} catch (_err) {
//
}
manager.installMultiple(
await ModuleManager.directory(
join(dirname(fromFileUrl(import.meta.url)), "modules"),
),
false,
);
manager.install(managerModule(manager), false);
manager.installMultiple(await ModuleManager.directory("externals"), true);
client.addEventHandler(manager.handler, new NewMessage({}));
client.start();
Loading

0 comments on commit 2597dd8

Please sign in to comment.