Initial commit

Signed-off-by: Hammer1279 <tobias.lenhardt@uni-leipzig.de>
This commit is contained in:
Hammer1279 2025-01-08 14:55:27 +01:00
commit e122a6332d
Signed by: Hammer1279
GPG Key ID: 7EB815F646A7F906
7 changed files with 590 additions and 0 deletions

135
.gitignore vendored Normal file
View File

@ -0,0 +1,135 @@
# ---> Node
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# Files with sensitive login data
config.json
token.txt

9
LICENSE Normal file
View File

@ -0,0 +1,9 @@
MIT License
Copyright (c) 2025 Hammer1279
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

2
README.md Normal file
View File

@ -0,0 +1,2 @@
# matrix-bot

8
config-sample.json Normal file
View File

@ -0,0 +1,8 @@
{
"homeserver": "https://example.org",
"deviceId": "my-dev-device",
"userId": "@user:example.org",
"password": "super-secret-password",
"registerToken": "Token-Goes-Here",
"leaveOnStart": false
}

174
index.js Normal file
View File

@ -0,0 +1,174 @@
// Matrix Bot by Hammer1279
// Matrix: @hammer1279:ht-dev.de | #general:ht-dev.de
// https://matrix.to/#/@hammer1279:ht-dev.de
// https://matrix.to/#/#general:ht-dev.de
import { initAsync, Tracing, OlmMachine, UserId, LoggerLevel, DeviceId } from "@matrix-org/matrix-sdk-crypto-wasm";
import { AuthType, ClientEvent, createClient, GuestAccess, KnownMembership, RoomEvent, RoomMemberEvent } from "matrix-js-sdk";
import { existsSync } from "node:fs";
import { writeFile, readFile, appendFile } from "node:fs/promises";
import { inspect } from "node:util";
import config from "./config.json" with {
type: "json"
}
const { homeserver, deviceId, userId, password, registerToken, leaveOnStart } = config;
let matrixClient;
let roomList = new Set();
async function loadCrypto(userId, deviceId) {
// Do this before any other calls to the library
await initAsync();
// Optional: enable tracing in the rust-sdk
new Tracing(LoggerLevel.Trace).turnOn();
// Create a new OlmMachine
//
// The following will use an in-memory store. It is recommended to use
// indexedDB where that is available.
// See https://matrix-org.github.io/matrix-rust-sdk-crypto-wasm/classes/OlmMachine.html#initialize
// const olmMachine = await OlmMachine.initialize(new UserId(userId), new DeviceId(deviceId), "MyStore", "MySuperSecretKey");
const olmMachine = await OlmMachine.initialize(new UserId(userId), new DeviceId(deviceId));
return olmMachine;
}
await loadCrypto(userId, deviceId);
if (!existsSync("./token.txt")) {
matrixClient = createClient({ baseUrl: homeserver, userId: userId, deviceId: deviceId, timelineSupport: true });
matrixClient.login(AuthType.Password, {"user": userId, "password": password}).then(async (response) => {
await writeFile("./token.txt", response.access_token);
});
} else {
// matrixClient.loginWithToken((await readFile("./token.txt")).toString());
matrixClient = createClient({ baseUrl: homeserver, userId: userId, accessToken: (await readFile("./token.txt")).toString(), deviceId: deviceId, timelineSupport: true });
}
// i cannot get this to work with a indexed db so this is false
await matrixClient.initRustCrypto({useIndexedDB: false});
appendFile("./client.log", `${new Date().toISOString()} | Started!\n`);
// attempt at automating registers, this might get used in a service for only allowing registers of certain users via prior oauth2 auth
// if (await matrixClient.isUsernameAvailable("demo123")) {
// matrixClient.register("demo123", "test123", undefined, {
// type: AuthType.Dummy
// }, undefined, undefined, true).then(() => console.log("gud"), reject => {
// const session = reject.data.session;
// matrixClient.register("demo123", "test123", session, {
// type: AuthType.RegistrationToken,
// token: registerToken,
// session: session,
// }, undefined, undefined, true)
// });
// } else {
// console.log("Username taken");
// }
matrixClient.on(RoomEvent.MyMembership, function (room, membership, prevMembership) {
if (membership === KnownMembership.Invite) {
matrixClient.joinRoom(room.roomId).then(function () {
console.log("Auto-joined %s", room.roomId);
roomList.add(room.roomId);
appendFile("./client.log", `${new Date().toISOString()} | Joined ${room.roomId}\n`);
});
}
});
// // Listen for low-level MatrixEvents
matrixClient.on(ClientEvent.Event, function (event) {
console.log(event.getType());
});
matrixClient.on(RoomMemberEvent.Membership, function (event, member) {
// appendFile("./client.log", `${new Date().toISOString()} | Membership Event: ${inspect(event)}\n`);
// appendFile("./client.log", `${new Date().toISOString()} | Membership Member: ${inspect(member)}\n`);
if (event.event.sender == userId && event.event.content.membership == KnownMembership.Join) {
roomList.add(event.event.room_id);
appendFile("./client.log", `${new Date().toISOString()} | I'm in?: ${event.event.room_id}\n`);
}
console.log(inspect(event), inspect(member))
})
// Listen for typing changes
matrixClient.on(RoomMemberEvent.Typing, function (event, member) {
if (member.typing) {
console.log(member.name + " is typing...");
} else {
console.log(member.name + " stopped typing.");
}
});
matrixClient.on(RoomEvent.Timeline, async function (event, room, toStartOfTimeline) {
if (toStartOfTimeline) {
return; // don't print paginated results
}
// if (event.getType() !== "m.room.message") {
// return; // only print messages
// }
// console.log(
// // the room name will update with m.room.name events automatically
// "(%s) %s :: %s",
// room.name,
// event.getSender(),
// event.getContent().body,
// );
// matrixClient.sendMessage(event.getRoomId(), "Hello")
let body = '';
try {
if (event.getType() === 'm.room.encrypted') {
const clearEvent = await matrixClient.getCrypto().decryptEvent(event);
({ body } = clearEvent.clearEvent.content);
} else {
({ body } = event.getContent());
appendFile("./client.log", `${new Date().toISOString()} | Message Event: ${event.getType()}\n`);
}
if (body) {
// do something
if (event.getSender() != userId) {
if (new Date().getTime() - 10000 > event.getDate()) {
console.log("Ignoring old message:", body);
appendFile("./client.log", `${new Date().toISOString()} | Ignoring old message: ${body}\n`);
return;
}
console.log("MESSAGE:", body);
if (body == "!help leave") {
leaveAllRooms();
appendFile("./client.log", `${new Date().toISOString()} | ${event.getSender()} told me to leave all rooms\n`);
} else {
appendFile("./client.log", `${new Date().toISOString()} | Received Message: ${body}\n`);
matrixClient.sendTextMessage(event.getRoomId(), "Hewwo :3")
}
}
}
} catch (error) {
console.error('#### ', error);
}
});
matrixClient.getRooms().forEach(room => {
appendFile("./client.log", `${new Date().toISOString()} | I'm in: ${inspect(room)}\n`);
})
if (leaveOnStart) {
setTimeout(() => {
leaveAllRooms();
}, 1000);
}
function leaveRoom(roomId) {
matrixClient.leave(roomId).then(val => {
appendFile("./client.log", `${new Date().toISOString()} | Left ${roomId}\n`);
}, () => {}) // do not give a shit if it failed
}
function leaveAllRooms() {
roomList.forEach(leaveRoom);
}
matrixClient.startClient();

241
package-lock.json generated Normal file
View File

@ -0,0 +1,241 @@
{
"name": "matrix-bot",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "matrix-bot",
"version": "1.0.0",
"license": "MIT",
"dependencies": {
"@matrix-org/matrix-sdk-crypto-wasm": "^12.1.0",
"matrix-bot": "file:",
"matrix-js-sdk": "^35.1.0"
}
},
"node_modules/@babel/runtime": {
"version": "7.26.0",
"resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.26.0.tgz",
"integrity": "sha512-FDSOghenHTiToteC/QRlv2q3DhPZ/oOXTBoirfWNx1Cx3TMVcGWQtMMmQcSvb/JjpNeGzx8Pq/b4fKEJuWm1sw==",
"license": "MIT",
"dependencies": {
"regenerator-runtime": "^0.14.0"
},
"engines": {
"node": ">=6.9.0"
}
},
"node_modules/@matrix-org/matrix-sdk-crypto-wasm": {
"version": "12.1.0",
"resolved": "https://registry.npmjs.org/@matrix-org/matrix-sdk-crypto-wasm/-/matrix-sdk-crypto-wasm-12.1.0.tgz",
"integrity": "sha512-NhJFu/8FOGjnW7mDssRUzaMSwXrYOcCqgAjZyAw9KQ9unNADKEi7KoIKe7GtrG2PWtm36y2bUf+hB8vhSY6Wdw==",
"license": "Apache-2.0",
"engines": {
"node": ">= 18"
}
},
"node_modules/@matrix-org/olm": {
"version": "3.2.15",
"resolved": "https://registry.npmjs.org/@matrix-org/olm/-/olm-3.2.15.tgz",
"integrity": "sha512-S7lOrndAK9/8qOtaTq/WhttJC/o4GAzdfK0MUPpo8ApzsJEC0QjtwrkC3KBXdFP1cD1MXi/mlKR7aaoVMKgs6Q==",
"license": "Apache-2.0"
},
"node_modules/@types/events": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/@types/events/-/events-3.0.3.tgz",
"integrity": "sha512-trOc4AAUThEz9hapPtSd7wf5tiQKvTtu5b371UxXdTuqzIh0ArcRspRP0i0Viu+LXstIQ1z96t1nsPxT9ol01g==",
"license": "MIT"
},
"node_modules/@types/retry": {
"version": "0.12.0",
"resolved": "https://registry.npmjs.org/@types/retry/-/retry-0.12.0.tgz",
"integrity": "sha512-wWKOClTTiizcZhXnPY4wikVAwmdYHp8q6DmC+EJUzAMsycb7HB32Kh9RN4+0gExjmPmZSAQjgURXIGATPegAvA==",
"license": "MIT"
},
"node_modules/another-json": {
"version": "0.2.0",
"resolved": "https://registry.npmjs.org/another-json/-/another-json-0.2.0.tgz",
"integrity": "sha512-/Ndrl68UQLhnCdsAzEXLMFuOR546o2qbYRqCglaNHbjXrwG1ayTcdwr3zkSGOGtGXDyR5X9nCFfnyG2AFJIsqg==",
"license": "Apache-2.0"
},
"node_modules/base-x": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/base-x/-/base-x-5.0.0.tgz",
"integrity": "sha512-sMW3VGSX1QWVFA6l8U62MLKz29rRfpTlYdCqLdpLo1/Yd4zZwSbnUaDfciIAowAqvq7YFnWq9hrhdg1KYgc1lQ==",
"license": "MIT"
},
"node_modules/bs58": {
"version": "6.0.0",
"resolved": "https://registry.npmjs.org/bs58/-/bs58-6.0.0.tgz",
"integrity": "sha512-PD0wEnEYg6ijszw/u8s+iI3H17cTymlrwkKhDhPZq+Sokl3AU4htyBFTjAeNAlCCmg0f53g6ih3jATyCKftTfw==",
"license": "MIT",
"dependencies": {
"base-x": "^5.0.0"
}
},
"node_modules/content-type": {
"version": "1.0.5",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz",
"integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/events": {
"version": "3.3.0",
"resolved": "https://registry.npmjs.org/events/-/events-3.3.0.tgz",
"integrity": "sha512-mQw+2fkQbALzQ7V0MY0IqdnXNOeTtP4r0lN9z7AAawCXgqea7bDii20AYrIBrFd/Hx0M2Ocz6S111CaFkUcb0Q==",
"license": "MIT",
"engines": {
"node": ">=0.8.x"
}
},
"node_modules/jwt-decode": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/jwt-decode/-/jwt-decode-4.0.0.tgz",
"integrity": "sha512-+KJGIyHgkGuIq3IEBNftfhW/LfWhXUIY6OmyVWjliu5KH1y0fw7VQ8YndE2O4qZdMSd9SqbnC8GOcZEy0Om7sA==",
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/loglevel": {
"version": "1.9.2",
"resolved": "https://registry.npmjs.org/loglevel/-/loglevel-1.9.2.tgz",
"integrity": "sha512-HgMmCqIJSAKqo68l0rS2AanEWfkxaZ5wNiEFb5ggm08lDs9Xl2KxBlX3PTcaD2chBM1gXAYf491/M2Rv8Jwayg==",
"license": "MIT",
"engines": {
"node": ">= 0.6.0"
},
"funding": {
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/loglevel"
}
},
"node_modules/matrix-bot": {
"resolved": "",
"link": true
},
"node_modules/matrix-events-sdk": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/matrix-events-sdk/-/matrix-events-sdk-0.0.1.tgz",
"integrity": "sha512-1QEOsXO+bhyCroIe2/A5OwaxHvBm7EsSQ46DEDn8RBIfQwN5HWBpFvyWWR4QY0KHPPnnJdI99wgRiAl7Ad5qaA==",
"license": "Apache-2.0"
},
"node_modules/matrix-js-sdk": {
"version": "35.1.0",
"resolved": "https://registry.npmjs.org/matrix-js-sdk/-/matrix-js-sdk-35.1.0.tgz",
"integrity": "sha512-uADi0Uj3uASPe20DuAKEc17/3fywCkla6cHqq4vTd+FgxDWo8nngozl8ykINIU+Y3VimcrxeciGvUjTyHcA9pg==",
"license": "Apache-2.0",
"dependencies": {
"@babel/runtime": "^7.12.5",
"@matrix-org/matrix-sdk-crypto-wasm": "^11.1.0",
"@matrix-org/olm": "3.2.15",
"another-json": "^0.2.0",
"bs58": "^6.0.0",
"content-type": "^1.0.4",
"jwt-decode": "^4.0.0",
"loglevel": "^1.7.1",
"matrix-events-sdk": "0.0.1",
"matrix-widget-api": "^1.10.0",
"oidc-client-ts": "^3.0.1",
"p-retry": "4",
"sdp-transform": "^2.14.1",
"unhomoglyph": "^1.0.6",
"uuid": "11"
},
"engines": {
"node": ">=20.0.0"
}
},
"node_modules/matrix-js-sdk/node_modules/@matrix-org/matrix-sdk-crypto-wasm": {
"version": "11.1.0",
"resolved": "https://registry.npmjs.org/@matrix-org/matrix-sdk-crypto-wasm/-/matrix-sdk-crypto-wasm-11.1.0.tgz",
"integrity": "sha512-JPuO9RCVDklDjbFzMvZfQb7PuiFkLY72bniRSu81lRzkkrcbZtmKqBFMm9H4f2FSz+tHVkDnmsvn12I4sdJJ5A==",
"license": "Apache-2.0",
"engines": {
"node": ">= 10"
}
},
"node_modules/matrix-widget-api": {
"version": "1.10.0",
"resolved": "https://registry.npmjs.org/matrix-widget-api/-/matrix-widget-api-1.10.0.tgz",
"integrity": "sha512-rkAJ29briYV7TJnfBVLVSKtpeBrBju15JZFSDP6wj8YdbCu1bdmlplJayQ+vYaw1x4fzI49Q+Nz3E85s46sRDw==",
"license": "Apache-2.0",
"dependencies": {
"@types/events": "^3.0.0",
"events": "^3.2.0"
}
},
"node_modules/oidc-client-ts": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/oidc-client-ts/-/oidc-client-ts-3.1.0.tgz",
"integrity": "sha512-IDopEXjiwjkmJLYZo6BTlvwOtnlSniWZkKZoXforC/oLZHC9wkIxd25Kwtmo5yKFMMVcsp3JY6bhcNJqdYk8+g==",
"license": "Apache-2.0",
"dependencies": {
"jwt-decode": "^4.0.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/p-retry": {
"version": "4.6.2",
"resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz",
"integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==",
"license": "MIT",
"dependencies": {
"@types/retry": "0.12.0",
"retry": "^0.13.1"
},
"engines": {
"node": ">=8"
}
},
"node_modules/regenerator-runtime": {
"version": "0.14.1",
"resolved": "https://registry.npmjs.org/regenerator-runtime/-/regenerator-runtime-0.14.1.tgz",
"integrity": "sha512-dYnhHh0nJoMfnkZs6GmmhFknAGRrLznOu5nc9ML+EJxGvrx6H7teuevqVqCuPcPK//3eDrrjQhehXVx9cnkGdw==",
"license": "MIT"
},
"node_modules/retry": {
"version": "0.13.1",
"resolved": "https://registry.npmjs.org/retry/-/retry-0.13.1.tgz",
"integrity": "sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==",
"license": "MIT",
"engines": {
"node": ">= 4"
}
},
"node_modules/sdp-transform": {
"version": "2.15.0",
"resolved": "https://registry.npmjs.org/sdp-transform/-/sdp-transform-2.15.0.tgz",
"integrity": "sha512-KrOH82c/W+GYQ0LHqtr3caRpM3ITglq3ljGUIb8LTki7ByacJZ9z+piSGiwZDsRyhQbYBOBJgr2k6X4BZXi3Kw==",
"license": "MIT",
"bin": {
"sdp-verify": "checker.js"
}
},
"node_modules/unhomoglyph": {
"version": "1.0.6",
"resolved": "https://registry.npmjs.org/unhomoglyph/-/unhomoglyph-1.0.6.tgz",
"integrity": "sha512-7uvcWI3hWshSADBu4JpnyYbTVc7YlhF5GDW/oPD5AxIxl34k4wXR3WDkPnzLxkN32LiTCTKMQLtKVZiwki3zGg==",
"license": "MIT"
},
"node_modules/uuid": {
"version": "11.0.4",
"resolved": "https://registry.npmjs.org/uuid/-/uuid-11.0.4.tgz",
"integrity": "sha512-IzL6VtTTYcAhA/oghbFJ1Dkmqev+FpQWnCBaKq/gUluLxliWvO8DPFWfIviRmYbtaavtSQe4WBL++rFjdcGWEg==",
"funding": [
"https://github.com/sponsors/broofa",
"https://github.com/sponsors/ctavan"
],
"license": "MIT",
"bin": {
"uuid": "dist/esm/bin/uuid"
}
}
}
}

21
package.json Normal file
View File

@ -0,0 +1,21 @@
{
"name": "matrix-bot",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "https://git.ht-dev.de/Hammer1279/matrix-bot.git"
},
"author": "Hammer1279",
"license": "MIT",
"dependencies": {
"@matrix-org/matrix-sdk-crypto-wasm": "^12.1.0",
"matrix-bot": "file:",
"matrix-js-sdk": "^35.1.0"
},
"type": "module"
}