How do I fix my Discord bot being offline? - node.js

I got recently interested in discord bots coding and I don't know what the problem is with this error, I tried different solutions I can find but all of them are not working and my bot is still offline on the server.
Error: Invalid transport, must be an object with a log method.
at new LegacyTransportStream (C:\Users\redacted\Desktop\NinyaBot\node_modules\winston-transport\legacy.js:18:11)
at DerivedLogger.add (C:\Users\redacted\Desktop\NinyaBot\node_modules\winston\lib\winston\logger.js:345:11)
at Object.winston.<computed> [as add] (C:\Users\redacted\Desktop\NinyaBot\node_modules\winston\lib\winston.js:110:68)
at Object.<anonymous> (C:\Users\redacted\Desktop\NinyaBot\bot.js:6:8)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:74:12)
at internal/main/run_main_module.js:18:47
this is the code i used that i found online.
var Discord = require('discord.io');
var logger = require('winston');
var auth = require('./auth.json');
// Configure logger settings
logger.remove(logger.transports.Console);
logger.add(logger.transports.Console, {
colorize: true
});
logger.level = 'debug';
// Initialize Discord Bot
var bot = new Discord.Client({
token: auth.token,
autorun: true
});
bot.on('ready', function (evt) {
logger.info('Connected');
logger.info('Logged in as: ');
logger.info(bot.username + ' - (' + bot.id + ')');
});
bot.on('message', function (user, userID, channelID, message, evt) {
// Our bot needs to know if it will execute a command
// It will listen for messages that will start with `!`
if (message.substring(0, 1) == '!') {
var args = message.substring(1).split(' ');
var cmd = args[0];
args = args.splice(1);
switch(cmd) {
// !ping
case 'ping':
bot.sendMessage({
to: channelID,
message: 'Pong!'
});
break;
// Just add any case commands if you want to..
}
}
});

The error showed in console is about line 6, however maybe is not what makes the
bot appears offline.
logger.add(logger.transports.Console, {
colorize: true
});
And should be fixed with something like
logger.add(new logger.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
winston.format.simple()
)
}));
Watch to new word. Now transports require a new object to work and for colorize you can set it combining the formats.
Here you can find more info about it https://www.npmjs.com/package/winston#common-transport-options

I recommend using discord.js https://discordjs.guide/creating-your-bot/#creating-the-bot-file
Use this code and it work just fine:
const Discord = require('discord.js');
const client = new Discord.Client();
client.once('ready', () => {
console.log('Ready!');
});
client.login('your-token-goes-here');

Related

Unexpected token '.' while trying to use Nodemailer SES transport sdk

I need to extend the functionality of my SMTP feature to handle bulk emails. It works fine, however when a big amount of emails presented it sends them very slowly (about 2-3 per second). Our current AWS plan allows up to 15 emails per second. I read NodeMailer documentation and tried to implement the SES SDK, however it crashes my app right away.
Here is an error:
/home/node/app/node_modules/#aws-sdk/client-ses/dist-cjs/protocols/Aws_query.js:3734
if (input.ReplacementTags?.length === 0) {
^
SyntaxError: Unexpected token '.'
at wrapSafe (internal/modules/cjs/loader.js:915:16)
at Module._compile (internal/modules/cjs/loader.js:963:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/node/app/node_modules/#aws-sdk/client-ses/dist-cjs/commands/CloneReceiptRuleSetCommand.js:8:21)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
[nodemon] app crashed - waiting for file changes before starting...
Here is my dependency list:
"#aws-sdk/client-ses": "^3.204.0",
"#aws-sdk/credential-provider-node": "^3.204.0",
"nodemailer": "^6.4.16"
And here is my nodeMailer code:
require('dotenv').config()
const nodemailer = require('nodemailer')
const Settings = require('./agentLogic/settings')
const Util = require('./util')
let aws = require('#aws-sdk/client-ses') // new feature I'm trying to implement
let {defaultProvider} = require('#aws-sdk/credential-provider-node') // new feature I'm trying to implement
const ses = new aws.SES({
apiVersion: '2010-12-01',
region: 'us-west-2',
defaultProvider,
}) // new feature I'm trying to implement
let currentSMTP = {}
async function emailService() {
currentSMTP = await Settings.getSMTP()
const decryptedPassword = Util.decrypt(
currentSMTP.dataValues.value.auth.pass,
currentSMTP.dataValues.value.IV,
)
const transporter = nodemailer.createTransport({
host: currentSMTP.dataValues.value.host,
// Defaults to 587 if "secure" is false or no value provided or 465 if true
port:
currentSMTP.dataValues.value.encryption === false
? 587
: !currentSMTP.dataValues.value.encryption
? 587
: currentSMTP.dataValues.value.encryption,
// False for STARTTLS (must use port 587), true for TLS (must use port 465)
secure: !currentSMTP.dataValues.value.encryption
? false
: currentSMTP.dataValues.value.encryption,
auth: {
user: currentSMTP.dataValues.value.auth.mailUsername
? currentSMTP.dataValues.value.auth.mailUsername
: currentSMTP.dataValues.value.auth.email,
pass: decryptedPassword,
},
tls: {
// Change to "false" to not fail on invalid certs
rejectUnauthorized: true,
},
SES: {ses, aws}, // new feature I'm trying to implement
sendingRate: 15, // new feature I'm trying to implement (I need this to match our current AWS SMTP plan of 15 emails/second)
})
return transporter
}
const sendMail = async (message) => {
const transporter = await emailService()
return new Promise((resolve, reject) => {
transporter.sendMail(message, (error, info) => {
if (error) {
console.log('Error occurred')
console.log(error.message)
reject('error')
} else {
console.log('Message sent successfully!')
console.log(nodemailer.getTestMessageUrl(info))
resolve(true)
}
// Only needed when using pooled connections
transporter.close()
})
})
}
Please, note that by default all the SMTP settings are not set. The user may or may not set the SMTP on demand. But the app comes without some SMTP preset values (such as host, username, email etc)
Can anyone help me understand why I'm getting and how to fix it?

DiscordJS - Send Message

Im Trying To Send A Message Through DiscordJS
Can Someone Help Me
I Tried This Code
const channel = client.channels.cache.get('example discord guild');
channel.send('content');
But It Doesent Work
index.js
// Credetials
const { token } = require('./json/token.json');
const { guild } = require('./json/guild.json');
const { client } = require('./json/client.json')
// Init
const { Client, Intents } = require('discord.js');
const bot = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_>
bot.login(guild);
console.log("Logged In As DeltaBOT");
const channel = client.channels.cache.get(guild);
channel.send('content');
Error
const channel = client.channels.cache.get(guild);
^
TypeError: Cannot read properties of undefined (reading 'cache')
at Object.<anonymous> (/storage/emulated/0/Download/node/index.js:15:33)
at Module._compile (node:internal/modules/cjs/loader:1097:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1149:10)
at Module.load (node:internal/modules/cjs/loader:975:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
at node:internal/main/run_main_module:17:47
You should wait for your client to login before attempting to send a message / fetching a channel. You can do this by using the ready event. For example:
bot.on('ready', async () => {
console.log('Logged in as: ' + bot.user.tag);
const channel = await bot.channels.fetch(guild);
await channel.send('content');
})
Another thing I noticed is that you use client instead of bot. client is a json object but you defined your discord bot object as the bot variable. So use the bot variable and not the client one.
Make sure that the guild is a valid guild ID. I don't know what is in your client json file but you don't appear to be using it.

Discord won't turn on

I need to create bridge from telegram to my discorcd channel, however i will receive error when i will run the .js script.
throw new TypeError('CLIENT_MISSING_INTENTS');
^
TypeError [CLIENT_MISSING_INTENTS]: Valid intents must be provided for the Client.
at Client._validateOptions (\dev\tele-discord-bot\node_modules\discord.js\src\client\Client.js:544:13)
at new Client (\dev\tele-discord-bot\node_modules\discord.js\src\client\Client.js:73:10)
at Object.<anonymous> (\dev\tele-discord-bot\bridge.js:19:14)
at Module._compile (node:internal/modules/cjs/loader:1101:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:79:12)
at node:internal/main/run_main_module:17:47 {
[Symbol(code)]: 'CLIENT_MISSING_INTENTS'
}
This is the error and here is the code i used:
const TelegramBot = require('node-telegram-bot-api'); // https://github.com/yagop/node-telegram-bot-api
const Discord = require('discord.js'); // https://github.com/discordjs/discord.js
/* Values:
token: Telegram bot token (logging into Telegram's API, you can get this from #BotFather on Telegram)
token2: Discord bot token (logging into Discord's API, you can get this from Discord's developer docs > my apps > app)
channelid: Discord channel ID (channel the Discord bot can access, right clicking a channel and clicking copy ID with developer mode enabled)
*/
const token = 'TELEGRAMTOKEN';
const token2 = 'DISCORDTOKEN';
const channelid = 'DISCRODCHANNELID';
/* Bots:
bot: Telegram bot
bot2: Discord bot
*/
const bot = new TelegramBot(token, {polling: true});
const bot2 = new Discord.Client();
// Matches "/echo [whatever]" in Telegram chat
bot.onText(/\/echo (.+)/, (msg, match) => {
// 'msg' is the received Message from Telegram
// 'match' is the result of executing the regexp above on the text content
// of the message
const chatId = msg.chat.id;
const resp = match[1]; // the captured "whatever"
// send back the matched "whatever" to the Telegram chat
bot.sendMessage(chatId, resp);
});
// Listen for any kind of message in Telegram. There are different kinds of messages.
// Check out node-telegram-bot-api's GitHub & the Telegram API docs for more info
// https://github.com/yagop/node-telegram-bot-api & https://core.telegram.org/api
bot.on('message', (msg) => {
const chatId = msg.chat.id;
console.log("we got a message from telegram");
bot2.channels.get(channelid).send("[Telegram] **" + msg.from.first_name + " (#" + msg.from.username + "):** " + msg.text);
console.log("sent that message to discord");
});
bot2.login(token2);
Source: https://gist.github.com/Ahe4d/866ef3b42cb5ca6ca7c84ff7da70828c
Any idea how to fix this or what is wrong? I never worked with discord.js before
Regards..
I'm guessing that you have a v8/9 gateway based discord bot....
https://discord.com/developers/docs/topics/gateway#privileged-intents
Gateway Intents
Intents are optionally supported on the v6 gateway but required as of v8
This is another great place to read:
https://discordjs.guide/additional-info/changes-in-v13.html#before-you-start
So you need to declare them as part of the client call, for example:
// Require the necessary discord.js classes
const { Client, Intents } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [Intents.FLAGS.GUILDS] });
// When the client is ready, run this code (only once)
client.once('ready', () => {
console.log('Ready!');
});
// Login to Discord with your client's token
client.login(token);

Running NodeJS App with Socket IO on Shared CPanel server Unexpected token

I created a very simple socket IO app which receives a message and posts it back in a socket group.
The app is running successfully on my Windows machine with Node.js v12.14.0. But I want to get rid of my port forwarding so asked my hoster if it was possible to run the Node.js app on Cpanel. They were not a fan, but opened it up.
I had to install the dependencies manually but finally got no more dependency error while starting the app, but ended up with the error below. After doing some google-ing it probably has to do with the Node.js version on the server which is v6.16.0 . The hoster says they can't get this updated as it comes with cpanel. Now I was hoping there is a way to get my app.js running on this version.
Error:
enter code here[username#server app]$ node /home/username/domains/website.nl/app/app.js
/home/username/domains/website.nl/app/node_modules/ws/lib/websocket.js:347
...options
^^^
SyntaxError: Unexpected token ...
at createScript (vm.js:56:10)
at Object.runInThisContext (vm.js:97:10)
at Module._compile (module.js:549:28)
at Object.Module._extensions..js (module.js:586:10)
at Module.load (module.js:494:32)
at tryModuleLoad (module.js:453:12)
at Function.Module._load (module.js:445:3)
at Module.require (module.js:504:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/username/domains/website.nl/app/node_modules/ws/index.js:3:19)
[username#server app]$ node -v
v6.16.0
The app:
var fs = require('fs');
var https = require('https');
var prvKey = fs.readFileSync('/home/username/ssl/keys/1.key').toString();
var prvCert = fs.readFileSync('/home/username/ssl/certs/1.crt').toString();
var server = https.createServer({key:prvKey,cert:prvCert});
var serverPort = 3000;
// var server = https.createServer();
var io = require('socket.io')(server);
server.listen(serverPort, function() {
console.log('server up and running at %s port', serverPort);
});
io.on("connection", function(socket) {
console.log("user connected: " + socket.id + " - " + socket.request.connection.remoteAddress);
var activequizid = null;
socket.on('jsondata', function(data){
if(data.join.join == "true"){
console.log(socket.id + " join group " + data.join.quizid)
socket.join(data.join.quizid)
}
})
socket.on('jsondataupdate', function(data){
console.log(data.update)
if(data.update.status){
socket.to(data.update.quizid).emit('update', data.update);
}
})
socket.on("disconnect", function(socketd) {
console.log(socketd)
console.log(this.id)
});
socket.on('connection', function () {
console.log('connection!')
})
socket.on('reconnecting', function () {
console.log('reconnecting!')
})
socket.on('reconnect', function () {
console.log('reconnect!')
})
socket.on('disconnect', function () {
console.log('disconnect!')
})
});
console.log("sever online")
websocket.js (partly function with error (look for "...options")) :
send(data, options, cb) {
if (this.readyState === WebSocket.CONNECTING) {
throw new Error('WebSocket is not open: readyState 0 (CONNECTING)');
}
if (typeof options === 'function') {
cb = options;
options = {};
}
if (typeof data === 'number') data = data.toString();
if (this.readyState !== WebSocket.OPEN) {
sendAfterClose(this, data, cb);
return;
}
const opts = {
binary: typeof data !== 'string',
mask: !this._isServer,
compress: true,
fin: true,
...options
};
if (!this._extensions[PerMessageDeflate.extensionName]) {
opts.compress = false;
}
this._sender.send(data || EMPTY_BUFFER, opts, cb);
}

I was writing Discord bot with index.js and .env and I messed with this error while running this in terminal "node index.js"

I want develop my own discord bot here's the contents:
Index code
const { Client } = require("discord.js");
const { config } = require("dotenv");
// Declares our bot,
// the disableEveryone prevents the client to ping #everyone
const client = new Client({
disableEveryone: true
});
config({
path: __dirname + "/.env"
})
// When the bot's online, what's in these brackets will be executed
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
// Set the user presence
client.user.setPresence({
status: "online",
game: {
name: "me getting developed",
type: "WATCHING"
}
});
})
// When a message comes in, what's in these brackets will be executed
client.on("message", async message => {
console.log(`${message.author.username} said: ${message.content}`);
});
// Login the bot
client.login(process.env.TOKEN);
Output
disableEveryone = true
^^^^^^^^^^^^^^^^^^^^^^
SyntaxError: Invalid shorthand property initializer
at Module._compile (internal/modules/cjs/loader.js:891:18)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:991:10)
at Module.load (internal/modules/cjs/loader.js:811:32)
at Function.Module._load (internal/modules/cjs/loader.js:723:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1043:10)
at internal/main/run_main_module.js:17:11
Invalid shorthand property initializer indicates that you used an invalid property initializer. In this case, it looks like you used "=" instead of ":" to declare the property value "true" on property "disableEveryone".
Saving the code as shared and running it again should solve your problem.

Resources