Discord chat bot to announce projects (#590) (#600)

* Discord chat bot to announce projects (#590)

Add support for discord chat bot to announce when images are set, with instructions on configuring for dev. This uses the REST
API instead of a websocket connection, which is needed for serverless deployment.

Co-authored-by: Kurt Hutten <k.hutten@protonmail.ch>

* Remove discord.js dependency.

Co-authored-by: Kurt Hutten <k.hutten@protonmail.ch>
This commit was merged in pull request #600.
This commit is contained in:
Scott Martin
2022-01-22 21:17:08 -05:00
committed by GitHub
parent 861b8374bf
commit 0a6439161e
7 changed files with 87 additions and 7 deletions

View File

@@ -0,0 +1,33 @@
import axios from 'axios'
let inst = null;
if (!process.env.DISCORD_TOKEN || !process.env.DISCORD_CHANNEL_ID) {
console.warn("Discord bot not configured - please set process.env.DISCORD_TOKEN and process.env.DISCORD_CHANNEL_ID to send discord chats");
} else {
inst = axios.create({
baseURL: 'https://discord.com/api'
});
inst.defaults.headers.common['Authorization'] = `Bot ${process.env.DISCORD_TOKEN}`
console.log(`Discord: using API token ${process.env.DISCORD_TOKEN}`);
}
export async function sendDiscordMessage(text: string, url?: string) {
if (!inst) {
console.error(`Discord: not configured to send message ("${text}")`);
} else {
const API_URL = `/channels/${process.env.DISCORD_CHANNEL_ID}/messages`;
if (url) {
return inst.post(API_URL, { embeds: [{
title: text,
image: {
url,
},
}] });
} else {
return inst.post(API_URL, {
content: text,
});
}
}
}

View File

@@ -12,6 +12,8 @@ import {
} from 'src/services/helpers'
import { requireAuth } from 'src/lib/auth'
import { requireOwnership, requireProjectOwnership } from 'src/lib/owner'
import { sendDiscordMessage } from 'src/lib/discord'
export const projects = ({ userName }) => {
if (!userName) {
@@ -243,7 +245,19 @@ export const updateProjectImages = async ({
const [updatedProject] = await Promise.all([
projectPromise,
imageDestroyPromise,
])
]).then(async (result) => {
const { userName } = await db.user.findUnique({
where: { id: project.userId },
})
sendDiscordMessage([
`${userName} just added an image to their ${project.cadPackage} project:`,
` => ${project.title}`,
``,
`Check it out, leave a comment, make them feel welcome!`,
`https://cadhub.xyz/u/${userName}/${project.title}`
].join('\n'), `https://res.cloudinary.com/irevdev/image/upload/c_scale,w_700/v1/${mainImage}`)
return result
})
return updatedProject
}