From 00d3d058834d629a265bbef9134f0668bba5f371 Mon Sep 17 00:00:00 2001 From: Drew Short Date: Tue, 7 Jan 2020 14:30:24 -0600 Subject: [PATCH] Allowing the bot to upload an avatar --- bot/bot.js | 38 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/bot/bot.js b/bot/bot.js index 0baf1e3..0c625b5 100644 --- a/bot/bot.js +++ b/bot/bot.js @@ -1,3 +1,4 @@ +let fs = require('fs'); let sdk = require('matrix-js-sdk'); let message = require('./message'); let utility = require('./utility'); @@ -25,6 +26,7 @@ class Bot { case "PREPARED": this.connected = true; await this.sendStatusStartup(); + await this.updateAvatar(process.env.NODE_PATH + '/assets/avatar.jpg'); this.client.getJoinedRooms() .done((rooms) => { logger.info("Connected to: %o", rooms) @@ -94,6 +96,42 @@ class Bot { botClient.loginWithToken(this.config.accessToken, connectWithToken); } + updateAvatar(avatarFile, overwrite=false) { + let matrixClient = this.client; + let botConfig = this.config; + let promises = [Promise.resolve(true)]; + if (this.connected) { + promises.push(this.client.getProfileInfo(this.config.userId, "avatar_url") + .then((existingAvatarUrl) => { + logger.info("Recieved avatar_url: %o", existingAvatarUrl); + if (typeof existingAvatarUrl !== 'undefined' && typeof existingAvatarUrl == 'object' + && existingAvatarUrl.constructor === Object && Object.keys(existingAvatarUrl).length !== 0 + && !overwrite) { + logger.info("Avatar already set"); + } else { + logger.info("Setting avatar content from %s", avatarFile); + let avatarFileBuffer = fs.readFileSync(avatarFile); + logger.debug("Avatar Image Data %o", avatarFileBuffer); + matrixClient.uploadContent(avatarFileBuffer, { + name: botConfig.userId + " avatar", + type: "image/jpeg", + rawResponse: false + }).then((uploadedAvatar) => { + logger.info("Uploaded avatar %o", uploadedAvatar); + matrixClient.setAvatarUrl(uploadedAvatar.content_uri) + .then(() => { + logger.info("Updated %s avatar to %s", botConfig.userId, uploadedAvatar.content_uri); + return true; + }); + }); + } + })); + } else { + logger.warn("Attempting to update avatar while disconnected"); + } + return Promise.all(promises); + } + sendStatusStartup() { let promises = [Promise.resolve(true)] if (this.connected) {