qq-guild-bot
Version:
1,829 lines (1,547 loc) • 71.6 kB
JavaScript
import resty from 'resty-client';
import WebSocket, { EventEmitter } from 'ws';
function _classCallCheck(instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
}
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
var versionMapping = Object.create(null);
function register(version, api) {
versionMapping[version] = api;
}
var apiMap = {
guildURI: '/guilds/:guildID',
guildMembersURI: '/guilds/:guildID/members',
guildMemberURI: '/guilds/:guildID/members/:userID',
channelsURI: '/guilds/:guildID/channels',
channelURI: '/channels/:channelID',
guildAnnouncesURI: '/guilds/:guildID/announces',
guildAnnounceURI: '/guilds/:guildID/announces/:messageID',
channelAnnouncesURI: '/channels/:channelID/announces',
channelAnnounceURI: '/channels/:channelID/announces/:messageID',
messagesURI: '/channels/:channelID/messages',
messageURI: '/channels/:channelID/messages/:messageID',
userMeURI: '/users/@me',
userMeGuildsURI: '/users/@me/guilds',
muteURI: '/guilds/:guildID/mute',
muteMemberURI: '/guilds/:guildID/members/:userID/mute',
muteMembersURI: '/guilds/:guildID/mute',
gatewayURI: '/gateway',
gatewayBotURI: '/gateway/bot',
audioControlURI: '/channels/:channelID/audio',
rolesURI: '/guilds/:guildID/roles',
roleURI: '/guilds/:guildID/roles/:roleID',
memberRoleURI: '/guilds/:guildID/members/:userID/roles/:roleID',
userMeDMURI: '/users/@me/dms',
dmsURI: '/dms/:guildID/messages',
channelPermissionsURI: '/channels/:channelID/members/:userID/permissions',
channelRolePermissionsURI: '/channels/:channelID/roles/:roleID/permissions',
schedulesURI: '/channels/:channelID/schedules',
scheduleURI: '/channels/:channelID/schedules/:scheduleID',
guildPermissionURI: '/guilds/:guildID/api_permission',
guildPermissionDemandURI: '/guilds/:guildID/api_permission/demand',
wsInfo: '/gateway/bot',
reactionURI: '/channels/:channelID/messages/:messageID/reactions/:emojiType/:emojiID',
pinsMessageIdURI: '/channels/:channelID/pins/:messageID',
pinsMessageURI: '/channels/:channelID/pins',
interactionURI: '/interactions/:interactionID',
guildVoiceMembersURI: '/channels/:channelID/voice/members',
// 语音子频道在线成员车查询
botMic: '/channels/:channelID/mic' // 机器人上麦|下麦
};
var getURL = function getURL(endpoint) {
return apiMap[endpoint];
};
var PinsMessage = /*#__PURE__*/function () {
function PinsMessage(request, config) {
_classCallCheck(this, PinsMessage);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 获取精华消息
_createClass(PinsMessage, [{
key: "pinsMessage",
value: function pinsMessage(channelID) {
var options = {
method: 'GET',
url: getURL('pinsMessageURI'),
rest: {
channelID: channelID
}
};
return this.request(options);
} // 发送精华消息
}, {
key: "putPinsMessage",
value: function putPinsMessage(channelID, messageID) {
var options = {
method: 'PUT',
url: getURL('pinsMessageIdURI'),
headers: {
'Content-Type': 'application/json;'
},
rest: {
channelID: channelID,
messageID: messageID
}
};
return this.request(options);
} // 删除精华消息
}, {
key: "deletePinsMessage",
value: function deletePinsMessage(channelID, messageID) {
var options = {
method: 'DELETE',
url: getURL('pinsMessageIdURI'),
rest: {
channelID: channelID,
messageID: messageID
}
};
return this.request(options);
}
}]);
return PinsMessage;
}();
var Reaction = /*#__PURE__*/function () {
function Reaction(request, config) {
_classCallCheck(this, Reaction);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 发表表情表态
_createClass(Reaction, [{
key: "postReaction",
value: function postReaction(channelId, reactionToCreate) {
var options = {
method: 'PUT',
url: getURL('reactionURI'),
rest: {
channelID: channelId,
messageID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.message_id,
emojiType: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_type,
emojiID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_id
}
};
return this.request(options);
} // 删除表情表态
}, {
key: "deleteReaction",
value: function deleteReaction(channelId, reactionToDelete) {
var options = {
method: 'DELETE',
url: getURL('reactionURI'),
rest: {
channelID: channelId,
messageID: reactionToDelete === null || reactionToDelete === void 0 ? void 0 : reactionToDelete.message_id,
emojiType: reactionToDelete === null || reactionToDelete === void 0 ? void 0 : reactionToDelete.emoji_type,
emojiID: reactionToDelete === null || reactionToDelete === void 0 ? void 0 : reactionToDelete.emoji_id
}
};
return this.request(options);
} // 拉取表情表态用户列表
}, {
key: "getReactionUserList",
value: function getReactionUserList(channelId, reactionToCreate, options) {
if (!options) {
return Promise.reject(new Error("'options' required!"));
}
var reqOptions = {
method: 'GET',
url: getURL('reactionURI'),
rest: {
channelID: channelId,
messageID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.message_id,
emojiType: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_type,
emojiID: reactionToCreate === null || reactionToCreate === void 0 ? void 0 : reactionToCreate.emoji_id
},
params: options
};
return this.request(reqOptions);
}
}]);
return Reaction;
}();
var Guild = /*#__PURE__*/function () {
function Guild(request, config) {
_classCallCheck(this, Guild);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 获取频道信息
_createClass(Guild, [{
key: "guild",
value: function guild(guildID) {
var options = {
method: 'GET',
url: getURL('guildURI'),
rest: {
guildID: guildID
}
};
return this.request(options);
} // 获取某个成员信息
}, {
key: "guildMember",
value: function guildMember(guildID, userID) {
var options = {
method: 'GET',
url: getURL('guildMemberURI'),
rest: {
guildID: guildID,
userID: userID
}
};
return this.request(options);
} // 获取频道成员列表
}, {
key: "guildMembers",
value: function guildMembers(guildID, pager) {
pager = pager || {
after: '0',
limit: 1
};
var options = {
method: 'GET',
url: getURL('guildMembersURI'),
rest: {
guildID: guildID
},
params: pager
};
return this.request(options);
} // 删除指定频道成员
}, {
key: "deleteGuildMember",
value: function deleteGuildMember(guildID, userID) {
var options = {
method: 'DELETE',
url: getURL('guildMemberURI'),
rest: {
guildID: guildID,
userID: userID
}
};
return this.request(options);
} // 语音子频道在线成员列表
}, {
key: "guildVoiceMembers",
value: function guildVoiceMembers(channelID) {
var options = {
method: 'GET',
url: getURL('guildVoiceMembersURI'),
rest: {
channelID: channelID
}
};
return this.request(options);
}
}]);
return Guild;
}();
function _typeof(obj) {
"@babel/helpers - typeof";
if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
_typeof = function _typeof(obj) {
return typeof obj;
};
} else {
_typeof = function _typeof(obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
}
return _typeof(obj);
}
var version = "2.9.5";
var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
var loglevel = {exports: {}};
/*
* loglevel - https://github.com/pimterry/loglevel
*
* Copyright (c) 2013 Tim Perry
* Licensed under the MIT license.
*/
(function (module) {
(function (root, definition) {
if (module.exports) {
module.exports = definition();
} else {
root.log = definition();
}
}(commonjsGlobal, function () {
// Slightly dubious tricks to cut down minimized file size
var noop = function() {};
var undefinedType = "undefined";
var isIE = (typeof window !== undefinedType) && (typeof window.navigator !== undefinedType) && (
/Trident\/|MSIE /.test(window.navigator.userAgent)
);
var logMethods = [
"trace",
"debug",
"info",
"warn",
"error"
];
// Cross-browser bind equivalent that works at least back to IE6
function bindMethod(obj, methodName) {
var method = obj[methodName];
if (typeof method.bind === 'function') {
return method.bind(obj);
} else {
try {
return Function.prototype.bind.call(method, obj);
} catch (e) {
// Missing bind shim or IE8 + Modernizr, fallback to wrapping
return function() {
return Function.prototype.apply.apply(method, [obj, arguments]);
};
}
}
}
// Trace() doesn't print the message in IE, so for that case we need to wrap it
function traceForIE() {
if (console.log) {
if (console.log.apply) {
console.log.apply(console, arguments);
} else {
// In old IE, native console methods themselves don't have apply().
Function.prototype.apply.apply(console.log, [console, arguments]);
}
}
if (console.trace) console.trace();
}
// Build the best logging method possible for this env
// Wherever possible we want to bind, not wrap, to preserve stack traces
function realMethod(methodName) {
if (methodName === 'debug') {
methodName = 'log';
}
if (typeof console === undefinedType) {
return false; // No method possible, for now - fixed later by enableLoggingWhenConsoleArrives
} else if (methodName === 'trace' && isIE) {
return traceForIE;
} else if (console[methodName] !== undefined) {
return bindMethod(console, methodName);
} else if (console.log !== undefined) {
return bindMethod(console, 'log');
} else {
return noop;
}
}
// These private functions always need `this` to be set properly
function replaceLoggingMethods(level, loggerName) {
/*jshint validthis:true */
for (var i = 0; i < logMethods.length; i++) {
var methodName = logMethods[i];
this[methodName] = (i < level) ?
noop :
this.methodFactory(methodName, level, loggerName);
}
// Define log.log as an alias for log.debug
this.log = this.debug;
}
// In old IE versions, the console isn't present until you first open it.
// We build realMethod() replacements here that regenerate logging methods
function enableLoggingWhenConsoleArrives(methodName, level, loggerName) {
return function () {
if (typeof console !== undefinedType) {
replaceLoggingMethods.call(this, level, loggerName);
this[methodName].apply(this, arguments);
}
};
}
// By default, we use closely bound real methods wherever possible, and
// otherwise we wait for a console to appear, and then try again.
function defaultMethodFactory(methodName, level, loggerName) {
/*jshint validthis:true */
return realMethod(methodName) ||
enableLoggingWhenConsoleArrives.apply(this, arguments);
}
function Logger(name, defaultLevel, factory) {
var self = this;
var currentLevel;
defaultLevel = defaultLevel == null ? "WARN" : defaultLevel;
var storageKey = "loglevel";
if (typeof name === "string") {
storageKey += ":" + name;
} else if (typeof name === "symbol") {
storageKey = undefined;
}
function persistLevelIfPossible(levelNum) {
var levelName = (logMethods[levelNum] || 'silent').toUpperCase();
if (typeof window === undefinedType || !storageKey) return;
// Use localStorage if available
try {
window.localStorage[storageKey] = levelName;
return;
} catch (ignore) {}
// Use session cookie as fallback
try {
window.document.cookie =
encodeURIComponent(storageKey) + "=" + levelName + ";";
} catch (ignore) {}
}
function getPersistedLevel() {
var storedLevel;
if (typeof window === undefinedType || !storageKey) return;
try {
storedLevel = window.localStorage[storageKey];
} catch (ignore) {}
// Fallback to cookies if local storage gives us nothing
if (typeof storedLevel === undefinedType) {
try {
var cookie = window.document.cookie;
var location = cookie.indexOf(
encodeURIComponent(storageKey) + "=");
if (location !== -1) {
storedLevel = /^([^;]+)/.exec(cookie.slice(location))[1];
}
} catch (ignore) {}
}
// If the stored level is not valid, treat it as if nothing was stored.
if (self.levels[storedLevel] === undefined) {
storedLevel = undefined;
}
return storedLevel;
}
function clearPersistedLevel() {
if (typeof window === undefinedType || !storageKey) return;
// Use localStorage if available
try {
window.localStorage.removeItem(storageKey);
return;
} catch (ignore) {}
// Use session cookie as fallback
try {
window.document.cookie =
encodeURIComponent(storageKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
} catch (ignore) {}
}
/*
*
* Public logger API - see https://github.com/pimterry/loglevel for details
*
*/
self.name = name;
self.levels = { "TRACE": 0, "DEBUG": 1, "INFO": 2, "WARN": 3,
"ERROR": 4, "SILENT": 5};
self.methodFactory = factory || defaultMethodFactory;
self.getLevel = function () {
return currentLevel;
};
self.setLevel = function (level, persist) {
if (typeof level === "string" && self.levels[level.toUpperCase()] !== undefined) {
level = self.levels[level.toUpperCase()];
}
if (typeof level === "number" && level >= 0 && level <= self.levels.SILENT) {
currentLevel = level;
if (persist !== false) { // defaults to true
persistLevelIfPossible(level);
}
replaceLoggingMethods.call(self, level, name);
if (typeof console === undefinedType && level < self.levels.SILENT) {
return "No console available for logging";
}
} else {
throw "log.setLevel() called with invalid level: " + level;
}
};
self.setDefaultLevel = function (level) {
defaultLevel = level;
if (!getPersistedLevel()) {
self.setLevel(level, false);
}
};
self.resetLevel = function () {
self.setLevel(defaultLevel, false);
clearPersistedLevel();
};
self.enableAll = function(persist) {
self.setLevel(self.levels.TRACE, persist);
};
self.disableAll = function(persist) {
self.setLevel(self.levels.SILENT, persist);
};
// Initialize with the right level
var initialLevel = getPersistedLevel();
if (initialLevel == null) {
initialLevel = defaultLevel;
}
self.setLevel(initialLevel, false);
}
/*
*
* Top-level API
*
*/
var defaultLogger = new Logger();
var _loggersByName = {};
defaultLogger.getLogger = function getLogger(name) {
if ((typeof name !== "symbol" && typeof name !== "string") || name === "") {
throw new TypeError("You must supply a name when creating a logger.");
}
var logger = _loggersByName[name];
if (!logger) {
logger = _loggersByName[name] = new Logger(
name, defaultLogger.getLevel(), defaultLogger.methodFactory);
}
return logger;
};
// Grab the current global log variable in case of overwrite
var _log = (typeof window !== undefinedType) ? window.log : undefined;
defaultLogger.noConflict = function() {
if (typeof window !== undefinedType &&
window.log === defaultLogger) {
window.log = _log;
}
return defaultLogger;
};
defaultLogger.getLoggers = function getLoggers() {
return _loggersByName;
};
// ES6 default export, for compatibility
defaultLogger['default'] = defaultLogger;
return defaultLogger;
}));
}(loglevel));
var log = loglevel.exports;
log.setLevel('info');
log.setLevel('trace');
var BotLogger = log;
var toObject = function toObject(data) {
if (Buffer.isBuffer(data)) return JSON.parse(data.toString());
if (_typeof(data) === 'object') return data;
if (typeof data === 'string') return JSON.parse(data); // return String(data);
};
var getTimeStampNumber = function getTimeStampNumber() {
return Number(new Date().getTime().toString().substr(0, 10));
}; // 添加 User-Agent
var addUserAgent = function addUserAgent(header) {
var sdkVersion = version;
header['User-Agent'] = "BotNodeSDK/v".concat(sdkVersion);
}; // 添加 User-Agent
var addAuthorization = function addAuthorization(header, appID, token) {
header['Authorization'] = "Bot ".concat(appID, ".").concat(token);
}; // 组装完整Url
var buildUrl = function buildUrl() {
var path = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : '';
var isSandbox = arguments.length > 1 ? arguments[1] : undefined;
return "".concat(isSandbox ? 'https://sandbox.api.sgroup.qq.com' : 'https://api.sgroup.qq.com').concat(path);
};
var Channel = /*#__PURE__*/function () {
function Channel(request, config) {
_classCallCheck(this, Channel);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 获取子频道信息
_createClass(Channel, [{
key: "channel",
value: function channel(channelID) {
var options = {
method: 'GET',
url: getURL('channelURI'),
rest: {
channelID: channelID
}
};
return this.request(options);
} // 获取频道下的子频道列表
}, {
key: "channels",
value: function channels(guildID) {
var options = {
method: 'GET',
url: getURL('channelsURI'),
rest: {
guildID: guildID
}
};
return this.request(options);
} // 创建子频道
}, {
key: "postChannel",
value: function postChannel(guildID, channel) {
if (channel.position === 0) {
channel.position = getTimeStampNumber();
}
var options = {
method: 'POST',
url: getURL('channelsURI'),
rest: {
guildID: guildID
},
data: channel
};
return this.request(options);
} // 修改子频道信息
}, {
key: "patchChannel",
value: function patchChannel(channelID, channel) {
if (channel.position === 0) {
channel.position = getTimeStampNumber();
}
var options = {
method: 'PATCH',
url: getURL('channelURI'),
rest: {
channelID: channelID
},
data: channel
};
return this.request(options);
} // 删除指定子频道
}, {
key: "deleteChannel",
value: function deleteChannel(channelID) {
var options = {
method: 'DELETE',
url: getURL('channelURI'),
rest: {
channelID: channelID
}
};
return this.request(options);
}
}]);
return Channel;
}();
var Me = /*#__PURE__*/function () {
function Me(request, config) {
_classCallCheck(this, Me);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 获取当前用户信息
_createClass(Me, [{
key: "me",
value: function me() {
var options = {
method: 'GET',
url: getURL('userMeURI')
};
return this.request(options);
} // 获取当前用户频道列表
}, {
key: "meGuilds",
value: function meGuilds(options) {
var reqOptions = {
method: 'GET',
url: getURL('userMeGuildsURI'),
params: options
};
return this.request(reqOptions);
}
}]);
return Me;
}();
var Message = /*#__PURE__*/function () {
function Message(request, config) {
_classCallCheck(this, Message);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 获取指定消息
_createClass(Message, [{
key: "message",
value: function message(channelID, messageID) {
var options = {
method: 'GET',
url: getURL('messageURI'),
rest: {
channelID: channelID,
messageID: messageID
}
};
return this.request(options);
} // 获取消息列表
}, {
key: "messages",
value: function messages(channelID, pager) {
var params = Object.create(null);
if (pager && pager.type && pager.id) {
params[pager.type] = pager.id;
params.limit = pager.limit || 20;
}
var options = {
method: 'GET',
url: getURL('messagesURI'),
rest: {
channelID: channelID
},
params: params
};
return this.request(options);
} // 发送消息
}, {
key: "postMessage",
value: function postMessage(channelID, message) {
var options = {
method: 'POST',
url: getURL('messagesURI'),
rest: {
channelID: channelID
},
data: message
};
return this.request(options);
} // 撤回消息
}, {
key: "deleteMessage",
value: function deleteMessage(channelID, messageID, hideTip) {
var params = Object.create(null);
if (hideTip) {
params.hidetip = hideTip;
}
var options = {
method: 'DELETE',
url: getURL('messageURI'),
rest: {
channelID: channelID,
messageID: messageID
},
params: params
};
return this.request(options);
}
}]);
return Message;
}();
var Member = /*#__PURE__*/function () {
function Member(request, config) {
_classCallCheck(this, Member);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 增加频道身份组成员
_createClass(Member, [{
key: "memberAddRole",
value: function memberAddRole(guildID, roleID, userID, channel // 兼容原来传递 channel 对象的逻辑,后续仅支持 string
) {
var channelObj = typeof channel === 'string' ? {
channel: {
id: channel
}
} : channel;
var options = {
method: 'PUT',
url: getURL('memberRoleURI'),
rest: {
guildID: guildID,
userID: userID,
roleID: roleID
},
data: channelObj
};
return this.request(options);
} // 删除频道身份组成员
}, {
key: "memberDeleteRole",
value: function memberDeleteRole(guildID, roleID, userID, channel // 兼容原来传递 channel 对象的逻辑,后续仅支持 string
) {
var channelObj = typeof channel === 'string' ? {
channel: {
id: channel
}
} : channel;
var options = {
method: 'DELETE',
url: getURL('memberRoleURI'),
rest: {
guildID: guildID,
userID: userID,
roleID: roleID
},
data: channelObj
};
return this.request(options);
}
}]);
return Member;
}();
var defaultFilter = {
name: 1,
color: 1,
hoist: 1
}; // 用户组默认颜色值
var defaultColor = 4278245297;
var Role = /*#__PURE__*/function () {
function Role(request, config) {
_classCallCheck(this, Role);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 获取频道身份组列表
_createClass(Role, [{
key: "roles",
value: function roles(guildID) {
var options = {
method: 'GET',
url: getURL('rolesURI'),
rest: {
guildID: guildID
}
};
return this.request(options);
} // 创建频道身份组
}, {
key: "postRole",
value: function postRole(guildID, role) {
var filter = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : defaultFilter;
if (role.color === 0) {
role.color = defaultColor;
}
var options = {
method: 'POST',
url: getURL('rolesURI'),
rest: {
guildID: guildID
},
data: {
guild_id: guildID,
filter: filter,
info: role
}
};
return this.request(options);
} // 修改频道身份组
}, {
key: "patchRole",
value: function patchRole(guildID, roleID, role) {
var filter = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : defaultFilter;
if (role.color === 0) {
role.color = defaultColor;
}
var options = {
method: 'PATCH',
url: getURL('roleURI'),
rest: {
guildID: guildID,
roleID: roleID
},
data: {
guild_id: guildID,
filter: filter,
info: role
}
};
return this.request(options);
} // 删除频道身份组
}, {
key: "deleteRole",
value: function deleteRole(guildID, roleID) {
var options = {
method: 'DELETE',
url: getURL('roleURI'),
rest: {
guildID: guildID,
roleID: roleID
}
};
return this.request(options);
}
}]);
return Role;
}();
var DirectMessage = /*#__PURE__*/function () {
function DirectMessage(request, config) {
_classCallCheck(this, DirectMessage);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 创建私信频道
_createClass(DirectMessage, [{
key: "createDirectMessage",
value: function createDirectMessage(dm) {
var options = {
method: 'POST',
url: getURL('userMeDMURI'),
data: dm
};
return this.request(options);
} // 在私信频道内发消息
}, {
key: "postDirectMessage",
value: function postDirectMessage(guildID, msg) {
var options = {
method: 'POST',
url: getURL('dmsURI'),
rest: {
guildID: guildID
},
data: msg
};
return this.request(options);
}
}]);
return DirectMessage;
}();
var ChannelPermissions = /*#__PURE__*/function () {
function ChannelPermissions(request, config) {
_classCallCheck(this, ChannelPermissions);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 获取指定子频道的权限
_createClass(ChannelPermissions, [{
key: "channelPermissions",
value: function channelPermissions(channelID, userID) {
var options = {
method: 'GET',
url: getURL('channelPermissionsURI'),
rest: {
channelID: channelID,
userID: userID
}
};
return this.request(options);
} // 修改指定子频道的权限
}, {
key: "putChannelPermissions",
value: function putChannelPermissions(channelID, userID, p) {
try {
// 校验参数
parseInt(p.add, 10);
parseInt(p.remove, 10);
} catch (error) {
return Promise.reject(new Error('invalid parameter'));
}
var options = {
method: 'PUT',
url: getURL('channelPermissionsURI'),
rest: {
channelID: channelID,
userID: userID
},
data: p
};
return this.request(options);
} // 获取指定子频道身份组的权限
}, {
key: "channelRolePermissions",
value: function channelRolePermissions(channelID, roleID) {
var options = {
method: 'GET',
url: getURL('channelRolePermissionsURI'),
rest: {
channelID: channelID,
roleID: roleID
}
};
return this.request(options);
} // 修改指定子频道身份组的权限
}, {
key: "putChannelRolePermissions",
value: function putChannelRolePermissions(channelID, roleID, p) {
try {
// 校验参数
parseInt(p.add, 10);
parseInt(p.remove, 10);
} catch (error) {
return Promise.reject(new Error('invalid parameter'));
}
var options = {
method: 'PUT',
url: getURL('channelRolePermissionsURI'),
rest: {
channelID: channelID,
roleID: roleID
},
data: p
};
return this.request(options);
}
}]);
return ChannelPermissions;
}();
var Audio = /*#__PURE__*/function () {
function Audio(request, config) {
_classCallCheck(this, Audio);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 执行音频播放,暂停等操作
_createClass(Audio, [{
key: "postAudio",
value: function postAudio(channelID, audioControl) {
var options = {
method: 'POST',
url: getURL('audioControlURI'),
rest: {
channelID: channelID
},
data: audioControl
};
return this.request(options);
} // 机器人上麦
}, {
key: "botOnMic",
value: function botOnMic(channelID) {
var options = {
method: 'PUT',
url: getURL('botMic'),
rest: {
channelID: channelID
},
data: {}
};
return this.request(options);
} // 机器人下麦
}, {
key: "botOffMic",
value: function botOffMic(channelID) {
var options = {
method: 'DELETE',
url: getURL('botMic'),
rest: {
channelID: channelID
},
data: {}
};
return this.request(options);
}
}]);
return Audio;
}();
var Mute = /*#__PURE__*/function () {
function Mute(request, config) {
_classCallCheck(this, Mute);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 禁言某个member
_createClass(Mute, [{
key: "muteMember",
value: function muteMember(guildID, userID, options) {
if (!options) {
return Promise.reject(new Error("'options' required!"));
}
var reqOptions = {
method: 'PATCH',
url: getURL('muteMemberURI'),
rest: {
guildID: guildID,
userID: userID
},
data: {
mute_end_timestamp: options === null || options === void 0 ? void 0 : options.timeTo,
mute_seconds: options === null || options === void 0 ? void 0 : options.seconds
}
};
return this.request(reqOptions);
} // 禁言所有人
}, {
key: "muteAll",
value: function muteAll(guildID, options) {
if (!options) {
return Promise.reject(new Error("'options' required!"));
}
var reqOptions = {
method: 'PATCH',
url: getURL('muteURI'),
rest: {
guildID: guildID
},
data: {
mute_end_timestamp: options === null || options === void 0 ? void 0 : options.timeTo,
mute_seconds: options === null || options === void 0 ? void 0 : options.seconds
}
};
return this.request(reqOptions);
} // 禁言批量member
}, {
key: "muteMembers",
value: function muteMembers(guildID, userIDList, options) {
if (!options) {
return Promise.reject(new Error("'options' required!"));
}
var reqOptions = {
method: 'PATCH',
url: getURL('muteMembersURI'),
rest: {
guildID: guildID
},
data: {
mute_end_timestamp: options === null || options === void 0 ? void 0 : options.timeTo,
mute_seconds: options === null || options === void 0 ? void 0 : options.seconds,
user_ids: userIDList
}
};
return this.request(reqOptions);
}
}]);
return Mute;
}();
var Announce = /*#__PURE__*/function () {
function Announce(request, config) {
_classCallCheck(this, Announce);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 创建guild公告
_createClass(Announce, [{
key: "postGuildAnnounce",
value: function postGuildAnnounce(guildID, channelID, messageID) {
var options = {
method: 'POST',
url: getURL('guildAnnouncesURI'),
rest: {
guildID: guildID
},
data: {
channel_id: channelID,
message_id: messageID
}
};
return this.request(options);
} // 删除guild公告
}, {
key: "deleteGuildAnnounce",
value: function deleteGuildAnnounce(guildID, messageID) {
var options = {
method: 'DELETE',
url: getURL('guildAnnounceURI'),
rest: {
guildID: guildID,
messageID: messageID
}
};
return this.request(options);
} // 创建频道公告推荐子频道
}, {
key: "postGuildRecommend",
value: function postGuildRecommend(guildID, recommendObj) {
var options = {
method: 'POST',
url: getURL('guildAnnouncesURI'),
rest: {
guildID: guildID
},
data: recommendObj
};
return this.request(options);
} // 创建channel公告
}, {
key: "postChannelAnnounce",
value: function postChannelAnnounce(channelID, messageID) {
var options = {
method: 'POST',
url: getURL('channelAnnouncesURI'),
rest: {
channelID: channelID
},
data: {
message_id: messageID
}
};
return this.request(options);
} // 删除channel公告
}, {
key: "deleteChannelAnnounce",
value: function deleteChannelAnnounce(channelID, messageID) {
var options = {
method: 'DELETE',
url: getURL('channelAnnounceURI'),
rest: {
channelID: channelID,
messageID: messageID
}
};
return this.request(options);
}
}]);
return Announce;
}();
var Schedule = /*#__PURE__*/function () {
function Schedule(request, config) {
_classCallCheck(this, Schedule);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 获取日程列表
_createClass(Schedule, [{
key: "schedules",
value: function schedules(channelID, since) {
if (since && since.length !== 13) {
return Promise.reject(new Error("Param 'since' is invalid, millisecond timestamp expected!"));
}
var options = {
method: 'GET',
url: getURL('schedulesURI'),
rest: {
channelID: channelID
},
params: {
since: since
}
};
return this.request(options);
} // 获取日程
}, {
key: "schedule",
value: function schedule(channelID, scheduleID) {
var options = {
method: 'GET',
url: getURL('scheduleURI'),
rest: {
channelID: channelID,
scheduleID: scheduleID
}
};
return this.request(options);
} // 创建日程
}, {
key: "postSchedule",
value: function postSchedule(channelID, schedule) {
var options = {
method: 'POST',
url: getURL('schedulesURI'),
rest: {
channelID: channelID
},
data: {
schedule: schedule
}
};
return this.request(options);
} // 修改日程
}, {
key: "patchSchedule",
value: function patchSchedule(channelID, scheduleID, schedule) {
var options = {
method: 'PATCH',
url: getURL('scheduleURI'),
rest: {
channelID: channelID,
scheduleID: scheduleID
},
data: {
schedule: schedule
}
};
return this.request(options);
} // 删除日程
}, {
key: "deleteSchedule",
value: function deleteSchedule(channelID, scheduleID) {
var options = {
method: 'DELETE',
url: getURL('scheduleURI'),
rest: {
channelID: channelID,
scheduleID: scheduleID
}
};
return this.request(options);
}
}]);
return Schedule;
}();
var GuildPermissions = /*#__PURE__*/function () {
function GuildPermissions(request, config) {
_classCallCheck(this, GuildPermissions);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 获取频道可用权限列表
_createClass(GuildPermissions, [{
key: "permissions",
value: function permissions(guildID) {
var options = {
method: 'GET',
url: getURL('guildPermissionURI'),
rest: {
guildID: guildID
}
};
return this.request(options);
} // 创建频道 API 接口权限授权链接
}, {
key: "postPermissionDemand",
value: function postPermissionDemand(guildID, permissionDemandObj) {
var options = {
method: 'POST',
url: getURL('guildPermissionDemandURI'),
rest: {
guildID: guildID
},
data: permissionDemandObj
};
return this.request(options);
}
}]);
return GuildPermissions;
}();
var Interaction = /*#__PURE__*/function () {
function Interaction(request, config) {
_classCallCheck(this, Interaction);
_defineProperty(this, "request", void 0);
_defineProperty(this, "config", void 0);
this.request = request;
this.config = config;
} // 异步更新交互数据
_createClass(Interaction, [{
key: "putInteraction",
value: function putInteraction(interactionID, interactionData) {
var options = {
method: 'PUT',
url: getURL('interactionURI'),
headers: {
'Content-Type': 'none'
},
rest: {
interactionID: interactionID
},
data: interactionData
};
return this.request(options);
}
}]);
return Interaction;
}();
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
var apiVersion = 'v1';
var OpenAPI = /*#__PURE__*/function () {
function OpenAPI(config) {
_classCallCheck(this, OpenAPI);
_defineProperty(this, "config", {
appID: '',
token: ''
});
_defineProperty(this, "guildApi", void 0);
_defineProperty(this, "channelApi", void 0);
_defineProperty(this, "meApi", void 0);
_defineProperty(this, "messageApi", void 0);
_defineProperty(this, "memberApi", void 0);
_defineProperty(this, "roleApi", void 0);
_defineProperty(this, "muteApi", void 0);
_defineProperty(this, "announceApi", void 0);
_defineProperty(this, "scheduleApi", void 0);
_defineProperty(this, "directMessageApi", void 0);
_defineProperty(this, "channelPermissionsApi", void 0);
_defineProperty(this, "audioApi", void 0);
_defineProperty(this, "reactionApi", void 0);
_defineProperty(this, "interactionApi", void 0);
_defineProperty(this, "pinsMessageApi", void 0);
_defineProperty(this, "guildPermissionsApi", void 0);
this.config = config;
this.register(this);
}
_createClass(OpenAPI, [{
key: "register",
value: function register(client) {
// 注册聚合client
client.guildApi = new Guild(this.request, this.config);
client.channelApi = new Channel(this.request, this.config);
client.meApi = new Me(this.request, this.config);
client.messageApi = new Message(this.request, this.config);
client.memberApi = new Member(this.request, this.config);
client.roleApi = new Role(this.request, this.config);
client.muteApi = new Mute(this.request, this.config);
client.announceApi = new Announce(this.request, this.config);
client.scheduleApi = new Schedule(this.request, this.config);
client.directMessageApi = new DirectMessage(this.request, this.config);
client.channelPermissionsApi = new ChannelPermissions(this.request, this.config);
client.audioApi = new Audio(this.request, this.config);
client.guildPermissionsApi = new GuildPermissions(this.request, this.config);
client.reactionApi = new Reaction(this.request, this.config);
client.interactionApi = new Interaction(this.request, this.config);
client.pinsMessageApi = new PinsMessage(this.request, this.config);
} // 基础rest请求
}, {
key: "request",
value: function request(options) {
var _this$config = this.config,
appID = _this$config.appID,
token = _this$config.token;
options.headers = _objectSpread({}, options.headers); // 添加 UA
addUserAgent(options.headers); // 添加鉴权信息
addAuthorization(options.headers, appID, token); // 组装完整Url
var botUrl = buildUrl(options.url, this.config.sandbox); // 简化错误信息,后续可考虑通过中间件形式暴露给用户自行处理
resty.useRes(function (result) {
return result;
}, function (error) {
var _error$response, _error$response$heade, _error$response2;
var traceid = error === null || error === void 0 ? void 0 : (_error$response = error.response) === null || _error$response === void 0 ? void 0 : (_error$response$heade = _error$response.headers) === null || _error$response$heade === void 0 ? void 0 : _error$response$heade['x-tps-trace-id'];
if (error !== null && error !== void 0 && (_error$response2 = error.response) !== null && _error$response2 !== void 0 && _error$response2.data) {
return Promise.reject(_objectSpread(_objectSpread({}, error.response.data), {}, {
traceid: traceid
}));
}
if (error !== null && error !== void 0 && error.response) {
return Promise.reject(_objectSpread(_objectSpread({}, error.response), {}, {
traceid: traceid
}));
}
return Promise.reject(error);
});
var client = resty.create(options);
return client.request(botUrl, options);
}
}], [{
key: "newClient",
value: function newClient(config) {
return new OpenAPI(config);
}
}]);
return OpenAPI;
}();
function v1Setup() {
register(apiVersion, OpenAPI);
}
function _assertThisInitialized(self) {
if (self === void 0) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return self;
}
function _setPrototypeOf(o, p) {
_setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) {
o.__proto__ = p;
return o;
};
return _setPrototypeOf(o, p);
}
function _inherits(subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function");
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
writable: true,
configurable: true
}
});
if (superClass) _setPrototypeOf(subClass, superClass);
}
function _possibleConstructorReturn(self, call) {
if (call && (_typeof(call) === "object" || typeof call === "function")) {
return call;
} else if (call !== void 0) {
throw new TypeError("Derived constructors may only return object or undefined");
}
return _assertThisInitialized(self);
}
function _getPrototypeOf(o) {
_getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) {
return o.__proto__ || Object.getPrototypeOf(o);
};
return _getPrototypeOf(o);
}
// 心跳参数
var OpCode; // 可使用的intents事件类型
(function (OpCode) {
OpCode[OpCode["DISPATCH"] = 0] = "DISPATCH";
OpCode[OpCode["HEARTBEAT"] = 1] = "HEARTBEAT";
OpCode[OpCode["IDENTIFY"] = 2] = "IDENTIFY";
OpCode[OpCode["RESUME"] = 6] = "RESUME";
OpCode[OpCode["RECONNECT"] = 7] = "RECONNECT";
OpCode[OpCode["INVALID_SESSION"] = 9] = "INVALID_SESSION";
OpCode[OpCode["HELLO"] = 10] = "HELLO";
OpCode[OpCode["HEARTBEAT_ACK"] = 11] = "HEARTBEAT_ACK";
})(OpCode || (OpCode = {}));
var AvailableIntentsEventsEnum; // OpenAPI传过来的事件类型
(function (AvailableIntentsEventsEnum) {
AvailableIntentsEventsEnum["GUILDS"] = "GUILDS";
AvailableIntentsEventsEnum["GUILD_MEMBERS"] = "GUILD_MEMBERS";
AvailableIntentsEventsEnum["GUILD_MESSAGES"] = "GUILD_MESSAGES";
AvailableIntentsEventsEnum["GUILD_MESSAGE_REACTIONS"] = "GUILD_MESSAGE_REACTIONS";
AvailableIntentsEventsEnum["DIRECT_MESSAGE"] = "DIRECT_MESSAGE";
AvailableIntentsEventsEnum["FORUMS_EVENT"] = "FORUMS_EVENT";
AvailableIntentsEventsEnum["AUDIO_ACTION"] = "AUDIO_ACTION";
AvailableIntentsEventsEnum["PUBLIC_GUILD_MESSAGES"] = "PUBLIC_GUILD_MESSAGES";
AvailableIntentsEventsEnum["MESSAGE_AUDIT"] = "MESSAGE_AUDIT";
AvailableIntentsEventsEnum["INTERACTION"] = "INTERACTION";
})(AvailableIntentsEventsEnum || (AvailableIntentsEventsEnum = {}));
var WsEventType = {
// ======= GUILDS ======
GUILD_CREATE: AvailableIntentsEventsEnum.GUILDS,
// 频道创建
GUILD_UPDATE: AvailableIntentsEventsEnum.GUILDS,
// 频道更新
GUILD_DELETE: AvailableIntentsEventsEnum.GUILDS,
// 频道删除
CHANNEL_CREATE: AvailableIntentsEventsEnum.GUILDS,
// 子频道创建
CHANNEL_UPDATE: AvailableIntentsEventsEnum.GUILDS,
// 子频道更新
CHANNEL_DELETE: AvailableIntentsEventsEnum.GUILDS,
// 子频道删除
// ======= GUILD_MEMBERS ======
GUILD_MEMBER_ADD: AvailableIntentsEventsEnum.GUILD_MEMBERS,
// 频道成员加入
GUILD_MEMBER_UPDATE: AvailableIntentsEventsEnum.GUILD_MEMBERS,
// 频道成员更新
GUILD_MEMBER_REMOVE: AvailableIntentsEventsEnum.GUILD_MEMBERS,
// 频道成员移除
// ======= GUILD_MESSAGES ======
MESSAGE_CREATE: AvailableIntentsEventsEnum.GUILD_MESSAGES,
// 机器人收到频道消息时触发
MESSAGE_DELETE: AvailableIntentsEventsEnum.GUILD_MESSAGES,
// 删除(撤回)消息事件
// ======= GUILD_MESSAGE_REACTIONS ======
MESSAGE_REACTION_ADD: AvailableIntentsEventsEnum.GUILD_MESSAGE_REACTIONS,
// 为消息添加表情表态
MESSAGE_REACTION_REMOVE: AvailableIntentsEventsEnum.GUILD_MESSAGE_REACTIONS,
// 为消息删除表情表态
// ======= DIRECT_MESSAGE ======
DIRECT_MESSAGE_CREATE: AvailableIntentsEventsEnum.DIRECT_MESSAGE,
// 当收到用户发给机器人的私信消息时
DIRECT_MESSAGE_DELETE: AvailableIntentsEventsEnum.DIRECT_MESSAGE,
// 删除(撤回)消息事件
// ======= INTERACTION ======
INTERACTION_CREATE: AvailableIntentsEventsEnum.INTERACTION,
// 互动事件创建时
// ======= MESSAGE_AUDIT ======
MESSAGE_AUDIT_PASS: AvailableIntentsEventsEnum.MESSAGE_AUDIT,
// 消息审核通过
MESSAGE_AUDIT_REJECT: AvailableIntentsEventsEnum.MESSAGE_AUDIT,
// 消息审核不通过
// ======= FORUMS_EVENT ======
FORUM_THREAD_CREATE: AvailableIntentsEventsEnum.FORUMS_EVENT,
// 当用户创建帖子时
FO