我的快速路由不适用于不同的不和谐服务器
My express routing not working on different discord servers
所以我正在创建一个从 express 访问路由的 discord 机器人,如果我将它保存在某个服务器上,它就可以工作,但是如果我尝试在另一台服务器上访问 express,而服务器处于打开状态,我得到
重新启动服务器会删除“分配不是函数”,因此这仅在我尝试从完全不同的服务器访问这些路由端点时有效。更多信息,如果我尝试使用不同的通道或公会 ID 信息对这些端点执行 curl 请求,我也会收到该错误。所以我假设这就是很多问题的来源。我不知道为什么不同的信息会导致功能失效。
index.js
import express, { json, query, request, response } from 'express';
import { assignments , announcements , discussions} from "./Fetch/fetchCalls.js";
var app = express();
app.use(express.json());
const PORT = 8080;
app.listen(PORT);
var guild;
var channel;
app.all('/assignments',(request) => {assignments(guild = request.body.guild, channel = request.body.channel);});
app.all('/discussions',(request) => {discussions(guild = request.body.guild,channel = request.body.channel); });
app.all('/announcements', (request) => {announcements(guild = request.body.guild,channel = request.body.channel);});
fetchCalls.js
import fetch from 'node-fetch';
import { createRequire } from "module";
import { getRecord, updateChannelID } from './dbUtil.js';
import { clearData } from './clear.js';
const require = createRequire(import.meta.url);
const config = require("../Canvas Bot/Source/Data/config.json")
var obj;
var course;
var url;
var access_token;
var guildid;
var channelid;
export function discussions(guild,channel) {
guildid = guild;
channelid = channel;
discussionsFunc();
async function discussionsFunc(){
try {
updateChannelID(guildid,channelid);
await getRecord({ guild_id : `${guildid}`}, getFetchData);
const res1 = await fetch(url + `courses/${course}/discussion_topics?scope=unlocked`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
for(discussions of apiData){
const string = ["**TOPIC: "+discussions.title +"**", discussions.message + "\n"];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`,
{
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
}
} catch (err) {
console.log(err);
}
}
clearData();
};
export function announcements(guild,channel) {
guildid = guild;
channelid = channel;
announcementsFunc();
async function announcementsFunc(){
updateChannelID(guildid,channelid);
try {
await getRecord({ guild_id : `${guildid}`}, getFetchData);
const res1 = await fetch(url + `/announcements?context_codes[]=${obj}&latest_only=true`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}` ,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
for( announcements of apiData){
const string = [`\`\`\`${announcements.title}\n`, `${announcements.message}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`,
{
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
export function assignments(guild, channel) {
guildid = guild;
channelid = channel;
assignmentsFunc();
async function assignmentsFunc(){
updateChannelID(guildid,channelid);
try {
await getRecord({guild_id : `${guildid}`}, getFetchData);
const res1 = await fetch(url + `/courses/${course}/assignments?order_by=due_at`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
var size = apiData.length-1;
for( assignments of apiData){
const string = [`\`\`\`Name: ${assignments.name}`, `Description:\n ${assignments.description}`,`Due Date: ${assignments.due_at}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`,
{
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
function getFetchData(document) {
obj = 'course_' + document._courseid;
course = document._courseid;
course1 = "_" + course;
url = 'https://' + document.prefix + '.instructure.com/api/v1/';
access_token = document.access_token;
console.log('obj = ' + obj + '\ncourse = ' + course + '\nurl = ' + url + '\naccess_token = ' + access_token);
}
如有必要
dbUtil.js
import { MongoClient } from 'mongodb';
const uri = 'cluser uri';
const client = new MongoClient(uri)
export async function updateChannelID(guildids, channelids) {
try{
await client.connect();
// db name and collection
const database = client.db("Users");
const docs = database.collection("user_info");
var query = {guild_id: `${guildids}`};
var insert = {$set: {channel_id: `${channelids}`}};
// find the first record matching the given query
docs.updateOne(query,insert);
}
catch(error){
console.log(error);
}
}
问题出在fetchCall.js
文件上。首先,您以错误的方式导出内容。如果你没有使用像 babel 这样的工具,语法 export function ...
不正确,你必须使用 module.exports
从 Node.js 模块导出东西。
因此您可以通过以下方式更改您的文件,例如。
function discussions(guild, channel) {
guildid = guild;
channelid = channel;
discussionsFunc();
async function discussionsFunc() {
try {
updateChannelID(guildid, channelid);
await getRecord({
guild_id: `${guildid}`
}, getFetchData);
const res1 = await fetch(url + `courses/${course}/discussion_topics?scope=unlocked`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
for (discussions of apiData) {
const string = ["**TOPIC: " + discussions.title + "**", discussions.message + "\n"];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`, {
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
}
} catch (err) {
console.log(err);
}
}
clearData();
};
function announcements(guild, channel) {
guildid = guild;
channelid = channel;
announcementsFunc();
async function announcementsFunc() {
updateChannelID(guildid, channelid);
try {
await getRecord({
guild_id: `${guildid}`
}, getFetchData);
const res1 = await fetch(url + `/announcements?context_codes[]=${obj}&latest_only=true`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
for (announcements of apiData) {
const string = [`\`\`\`${announcements.title}\n`, `${announcements.message}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`, {
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
function assignments(guild, channel) {
guildid = guild;
channelid = channel;
assignmentsFunc();
async function assignmentsFunc() {
updateChannelID(guildid, channelid);
try {
await getRecord({
guild_id: `${guildid}`
}, getFetchData);
const res1 = await fetch(url + `/courses/${course}/assignments?order_by=due_at`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
var size = apiData.length - 1;
for (assignments of apiData) {
const string = [`\`\`\`Name: ${assignments.name}`, `Description:\n ${assignments.description}`, `Due Date: ${assignments.due_at}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`, {
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
function getFetchData(document) {
obj = 'course_' + document._courseid;
course = document._courseid;
course1 = "_" + course;
url = 'https://' + document.prefix + '.instructure.com/api/v1/';
access_token = document.access_token;
console.log('obj = ' + obj + '\ncourse = ' + course + '\nurl = ' + url + '\naccess_token = ' + access_token);
}
module.exports = {assignments, discussions, announcements}
还有一个重命名函数的建议,函数是动词,不是名词,例如而不是 assignments
将其命名为 getAssignments
或任何它正在做的事情。
更新:
看起来你使用了错误的模块,Node.js 使用了 CommonJS 模块,所以你必须使用 require
导入其他模块,除非你使用 TypeScript 或 Babel。
将您的 index.js 文件更改为
const express = require('express');
const{ assignments , announcements , discussions}
= require("./Fetch/fetchCalls.js");
var app = express();
app.use(express.json());
常量端口 = 8080;
app.listen(港口);
var guild;
var channel;
app.all('/assignments',(request) => {assignments(guild = request.body.guild, channel = request.body.channel);});
app.all('/discussions',(request) => {discussions(guild = request.body.guild,channel = request.body.channel); });
app.all('/announcements', (request) => {announcements(guild = request.body.guild,channel = request.body.channel);});
所以我正在创建一个从 express 访问路由的 discord 机器人,如果我将它保存在某个服务器上,它就可以工作,但是如果我尝试在另一台服务器上访问 express,而服务器处于打开状态,我得到
重新启动服务器会删除“分配不是函数”,因此这仅在我尝试从完全不同的服务器访问这些路由端点时有效。更多信息,如果我尝试使用不同的通道或公会 ID 信息对这些端点执行 curl 请求,我也会收到该错误。所以我假设这就是很多问题的来源。我不知道为什么不同的信息会导致功能失效。
index.js
import express, { json, query, request, response } from 'express';
import { assignments , announcements , discussions} from "./Fetch/fetchCalls.js";
var app = express();
app.use(express.json());
const PORT = 8080;
app.listen(PORT);
var guild;
var channel;
app.all('/assignments',(request) => {assignments(guild = request.body.guild, channel = request.body.channel);});
app.all('/discussions',(request) => {discussions(guild = request.body.guild,channel = request.body.channel); });
app.all('/announcements', (request) => {announcements(guild = request.body.guild,channel = request.body.channel);});
fetchCalls.js
import fetch from 'node-fetch';
import { createRequire } from "module";
import { getRecord, updateChannelID } from './dbUtil.js';
import { clearData } from './clear.js';
const require = createRequire(import.meta.url);
const config = require("../Canvas Bot/Source/Data/config.json")
var obj;
var course;
var url;
var access_token;
var guildid;
var channelid;
export function discussions(guild,channel) {
guildid = guild;
channelid = channel;
discussionsFunc();
async function discussionsFunc(){
try {
updateChannelID(guildid,channelid);
await getRecord({ guild_id : `${guildid}`}, getFetchData);
const res1 = await fetch(url + `courses/${course}/discussion_topics?scope=unlocked`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
for(discussions of apiData){
const string = ["**TOPIC: "+discussions.title +"**", discussions.message + "\n"];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`,
{
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
}
} catch (err) {
console.log(err);
}
}
clearData();
};
export function announcements(guild,channel) {
guildid = guild;
channelid = channel;
announcementsFunc();
async function announcementsFunc(){
updateChannelID(guildid,channelid);
try {
await getRecord({ guild_id : `${guildid}`}, getFetchData);
const res1 = await fetch(url + `/announcements?context_codes[]=${obj}&latest_only=true`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}` ,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
for( announcements of apiData){
const string = [`\`\`\`${announcements.title}\n`, `${announcements.message}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`,
{
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
export function assignments(guild, channel) {
guildid = guild;
channelid = channel;
assignmentsFunc();
async function assignmentsFunc(){
updateChannelID(guildid,channelid);
try {
await getRecord({guild_id : `${guildid}`}, getFetchData);
const res1 = await fetch(url + `/courses/${course}/assignments?order_by=due_at`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
var size = apiData.length-1;
for( assignments of apiData){
const string = [`\`\`\`Name: ${assignments.name}`, `Description:\n ${assignments.description}`,`Due Date: ${assignments.due_at}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`,
{
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
function getFetchData(document) {
obj = 'course_' + document._courseid;
course = document._courseid;
course1 = "_" + course;
url = 'https://' + document.prefix + '.instructure.com/api/v1/';
access_token = document.access_token;
console.log('obj = ' + obj + '\ncourse = ' + course + '\nurl = ' + url + '\naccess_token = ' + access_token);
}
如有必要
dbUtil.js
import { MongoClient } from 'mongodb';
const uri = 'cluser uri';
const client = new MongoClient(uri)
export async function updateChannelID(guildids, channelids) {
try{
await client.connect();
// db name and collection
const database = client.db("Users");
const docs = database.collection("user_info");
var query = {guild_id: `${guildids}`};
var insert = {$set: {channel_id: `${channelids}`}};
// find the first record matching the given query
docs.updateOne(query,insert);
}
catch(error){
console.log(error);
}
}
问题出在fetchCall.js
文件上。首先,您以错误的方式导出内容。如果你没有使用像 babel 这样的工具,语法 export function ...
不正确,你必须使用 module.exports
从 Node.js 模块导出东西。
因此您可以通过以下方式更改您的文件,例如。
function discussions(guild, channel) {
guildid = guild;
channelid = channel;
discussionsFunc();
async function discussionsFunc() {
try {
updateChannelID(guildid, channelid);
await getRecord({
guild_id: `${guildid}`
}, getFetchData);
const res1 = await fetch(url + `courses/${course}/discussion_topics?scope=unlocked`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
for (discussions of apiData) {
const string = ["**TOPIC: " + discussions.title + "**", discussions.message + "\n"];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`, {
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
}
} catch (err) {
console.log(err);
}
}
clearData();
};
function announcements(guild, channel) {
guildid = guild;
channelid = channel;
announcementsFunc();
async function announcementsFunc() {
updateChannelID(guildid, channelid);
try {
await getRecord({
guild_id: `${guildid}`
}, getFetchData);
const res1 = await fetch(url + `/announcements?context_codes[]=${obj}&latest_only=true`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
for (announcements of apiData) {
const string = [`\`\`\`${announcements.title}\n`, `${announcements.message}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`, {
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
function assignments(guild, channel) {
guildid = guild;
channelid = channel;
assignmentsFunc();
async function assignmentsFunc() {
updateChannelID(guildid, channelid);
try {
await getRecord({
guild_id: `${guildid}`
}, getFetchData);
const res1 = await fetch(url + `/courses/${course}/assignments?order_by=due_at`, {
method: "GET",
headers: {
Authorization: `Bearer ${access_token}`,
"Content-Type": "application/json",
},
});
const apiData = await res1.json();
console.log(apiData);
var size = apiData.length - 1;
for (assignments of apiData) {
const string = [`\`\`\`Name: ${assignments.name}`, `Description:\n ${assignments.description}`, `Due Date: ${assignments.due_at}\n\`\`\``];
const res2 = await fetch(
`https://discordapp.com/api/channels/${channelid}/messages`, {
method: "POST",
headers: {
"Authorization": `Bot ${config.TOKEN}`,
Accept: "application/json",
"Content-Type": "application/json",
},
"Connection": "close",
body: JSON.stringify({
content: string.join('\n').replace(/(<([^>]+)>)/gi, "")
}),
}
);
const apiResponse = await res2.json();
console.log(apiResponse);
}
} catch (err) {
console.log(err);
}
}
clearData();
}
function getFetchData(document) {
obj = 'course_' + document._courseid;
course = document._courseid;
course1 = "_" + course;
url = 'https://' + document.prefix + '.instructure.com/api/v1/';
access_token = document.access_token;
console.log('obj = ' + obj + '\ncourse = ' + course + '\nurl = ' + url + '\naccess_token = ' + access_token);
}
module.exports = {assignments, discussions, announcements}
还有一个重命名函数的建议,函数是动词,不是名词,例如而不是 assignments
将其命名为 getAssignments
或任何它正在做的事情。
更新:
看起来你使用了错误的模块,Node.js 使用了 CommonJS 模块,所以你必须使用 require
导入其他模块,除非你使用 TypeScript 或 Babel。
将您的 index.js 文件更改为
const express = require('express');
const{ assignments , announcements , discussions}
= require("./Fetch/fetchCalls.js"); var app = express(); app.use(express.json()); 常量端口 = 8080; app.listen(港口);
var guild;
var channel;
app.all('/assignments',(request) => {assignments(guild = request.body.guild, channel = request.body.channel);});
app.all('/discussions',(request) => {discussions(guild = request.body.guild,channel = request.body.channel); });
app.all('/announcements', (request) => {announcements(guild = request.body.guild,channel = request.body.channel);});