hackmud-chat
Version:
A hackmud chat api wrapper for nodejs.
99 lines • 3.21 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
const Debug = require("debug");
const request = require("request-promise-native");
const account_1 = require("./account");
const channel_1 = require("./channel");
const constants_1 = require("./constants");
const user_1 = require("./user");
const debug = Debug("hackmud-chat:client");
/**
* The main class, used by all other classes.
*/
class HackmudApi {
constructor(token) {
/**
* The token to be used with the api.
*/
this.token = "";
if (token) {
this.token = token;
}
}
async request(endpoint, json) {
return await request.post(constants_1.API_URL + endpoint, { json });
}
async getToken(pass) {
if (pass.length > 5) {
throw new Error("You passed a token to getToken, and you should pass a password (5 chars)");
}
const body = await this.request(constants_1.ENDPOINTS.GET_TOKEN, { pass });
if (body.ok) {
debug("Token is:", body.chat_token);
this.token = body.chat_token;
return body.chat_token;
}
else {
throw new Error(body);
}
}
async getAccountData() {
const body = await this.request(constants_1.ENDPOINTS.ACCOUNT_DATA, { chat_token: this.token });
if (body.ok) {
const users = [];
for (const ownUser in body.users) {
if (ownUser) {
const channels = [];
for (const channelName in body.users[ownUser]) {
if (channelName) {
channels.push(new channel_1.Channel(this, channelName, body.users[ownUser][channelName], ownUser));
}
}
users.push(new user_1.User(this, ownUser, channels));
}
}
return new account_1.Account(this, users);
}
else {
throw new Error(body);
}
}
async sendChannel(channel, user, msg) {
const body = await this.request(constants_1.ENDPOINTS.CREATE_CHAT, {
chat_token: this.token,
username: user,
channel,
msg,
});
if (!body.ok) {
throw new Error(body);
}
}
async sendMessage(user, toUser, msg) {
const body = await this.request(constants_1.ENDPOINTS.ACCOUNT_DATA, {
chat_token: this.token,
username: user,
tell: toUser,
msg,
});
if (!body.ok) {
throw new Error(body);
}
}
async getChats(users, after, before) {
const body = await this.request(constants_1.ENDPOINTS.CHATS, {
chat_token: this.token,
usernames: users,
before,
after,
});
if (!body.ok) {
throw new Error(body);
}
else {
return body;
}
}
}
exports.HackmudApi = HackmudApi;
//# sourceMappingURL=hackmud.api.js.map
;