Skip to content

Commit

Permalink
Merge pull request #79 from erictik/new-ws
Browse files Browse the repository at this point in the history
use websocket-ts
  • Loading branch information
zcpua authored Jun 4, 2023
2 parents bc75880 + bb8b000 commit 4385039
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 50 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/releases.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: Node.js Package
env:
APPVERSION: v2.3.${{ github.run_number }}
APPVERSION: v2.4.${{ github.run_number }}
on:
workflow_dispatch:
push:
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "midjourney",
"version": "2.3.0",
"version": "2.4.0",
"description": "Node.js client for the unofficial MidJourney API.",
"main": "libs/index.js",
"types": "libs/index.d.ts",
Expand Down Expand Up @@ -48,7 +48,7 @@
"snowyflake": "^2.0.0",
"throat": "^6.0.2",
"tslib": "^2.5.0",
"ws": "^8.13.0",
"isomorphic-ws": "^5.0.0"
"websocket-ts": "^1.1.1",
"ws": "^8.13.0"
}
}
82 changes: 42 additions & 40 deletions src/ws.message.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import WebSocket from "isomorphic-ws";
import {
MessageConfig,
MessageConfigParam,
Expand All @@ -9,11 +8,12 @@ import {
WsEventMsg,
} from "./interfaces";
import { VerifyHuman } from "./verify.human";
import { WebsocketBuilder, Websocket } from "websocket-ts";
import WebSocket from "ws";

export class WsMessage {
ws: WebSocket;
ws: Websocket;
MJBotId = "936929561302675456";
private zlibChunks: Buffer[] = [];
public config: MessageConfig;
private event: Array<{ event: string; callback: (message: any) => void }> =
[];
Expand All @@ -32,21 +32,34 @@ export class WsMessage {
...DefaultMessageConfig,
...defaults,
};
this.DISCORD_GATEWAY=`${this.config.WsBaseUrl}/?v=9&encoding=json&compress=gzip-stream`
this.ws = new WebSocket(this.DISCORD_GATEWAY, {});
this.ws.on("open", this.open.bind(this));
}

private reconnect() {
//reconnect
this.zlibChunks = [];
this.ws = new WebSocket(this.DISCORD_GATEWAY);
this.ws.on("open", this.open.bind(this));
this.DISCORD_GATEWAY = `${this.config.WsBaseUrl}/?v=9&encoding=json&compress=gzip-stream`;
if (typeof global !== "undefined") {
// @ts-ignore
(global as any).WebSocket = WebSocket;
}
this.ws = new WebsocketBuilder(this.DISCORD_GATEWAY)
.onOpen((i, e) => {
console.log("opened");
this.open();
})
.onClose((i, ev) => {
console.log("closed");
})
.onError((i, ev) => {
console.log("error");
})
.onMessage((i, e) => {
this.parseMessage(e.data);
})
.onRetry((i, ev) => {
console.log("retry");
this.auth();
})
.build();
}

private async heartbeat(num: number) {
if (this.reconnectTime[num]) return;
if (this.ws.readyState !== WebSocket.OPEN) return;
this.heartbeatInterval++;
this.ws.send(
JSON.stringify({
Expand All @@ -60,14 +73,14 @@ export class WsMessage {
// After opening ws
private async open() {
const num = this.reconnectTime.length;
this.log("open", num);
this.reconnectTime.push(false);
// this.log("open", num);
// this.reconnectTime.push(false);
this.auth();
this.ws.on("message", this.incomingMessage.bind(this));
this.ws.onclose = () => {
this.reconnectTime[num] = true;
this.reconnect();
};
// this.ws.on("message", this.incomingMessage.bind(this));
// this.ws.onclose = () => {
// this.reconnectTime[num] = true;
// this.reconnect();
// };
setTimeout(() => {
this.heartbeat(num);
}, 1000 * 10);
Expand All @@ -93,10 +106,6 @@ export class WsMessage {
async timeout(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
private incomingMessage(data: Buffer) {
this.parseMessage(data);
}

private async messageCreate(message: any) {
// this.log("messageCreate", message);
const { application_id, embeds, id, nonce } = message;
Expand Down Expand Up @@ -163,9 +172,9 @@ export class WsMessage {
}

// parse message from ws
private parseMessage(data: Buffer) {
var jsonString = data.toString();
const msg = JSON.parse(jsonString);
private parseMessage(data: string) {
const msg = JSON.parse(data);
// this.log("parseMessage333", msg.t, msg.d);
if (msg.t === null || msg.t === "READY_SUPPLEMENTAL") return;
if (msg.t === "READY") {
this.emit("ready", null);
Expand All @@ -174,16 +183,7 @@ export class WsMessage {
if (!(msg.t === "MESSAGE_CREATE" || msg.t === "MESSAGE_UPDATE")) return;

const message = msg.d;
const {
channel_id,
content,
application_id,
embeds,
id,
nonce,
author,
attachments,
} = message;
const { channel_id, content, id, nonce, author } = message;
if (!(author && author.id === this.MJBotId)) return;
if (channel_id !== this.config.ChannelId) return;
this.log("has message", content, nonce, id);
Expand Down Expand Up @@ -248,11 +248,13 @@ export class WsMessage {
"Content-Type": "application/json",
Authorization: this.config.SalaiToken,
};
const response = await fetch(`${this.config.DiscordBaseUrl}/api/v9/interactions`,{
const response = await fetch(
`${this.config.DiscordBaseUrl}/api/v9/interactions`,
{
method: "POST",
body: JSON.stringify(payload),
headers: headers,
},
}
);
callback && callback(response.status);
//discord api rate limit
Expand Down
8 changes: 7 additions & 1 deletion test/test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import "dotenv/config";
import { Midjourney } from "../src";
import { Midjourney, WsMessage } from "../src";
import { nextNonce } from "../src/utls";
/**
*
Expand All @@ -12,5 +12,11 @@ import { nextNonce } from "../src/utls";
function test2() {
console.log(nextNonce());
console.log(nextNonce());

new WsMessage({
ChannelId: <string>process.env.CHANNEL_ID,
SalaiToken: <string>process.env.SALAI_TOKEN,
Debug: true,
});
}
test2();
10 changes: 5 additions & 5 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -281,11 +281,6 @@ get-tsconfig@^4.4.0:
resolved "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.5.0.tgz"
integrity sha512-MjhiaIWCJ1sAU4pIQ5i5OfOuHHxVo1oYeNsWTON7jxYkod8pHocXeh+SSbmu5OZZZK73B6cbJ2XADzXehLyovQ==

isomorphic-ws@^5.0.0:
version "5.0.0"
resolved "https://registry.npmjs.org/isomorphic-ws/-/isomorphic-ws-5.0.0.tgz#e5529148912ecb9b451b46ed44d53dae1ce04bbf"
integrity sha512-muId7Zzn9ywDsyXgTIafTry2sV3nySZeUDe6YedVd1Hvuuep5AsIlqK+XefWpYTyJG5e503F2xIuT2lcU6rCSw==

make-error@^1.1.1:
version "1.3.6"
resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2"
Expand Down Expand Up @@ -384,6 +379,11 @@ v8-compile-cache-lib@^3.0.1:
resolved "https://registry.yarnpkg.com/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz#6336e8d71965cb3d35a1bbb7868445a7c05264bf"
integrity sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==

websocket-ts@^1.1.1:
version "1.1.1"
resolved "https://registry.yarnpkg.com/websocket-ts/-/websocket-ts-1.1.1.tgz#de482da5e0c714ebc58a43fe94157e5a855f2828"
integrity sha512-rm+S60J74Ckw5iizzgID12ju+OfaHAa6dhXhULIOrXkl0e05RzxfY42/vMStpz5jWL3iz9mkyjPcFUY1IgI0fw==

ws@^8.13.0:
version "8.13.0"
resolved "https://registry.npmjs.org/ws/-/ws-8.13.0.tgz#9a9fb92f93cf41512a0735c8f4dd09b8a1211cd0"
Expand Down

0 comments on commit 4385039

Please sign in to comment.