Loading...
More JavaScript Posts
const Discord = require('discord.js');const client = new Discord.Client();const token = 'YOUR_BOT_TOKEN';// When the bot is ready, log a message to the consoleclient.on('ready', () => {console.log(`Logged in as ${client.user.tag}!`);});// When a user sends a message, check if they are authenticatedclient.on('message', async (msg) => {if (!msg.author.bot && !msg.author.authenticated) {const filter = (m) => m.author.id === msg.author.id;const collector = msg.channel.createMessageCollector(filter, { time: 15000 });// Send an authentication message to the usermsg.author.send('Please authenticate yourself by clicking this link: ' + generateAuthURL(msg.author.id));collector.on('collect', async (m) => {// Check if the message contains the authentication codeif (m.content.startsWith('!auth ')) {const code = m.content.slice(6);const { access_token } = await getAccessToken(code);// Set the user's authenticated status and access tokenmsg.author.authenticated = true;msg.author.access_token = access_token;collector.stop();}});collector.on('end', () => {if (!msg.author.authenticated) {msg.author.send('Authentication timed out.');}});}});// Generate an authentication URL for the userfunction generateAuthURL(userId) {const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');const scopes = 'identify';const clientID = 'YOUR_CLIENT_ID';return `https://discord.com/api/oauth2/authorize?client_id=${clientID}&redirect_uri=${redirectURI}&response_type=code&scope=${scopes}&state=${userId}`;}// Exchange the authorization code for an access tokenasync function getAccessToken(code) {const redirectURI = encodeURIComponent('YOUR_REDIRECT_URL');const clientID = 'YOUR_CLIENT_ID';const clientSecret = 'YOUR_CLIENT_SECRET';const res = await fetch('https://discord.com/api/oauth2/token', {method: 'POST',headers: {'Content-Type': 'application/x-www-form-urlencoded',},body: `grant_type=authorization_code&code=${code}&redirect_uri=${redirectURI}&client_id=${clientID}&client_secret=${clientSecret}`,});return await res.json();}client.login(token);
// promisify(f, true) to get array of resultsfunction promisify(f, manyArgs = false) {return function (...args) {return new Promise((resolve, reject) => {function callback(err, ...results) { // our custom callback for fif (err) {reject(err);} else {// resolve with all callback results if manyArgs is specifiedresolve(manyArgs ? results : results[0]);}}args.push(callback);f.call(this, ...args);});};}// usage:f = promisify(f, true);f(...).then(arrayOfResults => ..., err => ...);
const MongoClient = require('mongodb').MongoClient;const assert = require('assert');// Connection URLconst url = 'mongodb://localhost:27017';// Database Nameconst dbName = 'myproject';// Use connect method to connect to the serverMongoClient.connect(url, function(err, client) {assert.equal(null, err);console.log("Connected successfully to server");const db = client.db(dbName);client.close();});
let variableSet = JSON.parse('["parent","opener","top","length","frames","closed","location","self","window","document","name","customElements","history","locationbar","menubar","personalbar","scrollbars","statusbar","toolbar","status","frameElement","navigator","origin","external","screen","innerWidth","innerHeight","scrollX","pageXOffset","scrollY","pageYOffset","visualViewport","screenX","screenY","outerWidth","outerHeight","devicePixelRatio","clientInformation","screenLeft","screenTop","defaultStatus","defaultstatus","styleMedia","onsearch",&qu...find","webkitRequestAnimationFrame","webkitCancelAnimationFrame","fetch","btoa","atob","setTimeout","clearTimeout","setInterval","clearInterval","createImageBitmap","close","focus","blur","postMessage","onappinstalled","onbeforeinstallprompt","crypto","indexedDB","webkitStorageInfo","sessionStorage","localStorage","chrome","onpointerrawupdate","speechSynthesis","webkitRequestFileSystem","webkitResolveLocalFileSystemURL","openDatabase","variableSet","TEMPORARY","PERSISTENT","addEventListener","removeEventListener","dispatchEvent"]');let answer = [];for(let v in this) if(!variableSet.includes(v)) answer.push(v);console.log(answer);
function formatDate(date) {return date.toLocaleDateString();}function Comment(props) {return (<div className="Comment"><div className="UserInfo"><imgclassName="Avatar"src={props.author.avatarUrl}alt={props.author.name}/><div className="UserInfo-name">{props.author.name}</div></div><div className="Comment-text">{props.text}</div><div className="Comment-date">{formatDate(props.date)}</div></div>);}const comment = {date: new Date(),text: 'I hope you enjoy learning React!',author: {name: 'Hello Kitty',avatarUrl: 'https://placekitten.com/g/64/64',},};ReactDOM.render(<Commentdate={comment.date}text={comment.text}author={comment.author}/>,document.getElementById('root'));
const longestPalindrome = (s) => {if(s.length === 1) return sconst odd = longestOddPalindrome(s)const even = longestEvenPalindrome(s)if(odd.length >= even.length) return oddif(even.length > odd.length) return even};const longestOddPalindrome = (s) => {let longest = 0let longestSubStr = ""for(let i = 1; i < s.length; i++) {let currentLongest = 1let currentLongestSubStr = ""let left = i - 1let right = i + 1while(left >= 0 && right < s.length) {const leftLetter = s[left]const rightLetter = s[right]left--right++if(leftLetter === rightLetter) {currentLongest += 2currentLongestSubStr = s.slice(left+1, right)} else break}if(currentLongest > longest) {if(currentLongestSubStr) longestSubStr = currentLongestSubStrelse longestSubStr = s[i]longest = currentLongest}}return longestSubStr}const longestEvenPalindrome = (s) => {let longest = 0let longestSubStr = ""for(let i = 0; i < s.length - 1; i++) {if(s[i] !== s[i+1]) continue;let currentLongest = 2let currentLongestSubStr = ""let left = i - 1let right = i + 2while(left >= 0 && right < s.length) {const leftLetter = s[left]const rightLetter = s[right]left--right++if(leftLetter === rightLetter) {currentLongest += 2currentLongestSubStr = s.slice(left+1, right)} else break}if(currentLongest > longest) {if(currentLongestSubStr) longestSubStr = currentLongestSubStrelse longestSubStr = s[i] + s[i+1]longest = currentLongest}}return longestSubStr}console.log(longestPalindrome("babad"))