So basically in short im making a bot on discord and there are a few words that I need to censor. No problem, except now users can simply use characters from keyboards that are not english, and bypass the censors. Is there a simple way I can take any string and convert its contents to english keyboard characters? Thanks in advance!
It seems like DiscordJS is running on NodeJS - so here's what we can do.
Here is the example code posted on the website, but we can use it for your project.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
if (msg.content === 'swearword') {
msg.reply('naughty!');
}
});
client.login('token');
With this code in place, you can use an API like Google Translate API to take every word that is processed and pass it to it, and await a response.
Here is the sample provided by Google:
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// Imports the Google Cloud client library
const {Translate} = require('#google-cloud/translate').v2;
// Instantiates a client
const translate = new Translate({projectId});
async function quickStart() {
// The text to translate
const text = 'Hello, world!';
// The target language
const target = 'ru';
// Translates some text into Russian
const [translation] = await translate.translate(text, target);
console.log(`Text: ${text}`);
console.log(`Translation: ${translation}`);
}
quickStart();
If you combine the translation process along with msg.content you should get a swearword in another language.
Here's an example (I havent tested this but play around with it):
You will need Google API account / key etc. So please read their instructions on how to set it up.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
/**
* TODO(developer): Uncomment the following line before running the sample.
*/
// const projectId = 'YOUR_PROJECT_ID';
// Imports the Google Cloud client library
const {Translate} = require('#google-cloud/translate').v2;
// Instantiates a client
const translate = new Translate({projectId});
var translation = "";
client.on('message', msg => {
// Translate msg.content
// The target language (i think english is en, you need to check)
const target = 'en';
// Translates some text into English (i think)
translation = await translate.translate(msg.content, target);
if (translation === 'swearword') {
msg.reply('naughty!');
}
});
client.login('token');
Related
I'm starting with discord.js and I have a question. Is it possible to make an infinite argument currently I have to use message.channel.send(${args}) and for example when I type $test 1 2 only 1 will be sent and 2 will not please help I wanted to make a reason for the command $kick but only one argument the first is often seen only the first sentence instead of the whole reason please help!
I don't think you know what I mean, I mean that the argument should not be a single word, for example command:$embed hello word :) I want the bot to send: hello word :) but it sends: hello without word and :) it doesn't have to be hello word :) it has to be the words given by the user I hope I wrote it clearly for any help thank you!
const Discord = require('discord.js');
const client = new Discord.Client();
const config = require('./config.json');
const fs = require('fs');
const prefix = "$";
const RED = "#EC0F0F";
const BLUE = "#1725E7";
const GREEN = "#17E729";
const FIOLET = "#880FEC";
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', async message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
console.log(message.content);
if (message.content === `$embed`) {
const embesmess = new Discord.MessageEmbed()
.setTitle(`${args[0]}`)
.setColor(`${GREEN}`)
.setdescription(`HERE I WANT THIS ARGUMENT`)
message.channel.send(embesmess);
}
});
client.login(config.token);
Use something like
if (message.content.startsWith(`$embed`)) {
const embesmess = new Discord.MessageEmbed()
.setTitle(`${args.slice(1).join(" ")}`) //join all arguments besides the first
.setColor(`${GREEN}`)
.setdescription(`HERE I WANT THIS ARGUMENT`)
message.channel.send(embesmess);
}
This will combine all of your arguments excluding the first.
I'm working on my discord bot and I want it to save messages that i sent it to save, how do I do this since the rest of the internet doesn't ask this question for some reason. i've been looking for someone to point me in a direction but haven't found anything
This is a really simplified version of what you want to do but I'm sure if you read it you'll understand and it will get the job done.
const discord = require('discord.js'); // Import discord.js
const client = new discord.Client(); // Initialize new discord.js client
const messages = [];
client.on('message', (msg) => {
if (!msg.content.startsWith('+')) return; // If the message doesn't start with the prefix return
const args = msg.content.slice(1).split(' '); // Split all spaces so you can get the command out of the message
const cmd = args.shift().toLowerCase(); // Get the commands name
switch (cmd) {
case 'add':
messages.push(args.join(' ')); // Add the message's content to the messages array
break;
case 'get':
msg.channel.send(messages.map((message) => `${message}\n`)); /* Get all the stored messages and map them + send them */
break;
}
});
client.login(/* Your token */); // Login discord.js
I am struggling to run an async function taken from a Google example alongside the Environment Variables on Windows 10. I have created a bucket at GCS and uploaded my .raw file.
I then created a .env file which contains the following
HOST=localhost
PORT=3000
GOOGLE_APPLICATION_CREDENTIALS=GDeveloperKey.json
Doing this in AWS Lambda is just a case of wrapping the code within exports.handler = async (event, context, callback) => {
How can I emulate the same locally in Windows 10?
// Imports the Google Cloud client library
const speech = require('#google-cloud/speech');
// Creates a client
const client = new speech.SpeechClient();
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// const gcsUri = 'gs://my-bucket/audio.raw';
// const encoding = 'Encoding of the audio file, e.g. LINEAR16';
// const sampleRateHertz = 16000;
// const languageCode = 'BCP-47 language code, e.g. en-US';
const config = {
encoding: encoding,
sampleRateHertz: sampleRateHertz,
languageCode: languageCode,
};
const audio = {
uri: gcsUri,
};
const request = {
config: config,
audio: audio,
};
// Detects speech in the audio file. This creates a recognition job that you
// can wait for now, or get its result later.
const [operation] = await client.longRunningRecognize(request);
// Get a Promise representation of the final result of the job
const [response] = await operation.promise();
const transcription = response.results
.map(result => result.alternatives[0].transcript)
Wrap your await statements into an immediately-invoked async function.
Ex:
(async () => {
// Detects speech in the audio file. This creates a recognition job that you
// can wait for now, or get its result later.
const [operation] = await client.longRunningRecognize(request);
// Get a Promise representation of the final result of the job
const [response] = await operation.promise();
const transcription = response.results
.map(result => result.alternatives[0].transcript)
})();
So my code is as below
`message.channel.send(
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'your bot token here';
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
// If message content = .ping
if (message.content === '.ping') {
message.channel.send(`Pong! Latency is ${m.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
}
});
client.login(token);
);`
And I would like to put that into a string, However when attempting to im meant with a million syntax errors and so I googled escape character. I found the Javascript ones however when trying them the
message.channel.send(`Pong! Latency is ${m.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
}
ends up stopping the code with an unexpected identifier, When doing this without the above code it works.
If someone could hlep with formmating it, that would be great
P.S Im using Discord.js an addon for Node.js
Since you're not providing us with the error you're getting there could be a few things going on, but I've got a vague Idea of what you're mistake is. You're trying to calculate the difference of time between a received message and a not yet created message.
What you want to do is reply to the message simply with some dummy text, say ping, then update that message and calculate the difference between the received message and your reply. Something like this:
const Discord = require('discord.js');
const client = new Discord.Client();
const token = 'your bot token here';
client.on('ready', () => {
console.log('I am ready!');
});
client.on('message', message => {
// If message content = ping
if (message.content === 'ping') {
message.channel.send('Pong!')
.then(pongMessage => {
pongMessage.edit(`Pong! Latency is ${pongMessage.createdTimestamp - message.createdTimestamp}ms. API Latency is ${Math.round(client.ping)}ms`);
});
}
});
client.login(token);
Your comment about this script, that it's not supposed to be run confused me a little bit, but if this is supposed to be one huge template literal you're sending and the ${} is mistakenly interpreted as code, simply escape it with \
console.log(`${ 1 + 1 } | \${ 1 + 1}`) // 2 | ${ 1 + 1 }
I've been working on a discord bot lately, this is my first time coding in general, and I thought Javascript would be easier than other options I might have had. Right now, I'm struggling through reading error after error.
Anyways, lets get to the question at hand. Currently, the code is as follows:
const Discord = require("discord.js");
const client = new Discord.Client();
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix="^";
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
let short = msg.content.toLowerCase()
let GeneralChannel = server.channels.find("General", "Bot")
if (msg.content.startsWith( prefix + "suggest")) {
var args = msg.content.substring(8)
msg.guild.channels.get(GeneralChannel).send("http\n SUGGESTION:" + msg.author.username + " suggested the following: " + args + "")
msg.delete();
msg.channel.send("Thank you for your submission!")
}
});
When I ran said code, it returned an error that (I think) basically told me that "server" in let GeneralChannel = server.channels.find("General", "Bot") was undefined. My problem is, I dont actually know how to define server. I'm assuming that when I define server to it, it will also tell me I need to define channel and find, though I'm not sure.
Thanks in advance :)
First of all, why are you using both let and var? Anyways, as the error says, server is not defined. The client doesn't know what server you're referring to. That's where your msg object comes in, it has a property guild which is the server.
msg.guild;
Secondly, what are you trying to achieve with let GeneralChannel = server.channels.find("General", "Bot")? the find method for arrays takes a function. Are you trying to look for the channel with the name "General" or something? If so, better to use the id of the channel that way, you can use a channel from any server the bot is in (in case you're trying to send all suggestions to a specific channel on a different server).
let generalChannel = client.channels.find(chan => {
return chan.id === "channel_id"
})
//generalChannel will be undefined if there is no channel with the id
If you're trying to send
Going by that assumption, your code can then be re-written to:
const Discord = require("discord.js");
const client = new Discord.Client();
const commando = require('discord.js-commando');
const bot = new commando.Client();
const prefix="^";
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', msg => {
let short = msg.content.toLowerCase();
if (msg.content.startsWith( prefix + "suggest")) {
let generalChannel = client.channels.find(chan => {
return chan.id === 'channel_id';
});
let args = msg.content.substring(8);
generalChannel.send("http\n SUGGESTION: " + msg.author.username + " suggested the following: " + args + "");
msg.delete();
msg.channel.send("Thank you for your submission!")
}
});
Not that scope is a concern in this instance but it's worth noting that 'let 'defines a local variable while 'var' defines a global variable. There is a difference.