revoltchat / revolt.js Goto Github PK
View Code? Open in Web Editor NEWModern Typescript library for interacting with Revolt.
Home Page: https://revolt.js.org
License: MIT License
Modern Typescript library for interacting with Revolt.
Home Page: https://revolt.js.org
License: MIT License
my bot crashes when i use the kick command
Full error:
C:\Users\wlodz\Projects\revoltBots\construct\construct\node_modules\solid-js\store\dist\server.cjs:67
next = current[part];
^
TypeError: Cannot read properties of undefined (reading 'lastMessageId')
at updatePath (C:\Users\wlodz\Projects\revoltBots\construct\construct\node_modules\solid-js\store\dist\server.cjs:67:19)
at updatePath (C:\Users\wlodz\Projects\revoltBots\construct\construct\node_modules\solid-js\store\dist\server.cjs:64:7)
at ChannelCollection.setStore [as updateUnderlyingObject] (C:\Users\wlodz\Projects\revoltBots\construct\construct\node_modules\solid-js\store\dist\server.cjs:83:66)
at C:\Users\wlodz\Projects\revoltBots\construct\construct\node_modules\revolt.js\lib\cjs\events\v1.js:77:41
at batch (C:\Users\wlodz\Projects\revoltBots\construct\construct\node_modules\solid-js\dist\server.cjs:105:10)
at C:\Users\wlodz\Projects\revoltBots\construct\construct\node_modules\revolt.js\lib\cjs\events\v1.js:75:42
at Generator.next (<anonymous>)
at fulfilled (C:\Users\wlodz\Projects\revoltBots\construct\construct\node_modules\revolt.js\lib\cjs\events\v1.js:5:58)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
kick command code:
import { replyWithErr } from "../lib.js";
const log = console.log
export default {
name: 'kick',
aliases: [],
// privilege: CommandPrivilege.Manager,
async run(message, args, command, db, bot, { client }) {
const isOwner = message.author.id == bot.owner.id
if (!(isOwner || message.member.hasPermission(message.server, "KickMembers"))) { replyWithErr(message, "Missing permission"); return }
if (message.server.ownerId == message.mentionIds[0]) { replyWithErr(message, "Unable to kick owner"); return }
if (message.mentionIds == undefined) { replyWithErr(message, "Missing argument 1"); return }
if (message.mentionIds[0] == bot.id) { replyWithErr(message, "I can't kick myself!"); return }
var myRank = await message.server.fetchMember(bot.id).ranking
var targetRank = await message.server.fetchMember(message.mentionIds[0]).ranking
if (myRank > targetRank) { replyWithErr(message, "My rank is lower than the rank of the person you are trying to kick"); return }
try {
message.server.kickUser(message.mentionIds[0])
} catch (err) {
log(`! Fatal Error: ${err}`)
console.log(err)
message.reply("someting went wrong, check if the bot has permission to kick/ban and try again!")
return
}
try {
if (message.server.id == "01H36T7ZNX7ZMQ4FKB2TZHKX04") {
Array.prototype.random = function() {
return this[Math.floor(Math.random() * this.length)]
}
let killers = [
':01HJ1E0VN82X9HY5NZTDK93NJF:',
':01HKF2GPK971GA0XP5DQQ3F78B:',
':01HKJBBYTGFT42EKC6HYHDZVDT:',
':01HKJBD22G8WA376S10VPZJP5X:',
':01HKJBV6E07JG64HP7HSV450GA:',
':01HKJC0KPYX980T3ARTBH4W97K:',
':01HKJC124ZVN8JXRZ478X65ZCG:',
':01HKJBWN7A59Q0K3AKCE37BJJN:',
':01HKJBX09P4Z8NTBEZDHN09K61:',
];
let weepons = [
':01H36VVBSK3C72AFNGSFT6HQQ1:',
':01H36VVSHZJS8JPZ55ZNCA0N08:',
':01H36VWDPEQ3EYNEDRR933311E:',
':01H36VWZ54FN14YV4ABYARAT22:',
':01H36VXB1CJTM070PBZXAGGNY4:',
':01H36VXVGQQZ9YQX5X991NA9PH:',
':01H36VYF63ZNMN3Y0NKSQN3W5Z:',
];
try {
if (client.channels.get("01H8A1BFF1F2Q2AT6629WC6A4Q")) {
client.channels.get("01H8A1BFF1F2Q2AT6629WC6A4Q").sendMessage(`${killers.random()}${weepons.random()}${message.args[0]}`)
}
} catch (fatalError) {
log(`! Fatal Error: ${fatalError}`)
console.log(JSON.stringify(fatalError))
}
} else {
try {
message.channel.sendMessage(`<@${message.mentionIds[0]}> kicked`)
} catch (fatalError) {
log(`! Fatal Error: ${fatalError}`)
console.log(JSON.stringify(fatalError))
}
}
} catch (fatalError) {
log(`! Fatal Error: ${fatalError}`)
console.log(JSON.stringify(fatalError))
}
},
}
it gets to the client.channels.get("01H8A1BFF1F2Q2AT6629WC6A4Q").sendMessage(`${killers.random()}${weepons.random()}${message.args[0]}`)
part before crashing
pls help
I believe this applies to almost all update events, but it's mainly been affecting me with channels, so I'll use those as an example.
From what I have gathered, when a ChannelUpdate event is received, revolt.js doesn't apply the key mappings. For example, when a channel's permissions are updated, the new Channel object looks like this:
rolePermissions
here is the old data, role_permissions
is the new data.
The result is that all data that revolt.js provides under a different key than what the API returns will not be updated and keep its initial value until the client reconnects.
npm i git+https://github.com/revoltchat/revolt.js.git
A successful package install from git.
Instead, missing lib directory.
Webhook support would probably be a good idea, as github commits and other stuff support them, so I can have a github feed in a server
In the latest version of the revolt.js npm package, which as of writing this issue is 7.0.0-beta.9
, the client can fetch and add emojis to an server (though the fetchEmojis
and createEmoji
method), but not delete the emojis. So adding the ability to delete emojis would help add more capabilities to the packages.
When importing revolt.js' ESM version directly from revolt.js/lib/esm/index.js
, an error is thrown because it's interpreted as a CJS module by both Node and Deno.
How to reproduce:
import { Client } from "revolt.js/lib/esm/index.js";
// or "npm:[email protected]/lib/esm/index.js" when using Deno
const bot = new Client();
Logs:
file:///home/jersey/projects/revolt-repro/index.js:1
import { Client } from "revolt.js/lib/esm/index.js";
^^^^^^
SyntaxError: Named export 'Client' not found. The requested module 'revolt.js/lib/esm/index.js' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from 'revolt.js/lib/esm/index.js';
const { Client } = pkg;
at ModuleJob._instantiate (node:internal/modules/esm/module_job:123:21)
at async ModuleJob.run (node:internal/modules/esm/module_job:189:5)
Node.js v19.8.1
error: 'import', and 'export' cannot be used outside of module code at file:///home/jersey/projects/revolt-repro/node_modules/.deno/[email protected]/node_modules/revolt.js/lib/esm/index.js:1:1
export * from "./classes";
~~~~~~
It appears that when a user leaves a server (or gets kicked/banned) and is not already cached, revolt.js attempts to fetch that user. If it is unable to fetch it (Usually because of missing permission), an exception is thrown.
This is not a big issue in browser applications, but it almost certainly causes node.js applications such as bots to exit. (See attached video)
The error comes from the method: https://github.com/revoltchat/revolt.js/blob/master/src/permissions/calculator.ts#L25
(something like msg.timestamp
)
The current lack of cache eviction can cause abnormally high system resource usage.
Notice: username and nickname are not the same thing.
nickname is related to the server/guild member.
username is related to the revolt instance user.
Edit: Happens with invited bots that are second, third, fourth on the Guild/Server.
First invited bot on the server/guild does not have such issue.
I'm trying to get the username of a member on the server/guild.
For fetching a member I use .fetchMember
.user property/accessor is missing when fetching a member from a server using a user id.
Returned member object. (missing user: property/accessor )
_id: [object Object]
nickname: boqsc
avatar: null
roles: 01GK52Z15W78JM1WQ1NK7MMZCW
timeout: null
joined_at: Wed Nov 30 2022 12:52:54 GMT+0200 (Eastern European Standard Time)
Example:
client.on("packet", async (event) => {
if ((event.type == "MessageReact" || event.type == "MessageUnreact") && (event.user_id != client.user._id)){
console.log("Red reaction.");
client.servers.forEach(async (values, keys, objects) => {
if (values.channel_ids.includes(event.channel_id) ){
guild = await client.servers.get(values._id);
guild_member = await guild.fetchMember(event.user_id);
for (const [key, value] of Object.entries(guild_member)) {
console.log(` ${key}: ${value}`);
}
console.log(` Guild Name: ${guild.name}`);
console.log(` Guild_Member Id: ${guild_member._id.user}`);
console.log(` Guild_Member Nickname: ${guild_member.nickname}`);
console.log(` Guild_Member Joined at: ${guild_member.joined_at}`);
console.log(` Guild_Member Roles: ${guild_member.roles}`);
console.log(` Guild_Member User: ${guild_member.user.username}`);
for (const [key, value] of Object.entries(guild_member)) {
console.log(` ${key}: ${value}`);
}
}
});
}
});
Example output:
Red reaction.
client: [object Object]
_id: [object Object]
nickname: boqsc
avatar: null
roles: 01GK52Z15W78JM1WQ1NK7MMZCW
timeout: null
joined_at: Wed Nov 30 2022 12:52:54 GMT+0200 (Eastern European Standard Time)
Guild Name: Colors Server
Guild_Member Id: 01GHZS22KV2CPEVGGVC3HSQYFZ
Guild_Member Nickname: boqsc
Guild_Member Joined at: Wed Nov 30 2022 12:52:54 GMT+0200 (Eastern European Standard Time)
Guild_Member Roles: 01GK52Z15W78JM1WQ1NK7MMZCW
(node:454029) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined
at /root/bot.js:57:59
at processTicksAndRejections (internal/process/task_queues.js:97:5)
similar to discord.js's awaitMessage
, add a collector of some kind
Seems latest 6.0.0 RC have some issues with ES Module, I tried using revolt.js on CommonJS and ESM and it throws same ERR_REQUIRE_ESM.
The last version that still works for me is 6.0.0-rc13.
/home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/websocket/client.js:27
const exponential_backoff_1 = require("@insertish/exponential-backoff");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/<username>/Documents/node-sandbox/node_modules/@insertish/exponential-backoff/dist/backoff.js from /home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/websocket/client.js not supported.
Instead change the require of backoff.js in /home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/websocket/client.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/websocket/client.js:27:31)
at Object.<anonymous> (/home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/Client.js:26:18)
at Object.<anonymous> (/home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/index.js:36:14)
at Object.<anonymous> (/home/<username>/Documents/node-sandbox/rtest.js:3:20) {
code: 'ERR_REQUIRE_ESM'
}
(node:36817) ExperimentalWarning: The Node.js specifier resolution flag is experimental. It could change or be removed at any time.
(Use `node --trace-warnings ...` to show where the warning was created)
/home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/websocket/client.js:27
const exponential_backoff_1 = require("@insertish/exponential-backoff");
^
Error [ERR_REQUIRE_ESM]: require() of ES Module /home/<username>/Documents/node-sandbox/node_modules/@insertish/exponential-backoff/dist/backoff.js from /home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/websocket/client.js not supported.
Instead change the require of backoff.js in /home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/websocket/client.js to a dynamic import() which is available in all CommonJS modules.
at Object.<anonymous> (/home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/websocket/client.js:27:31)
at Object.<anonymous> (/home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/Client.js:26:18)
at Object.<anonymous> (/home/<username>/Documents/node-sandbox/node_modules/revolt.js/dist/index.js:36:14)
at async Promise.all (index 0) {
code: 'ERR_REQUIRE_ESM'
}
When using client.servers.fetch()
to get the server promise for a specific server you are currently greeted with this lovely API response:
data: { error: { code: 401, reason: 'Unauthorized', description: 'The request requires user authentication.' } }
This is not a problem in v6 so I think most developers will be fine for the time being, but it's a pain in the ass when trying to use the v7 beta.
Issue Summary:
I'm currently working on a Revolt bot using revolt.js
, and I noticed that the events type is not exported. Having access to the events type would be nice so that I can enforce type safety better in my own event handler.
Steps to Reproduce:
N/A
Expected Behavior:
I expected the library to export the events type so that developers can ensure type safety in their event handlers.
Actual Behavior:
The events type is not exported.
Additional Information:
N/A
Proposed Solution:
Export the events type in the API library to facilitate better type safety in event handling. I will open a GitHub PR.
Environment:
revolt.js
Version: v7.0.0-beta.10Screenshots/Code Snippets:
N/A
When running tsc
on any typescript project using revolt.js (including the example one provided in revolt.js.org), it'll give these errors:
You can add skipLibCheck: true
to your tsconfig.json
, which would skip checking all libraries entirely. Alternatively you can just ignore the errors caused by revolt-api
and start your code anyways.
Obviously though, that doesn't fix the wider issue, and some stuff might be broken.
This snippet of code causes the above error:
case 'MessageReact': {
const message = client.messages.getOrPartial(event.id);
if (message) {
const reactions = message.reactions;
const set = reactions.get(event.emoji_id);
... when a messageReactionAdd
event listener exists:
// ...
this.options.client.on('messageReactionAdd', this.listener);
// ...
This code was used to trigger the error:
await msg.clearReactions();
await msg.react(encodeURIComponent('โ'));
Explanation: The event tries to get which reaction was added (?), but, since clearReactions
ran, message.reactions
is {}
, causing the reactions.get is not a function
error, since reactions
is not a Map
anymore.
My temporary fix:
case 'MessageReact': {
const message = client.messages.getOrPartial(event.id);
if (message) {
let reactions = message.reactions;
if (!(reactions instanceof Map)) reactions = new Map();
const set = reactions.get(event.emoji_id);
Expose simple and straightforward permission checks.
channel.havePermission(Permission.ABC)
server.havePermission(Permission.ABC)
member.hasPermission(Permission.ABC)
My code is this:
const embed = new TextEmbed(new MessageEmbed({ title: "Too many verse references!", description: "There are too many verse references in your message." }))
Yet, I keep getting this error:
TypeError: Cannot read properties of undefined (reading 'icon_url')
at new TextEmbed (D:\Repos\KJV-Bot-Revolt\node_modules\revolt.js\lib\cjs\classes\MessageEmbed.js:166:28)
at Object.execute (D:\Repos\KJV-Bot-Revolt\src\events\client\messageCreate.js:14:39)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
I have tried putting a value icon_url
in the TextEmbed, and even gave a valid image url, yet it keeps giving me the exact same error. I also tried putting it as iconUrl
to see if that worked, and it didn't.
Plain simple bot gives an error of 404 when another bot joins the server.
OS: Linux/Debian
Bot example:
const { Client } = require("revolt.js");
let client = new Client();
client.loginBot("YOUR_BOT_TOKEN");
Steps:
/members/00000000000000000000000000
Full error message: new 19.txt
After a restart of revolt bot, IF the member is in the server the serverMemberLeave
event does not respond when member leaves.
Example:
client.on("serverMemberLeave", async (member) => {
console.log("left");
});
It would be nice if we could use this within Deno. Here are the things that would have to occur if we were to proceed with this:
There are many reasons to use Deno over Node, including the built-in TypeScript support, Permission system and much more
Is there a Revolt channel I could use to discuss revolt.js? It would be best for fast communication
Minimum reproducible example: https://gitlab.insrt.uk/insert/revolt.js-type-issue
`
Error [ERR_REQUIRE_ESM]: require() of ES Module /home//node_modules/revolt.js/dist/index.js from /home//Projects//src/util/client.js not supported.
Instead change the require of index.js in /home//Projects//src/util/client.js to a dynamic import() which is available in all CommonJS modules.
at Object. (/home//Projects//src/util/client.js:13:21)
at Object. (/home//Projects/*/src/index.js:3:18)
at async Promise.all (index 0) {
code: 'ERR_REQUIRE_ESM'
}
Node.js v17.5.0
`
When running with ts-node, this error is outputted.
Needed for revoltchat/revite#369
Revolt.js 7 seems to not handle deleting messages using message.delete()
or channel.deleteMessages()
correctly after a DM is sent.
Error message:
/home/dumpling/Documents/Code/stationbot/packages/revolt.js/lib/cjs/classes/Message.js:96
return __classPrivateFieldGet(this, _Message_collection, "f").getUnderlyingObject(this.id).authorId;
^
TypeError: Cannot read properties of undefined (reading 'authorId')
at get authorId [as authorId] (/home/dumpling/Documents/Code/stationbot/packages/revolt.js/lib/cjs/classes/Message.js:96:99)
at Timeout._onTimeout (/home/dumpling/Documents/Code/stationbot/packages/base/dist/index.js:244:53)
at listOnTimeout (node:internal/timers:564:17)
at process.processTimers (node:internal/timers:507:7)
Node.js v18.7.0
Code is available here
Removing message.delete()
/channel.deleteMessages()
seems to fix the issue.
Currently using revolt.js 7.0.0-beta.1
. Built locally.
EDIT: Add version information
I'm trying to write a revolt bot in javascript and this error shows up:
let client = new Client();
^
TypeError: Client is not a constructor
at Object.<anonymous> (/home/tom/test.js:3:14)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:168:29)
at ModuleJob.run (node:internal/modules/esm/module_job:197:25)
at async Promise.all (index 0)
at async ESMLoader.import (node:internal/modules/esm/loader:337:24)
at async loadESM (node:internal/process/esm_loader:88:5)
I tried even typing it in TypeScript, but it didn't work and it told me some other error (I used example code). Here's example code, but in JavaScript:
let { Client } = require("revolt-api")
let client = new Client();
client.on("ready", async () =>
console.info(`Logged in as ${client.user.username}!`),
);
client.on("message", async (message) => {
if (message.content === "hello") {
message.channel.sendMessage("world");
}
});
client.loginBot("..");
Here's my error in TypeScript:
error TS2468: Cannot find global value 'Promise'.
test.ts:1:10 - error TS2305: Module '"revolt-api"' has no exported member 'Client'.
1 import { Client } from "revolt-api";
~~~~~~
test.ts:9:22 - error TS2705: An async function or method in ES5/ES3 requires the 'Promise' constructor. Make sure you have a declaration for the 'Promise' constructor or include 'ES2015' in your '--lib' option.
9 client.on("message", async (message) => {
~~~~~~~~~~~~~~~~~~~~
Found 3 errors in the same file, starting at: test.ts:1
Maybe I'm too dumb, but I tried fixing it for an hour and none other person had this same problem.
Would be nice using TypeDoc
๐
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.