我该如何将一个 discord.js 机器人部署到 Cloud Functions?

5

我想将基于discord.js运行的Discord机器人部署到Firebase Cloud函数上,但我无法使机器人在Firebase中运行。如果我使用nodemon,则可以完美运行,但如果我使用firebase deploy,则机器人不会启动。

以下是我的当前代码:

const functions = require('firebase-functions');

require('dotenv').config();
const token = process.env.TOKEN

const Discord = require('discord.js')
const Client = new Discord.Client();

Client.on('ready', () => {
    Client.channels.find(x => x.name === 'main-cannel').send('bot is deployed')
    Client.user.setGame(`The Cult | ${Client.guilds.size} servers`)
    Console.log('test')
});

Client.login(token);

//is is not working but de basic
//export.App = functions.... {Client}
exports.app = functions.https.onRequest((request, response) => {
    response.send("Test");
});

有任何错误信息吗?你是如何启动它的?这里需要更多的信息。 - Thomas Reichmann
抱歉@ThomasReichmann,如果我运行nodemon app.js,它会运行,但是如果我运行firebase deploy --only functions,它就无法运行了。 - Lars Rijnen
有没有人可以帮我解决这个问题啊?^^ - Lars Rijnen
当您部署代码时会发生什么? - Dharmaraj
2个回答

5

由于Cloud Functions并非为此设计而生,因此这可能不是Google Cloud Platform服务的最佳组合。 您可以在计算引擎机器上托管您的Discord机器人。

如果您想要使用动态缩放,请查看Discord Microservice Bots,其中DasWolke描述了什么是微服务。他还包括了将不同的服务拆分为Discord所需的JavaScript代码。

您可以在Google Cloud Platform上创建一个具有运行Gateway的VM。 这需要24/7运行且应轻量级。 您可以使用f1-micro(免费)进行此操作,但谷歌建议使用g1-small进行此任务。

网关应过滤您正在寻找的事件(因为Discord发送了大量事件,您不需要大部分)并将数据发送到Cloud FunctionCloud Run(您可以通过Pub/Sub发送数据)。 根据我的经验,Cloud Run启动时间更短,因此我选择了它。

在函数内部,您接收数据并根据需要进行处理。 如果您想要在Discord中执行某些操作(发送消息,管理频道等),可以使用SnowTransfer。 SnowTransfer仅调用discord上的REST API。


3
client.login(token)放在response.send("Test");处。这将提示您的机器人代码在HTTP请求时执行。
https://us-central1-<your project ID>.cloudfunctions.net/app中,将<your project ID>替换为您的项目ID。
如果Firebase Hosting给出的URL是example-123.web.app,则您的项目ID是example-123。您也可以通过控制台获取项目ID:打开Firebase控制台,选择您的项目,单击设置图标,转到“项目设置”,其ID位于表格的第二行。
为使此操作起作用,您必须直接将令牌移入代码中。不能使用像.env这样的shell文件。
最终,您的代码将是:
const functions = require('firebase-functions');
const token = 'whatever the token is';
const Discord = require('discord.js')
const Client = new Discord.Client();

Client.on('ready', () => {
    Client.channels.find(x => x.name === 'main-cannel').send('bot is deployed')
    Client.user.setGame(`The Cult | ${Client.guilds.size} servers`)
    Console.log('test')
});

exports.app = functions.https.onRequest((request, response) => {
    response.send("Test"); // Do not delete this! Your request will time out if you do.
    Client.login(token);
});

正如Gabber235所指出的,这可能不是用于此目的最好的Google Cloud Platform服务,你应该使用Compute Engine。

3
尽可能地, 请努力提供额外的解释而不仅仅是代码。这样的回答往往更有用,因为它们可以帮助社区成员和尤其是新开发人员更好地理解解决方案的原因,还可以帮助避免需要回答后续问题的情况。 - Rajan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接