I am new to programming a Discord bot (and I love it), and it has problems responding. When I start it with node main.js, it works as normal until I do something like -ping, upon which it stops working.
Here is the error that I receive:
ReferenceError: clicent is not defined
at Client.<anonymous> (C:\Users\Eric Müller\Desktop\Discord bot\Main.js:27:9)
at Client.emit (events.js:315:20)
at MessageCreateAction.handle (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
at Object.module.exports [as MESSAGE_CREATE] (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
at WebSocketManager.handlePacket (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
at WebSocketShard.onPacket (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
at WebSocketShard.onMessage (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
at WebSocket.onMessage (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\ws\lib\event-target.js:132:16)
at WebSocket.emit (events.js:315:20)
at Receiver.receiverOnMessage (C:\Users\Eric Müller\Desktop\Discord bot\node_modules\ws\lib\websocket.js:825:20)
Here is my code:
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '-';
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('Codelyon is online!');
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
}
});
client.login(' '); (DISCLAMER! THE TOKEN IS FILLED IN AND CORRECT)
ping.js:
module.exports = {
name: 'ping',
description: "this is a ping command!",
execute(message, args){
message.channel.send('pong!');
}
}
As the error suggests, you most likely have a typo somewhere in your code:
ReferenceError: clicent is not defined at Client. (C:\Users\Eric Müller\Desktop\Discord bot\Main.js:27:9)
The error tells you that at the beginning of line 27 in Main.js file, you have clicent, but it was probably supposed to be client.
Related
I'm trying to automate some tests with protractor and jasmine and I'm using async/await to resolve the promises.
The issue is, when an error does happen, the stack trace is TOO short and thus, I can't seem to locate the source of the issue.
I did make sure to put SELENIUM_PROMISE_MANAGER to FALSE in the config file.
I'm using protractor 7 along with node 14.16.0
Does anyone know how to solve this ? There are not enough details
Here's a code snippet
const invoicesButton: Button = new Button("Invoices", LocatorType.Href, "#/Invoices");
describe("Kouka test", function () {
beforeEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1000000000;
});
it("Does a random test", async function () {
await browser.get("https://appdev.expensya.com/Portal/#/Login?lang=en");
await loginEmailInput.typeText("amr.refacto#yopmail.com")
await loginPasswordInput.typeText("a")
await loginButton.click(true);
await dashboardPage.invoicesButton.click().catch((e) => {
e.stackTraceLimit = Infinity;
throw e;
});
await userInvoicesPage.createManualInvoice(invoice).catch((e) => {
e.stackTraceLimit = Infinity;
console.error("TEST ERROR ", e);
throw e;
});
await browser.sleep(10000);
});
});
And here's the definition of the "Button" Class:
import { browser } from "protractor";
import { WebComponent } from "./webComponent";
export class Button extends WebComponent {
/**
* #param webElementText Text that the web element contains.
* #param locatorType Locator type of the web element to search for.
* #param locator Locator of the web element to search for.
* #param parentElement Parent Web Component if it exists.
*/
constructor(webElementText, locatorType, locator, parentElement: WebComponent = null) {
super(webElementText, locatorType, locator, parentElement);
}
async click(usingJavaScript = false) {
if (usingJavaScript) {
await this.isPresent();
await browser.executeScript("arguments[0].click();", await this.webElement)
}
else {
await this.isVisible();
await this.isClickable();
await this.webElement.click();
}
}
}
Finally, here's the stack trace
Started
Jasmine started
undefined
F
Kouka test
× Does a random test
- Failed: Wait timed out after 10012ms
at C:\Users\Amrou Bellalouna\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2201:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:20:5)
at Object.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:15:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
Failures:
1) Kouka test Does a random test
Message:
Failed: Wait timed out after 10012ms
Stack:
TimeoutError: Wait timed out after 10012ms
at C:\Users\Amrou Bellalouna\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2201:17
at runMicrotasks (<anonymous>)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
From asynchronous test:
Error
at Suite.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:20:5)
at Object.<anonymous> (C:\Users\Amrou Bellalouna\source\repos\NewE2EArchitecture\NewArchitecture\koukouTest.spec.ts:15:1)
at Module._compile (internal/modules/cjs/loader.js:1063:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
at Module.load (internal/modules/cjs/loader.js:928:32)
at Function.Module._load (internal/modules/cjs/loader.js:769:14)
1 spec, 1 failure
Finished in 19.461 seconds
I remember trying to solve this a while ago and I couldn't. But I implemented a bunch of workarounds and apparently this was enough
To begin, can you share what these are doing
await this.isPresent();
await this.isVisible();
await this.isClickable();
Having this function
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime
)
}
you can use an advantage of third argument of browser.wait as described here and include an optional message on failure like this
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime,
`Element ${this.webElement.locator().toString()} is not present after ${this._elapsedTime}ms`);
)
}
(I'm giving you all my secret sauce ingredients haha) If you add this to onPrepare in the config
/**
* Set global environment configuration
*/
Object.defineProperty(global, '__stack', {
get: function() {
let orig = Error.prepareStackTrace;
Error.prepareStackTrace = function(_, stack) {
return stack;
};
let err = new Error();
Error.captureStackTrace(err, arguments.callee);
let stack = err.stack;
Error.prepareStackTrace = orig;
return stack;
},
});
// returns name of the file from which is called
Object.defineProperty(global, '__file', {
get: function() {
let path = __stack[1].getFileName();
try {
//*nix OSes
return path.match(/[^\/]+\/[^\/]+$/)[0];
} catch (error) {
//Windows based OSes
return path.match(/[^\\]+\\[^\\]+$/)[0];
}
},
});
// returns function name from which is called
Object.defineProperty(global, '__function', {
get: function() {
return __stack[1].getFunctionName();
},
});
// returns line number of the position in code when called
Object.defineProperty(global, '__line', {
get: function() {
return __stack[1].getLineNumber();
},
});
then you can use it for logging the file name, function name, and the line where it's called
For example,
async isVisible(){
await browser.wait(
ExpectedConditions.visibilityOf(this.webElement),
this._elapsedTime,
`Failed at ${__file} -> ${__function}() -> line ${__line}`
)
}
will result in this error
- Failed: Failed at common/index.js -> isVisible() -> line 82
Wait timed out after 1032ms
Wait timed out after 1032ms
So you can accommodate this to your needs
also I just realized you may want to play around with __stack variable itself
I am trying to use cypress select tests but facing the following exception. Did anyone face this issue before?
cypress/plugins/index.ts
const TC_GROUPING = require('cypress-select-tests/grep')
module.exports = (on, config) => {
require('cypress-terminal-report/src/installLogsPrinter')(on, {
printLogsToConsole: 'always'
}
)
on('file:preprocessor', TC_GROUPING(config))
on('task', {
// Returns the customer Object of type: Customer
createCustomer: () => {
console.log("This is Sample Function")
}
})
return config
}
Error Message:
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module' (17:0)
at Parser.pp$4.raise (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:2927:15)
at Parser.pp$1.parseStatement (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:870:18)
at Parser.pp$1.parseTopLevel (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:755:23)
at Parser.parse (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:555:17)
at Function.parse (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:578:37)
at Object.parse (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/acorn/dist/acorn.js:5143:19)
at module.exports (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/falafel/index.js:23:22)
at Object.findTests (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/cypress-select-tests/src/spec-parser.js:95:3)
at process (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/cypress-select-tests/src/itify.js:18:33)
at Stream.onend (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/cypress-select-tests/src/itify.js:52:18)
at _end (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/through/index.js:65:9)
at Stream.stream.end (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/through/index.js:74:5)
at DestroyableTransform.onend (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:577:10)
at Object.onceWrapper (events.js:416:28)
at DestroyableTransform.emit (events.js:322:22)
at endReadableNT (/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/node_modules/through2/node_modules/readable-stream/lib/_stream_readable.js:1010:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Error: The following error was thrown by a plugin. We stopped running your tests because a plugin crashed. Please check your plugins file (`/Users/saahithg/workspace/ElmoCypressFinal/src/ElmoCypress/cypress/plugins/index.ts`)
at Object.get (/private/tmp/cypress_cache/5.4.0/Cypress.app/Contents/Resources/app/packages/server/lib/errors.js:968:15)
at EventEmitter.handleError (/private/tmp/cypress_cache/5.4.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/index.js:159:20)
at EventEmitter.emit (events.js:310:20)
at ChildProcess.<anonymous> (/private/tmp/cypress_cache/5.4.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:19:22)
at ChildProcess.emit (events.js:310:20)
at emit (internal/child_process.js:876:12)
at processTicksAndRejections (internal/process/task_queues.js:85:21)
Added the following lines in plugins/index.ts as mentioned in blog: https://en.it1352.com/article/1963119.html but no luck. Did anyone encounter this issue?
const options = {
// send in the options from your webpack.config.js, so it works the same
// as your app's code
webpackOptions: require('../../webpack.config'),
watchOptions: {}
}
on('file:preprocessor', web_pack(options))
webpack.config.js
const path = require('path');
module.exports = {
entry: './src/index.ts',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
},
};
When the job is running on Azure DevOps yarn test:unit the following error happens multiple times. This does not prevent tests to pass. The project runs vue and jest for testing. When runs locally, no errors occur.
jest.config.js
const Vue = require('vue');
const Vuetify = require('vuetify');
Vue.use(Vuetify);
module.exports = {
preset: '#vue/cli-plugin-unit-jest/presets/typescript-and-babel',
collectCoverage: false,
collectCoverageFrom: [
'src/**/*.{js,vue}',
'!src/registerServiceWorker.js',
'!src/helpers.js',
'!src/constants/**',
'!src/mixins/**',
'!src/plugins/**',
'!src/router/**',
'!src/test/**',
'!src/main.js', // No need to cover bootstrap file
],
transform: {
'vee-validate/dist/rules': 'babel-jest',
},
transformIgnorePatterns: [
'<roodDir>/node_modules/(?!vee-validate/dist/rules)',
],
testEnvironmentOptions: {
// Allow test environment to fire onload event
// See https://github.com/jsdom/jsdom/issues/1816#issuecomment-355188615
resources: 'usable',
},
};
axios.js
let baseURL = '';
switch (process.env.NODE_ENV) {
case 'development': {
baseURL = 'https://localhost:44359/api/v1';
break;
}
case 'production': {
baseURL = 'webapi/api/v1';
break;
}
case 'docker': {
const port = process.env.VUE_APP_WebAPI_PORT;
const path = process.env.VUE_APP_WebAPI_Path;
const version = process.env.VUE_APP_WebAPI_Version;
const url = new URL(window.location.origin);
url.port = port;
baseURL = `${url.origin.toString()}/${path}/${version}`;
break;
}
default: baseURL = 'webapi/api/v1';
}
/* eslint-disable import/prefer-default-export */
export const http = axios.create({
baseURL,
withCredentials: true,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
paramsSerializer: (params) => {
Object.keys(params).forEach((key) => {
if (_isArray(params[key]) && !params[key].length) {
delete params[key];
}
});
return qs.stringify(params, { arrayFormat: 'repeat' });
},
});
Error
Error: Error: connect ECONNREFUSED 127.0.0.1:80
at Object.dispatchError (/home/vsts/work/1/s/node_modules/jsdom/lib/jsdom/living/xhr-utils.js:54:19)
at Request. (/home/vsts/work/1/s/node_modules/jsdom/lib/jsdom/living/xmlhttprequest.js:675:20)
at Request.emit (events.js:327:22)
at Request.onRequestError (/home/vsts/work/1/s/node_modules/request/request.js:877:8)
at ClientRequest.emit (events.js:315:20)
at Socket.socketErrorListener (_http_client.js:426:9)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) undefined
console.error node_modules/jsdom/lib/jsdom/virtual-console.js:29
Any help would be welcome
This error could be due to i18n usage. I have noticed that when I have the same problem and debug it, it gets this error because it cannot access localization files. You can use the moduleNameMapper setting as a solution.
https://jestjs.io/docs/en/configuration#modulenamemapper-objectstring-string--arraystring
I am unable to understand why nodemailer is not working properly within a VUE.js app.
The code is from the nodemailer examples. Here is the method I call on form submit:
methods: {
submit() {
this.$refs.form.validate().then(() => {
"use strict";
const nodemailer = require("nodemailer");
async function main() {
let transporter = nodemailer.createTransport({
host:'mail.kakakakak',
port: 465,
secure: true,
auth: {
user: 'info#',
pass: '****'
}
});
// send mail with defined transport object
let info = await transporter.sendMail({
from: '"Fred Foo 👻" <foo#example.com>', // sender address
to: "info#lopezi.com",
subject: "Hello ✔", // Subject line
text: "Hello world?", // plain text body
html: "<b>Hello world?</b>" // html body
});
console.log("Message sent: %s", info.messageId);
}
main().catch(console.error);
});
},
}
The first time I click the submit button I get the error:
Uncaught (in promise) Error: Cannot find module 'net'
at webpackEmptyContext (eval at ./node_modules/defaultable sync recursive (app.5176eebb0babf67e88fb.hot-update.js:22), <anonymous>:2:10)
at Object.workaround_require (defaultable.js?6987:49)
at require (defaultable.js?6987:77)
at eval (server.js?663d:9)
at defaulter (defaultable.js?6987:83)
at defaultable (defaultable.js?6987:63)
at good (defaultable.js?6987:174)
at Object.eval (server.js?663d:5)
at eval (server.js:242)
at Object../node_modules/hbo-dnsd/server.js (chunk-vendors.5176eebb0babf67e88fb.hot-update.js:2053)
The second time I click the submit button, still with the same content in there I get the error:
TypeError: nodemailer.createTransport is not a function
at _callee$ (ContactForm.vue?2be1:64)
at tryCatch (runtime.js?96cf:45)
at Generator.invoke [as _invoke] (runtime.js?96cf:271)
at Generator.prototype.<computed> [as next] (runtime.js?96cf:97)
at asyncGeneratorStep (asyncToGenerator.js?3b8d:5)
at _next (asyncToGenerator.js?3b8d:27)
at eval (asyncToGenerator.js?3b8d:34)
at new Promise (<anonymous>)
at new F (_export.js?63b6:36)
at eval (asyncToGenerator.js?3b8d:23)
I'm trying to send a simple POST request for a contact form in a static site built on top of NuxtJs.
Im trying to use express and nodemailer in the serverMiddleware Nuxt provides
here's the code from api/contact.js
const express = require('express')
const nodemailer = require('nodemailer')
const validator = require('validator')
const xssFilters = require('xss-filters')
const app = express()
app.use(express.json())
const rejectFunctions = new Map([
['name', a => a.trim().length < 4],
['email', v => !validator.isEmail(v)],
['message', v => v.trim().length < 10]
])
const validateAndSanitize = (key, value) => {
return (
rejectFunctions.has(key) &&
!rejectFunctions.get(key)(value) &&
xssFilters.inHTMLData(value)
)
}
const sendMail = (name, email, msg) => {
const transporter = nodemailer.createTransport({
sendmail: true,
newline: 'unix',
path: '/usr/sbin/sendmail'
})
transporter.sendMail(
{
from: email,
to: 'johndoe#mail.com',
subject: 'New Contact Form',
text: msg
}
)
}
app.post('/', (req, res) => {
const attributes = ['name', 'email', 'message']
const sanitizedAttributes = attributes.map(attr =>
validateAndSanitize(attr, req.body[attr])
)
const someInvalid = sanitizedAttributes.some(r => !r)
if (someInvalid) {
return res
.status(422)
.json({ error: 'Error : at least one fiel is invalid' })
}
sendMail(...sanitizedAttributes)
res.status(200).json({ message: 'OH YEAH' })
})
export default {
path: '/api/contact',
handler: app
}
Everything works as intended until the sendMail function where I end up with this error :
(node:10266) UnhandledPromiseRejectionWarning: Error: spawn /usr/sbin/sendmail ENOENT
at Process.ChildProcess._handle.onexit (internal/child_process.js:246:19)
at onErrorNT (internal/child_process.js:427:16)
at processTicksAndRejections (internal/process/next_tick.js:76:17)
(node:10266) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 6)
Any idea what Im doing wrong?
The error
Error: spawn /usr/sbin/sendmail ENOENT
suggests that nodemailer was looking for sendmail in /usr/sbin/ but haven't found it (this is the default location and can be configured in the path option of createTransport). First, make sure it doesn't exist (like AnFi has suggested) by running
ls -l /usr/sbin/sendmail
If you get
ls: cannot access '/usr/bin/sendmail': No such file or directory
then install sendmail by running
sudo apt-get install sendmail
Then, try ls -l /usr/sbin/sendmail and sending email again.