So what happens is I am creating a discord bot that access the routes from express and it works if I keep it on a certain server, but if I try to access express on a different server while the server is on I get
Restarting the server removes the "assignments is not a function" So this only works when I try to access these routes endpoints from a completely different server. More information, If I try to do curl requests to these endpoints with different channel or guild id information, I also get that error. So I am assuming thats where a lot of the problem is coming from. I don't know why different information throws off the function.
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);
}
and if necessary
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);
}
}
CodePudding user response:
The problem lies in the fetchCall.js
file. First of all, you are exporting things in the wrong manner. If you are not using tools like babel, syntax export function ...
is incorrect, you have to use module.exports
to export things from a Node.js module.
So you can change your file in the following manner, for example.
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}
Also another advice to rename your functions, functions are verbs, not nouns, e.g. instead of assignments
name it getAssignments
or whatever it is doing.
UPD:
And looks like you are using wrong modules, Node.js uses CommonJS modules, so you have use require
to import other modules unless you are using TypeScript or Babel.
Change your index.js file to
const express = require('express');
const{ assignments , announcements , discussions}
= require("./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);});