Browse Author

wesley

How to Stop MacBook from Sleeping

I have a spare MacBook Pro that I’m using to run a 24/7 Plex media server for streaming movies and shows to my TV. I thought hey, I can run a Discord bot on this machine as well! So I simply ran npm start in a terminal window and expected my Node.js Discord bot to be up and running as long as my computer was on.

One problem ocurred: each time macOS went to sleep, my node script would stop running as well. When I moved the mouse to wake up it, the bot would go back online, and then go back to sleep soon after. Even enabling the Amphetamine app wasn’t keeping my bot online.

So I did some googling, and found a new command that I had not known about: caffeinate

We simply need to give our npm command some caffeine so it doesn’t go to sleep:

caffeinate -s npm start

And voilà! My Discord bot has been online ever since I’ve ran the command.

If your node script is already running and you don’t want to restart it with the caffeinate command, you can find the process ID of it by using: ps | grep node and keep it awake like this:

caffeinate -w <PID>

How to make a no-op commit

Sometimes I want to push a no-op (no-operation / empty) commit to GitHub to trigger an automatic deploy. The command to make the commit is:

git commit --allow-empty -m "noop"

Sending Discord Messages in Node.js with Fetch

This post is an update to Simple Discord Messages in Python, but this time in JavaScript! We’re going to use some simple code for sending a Discord message without the need of any Discord API library.

Here’s the basic code:

const BOT_TOKEN = 'xxxxx';
const CHANNEL_ID = '#####';
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

async function sendMessage(content) {
    const response = await fetch(
        `https://discord.com/api/v9/channels/${CHANNEL_ID}/messages`, {
            method: 'post',
            body: JSON.stringify({content}),
            headers: {
                'Authorization': `Bot ${BOT_TOKEN}`,
                'Content-Type': 'application/json',
            }
        }
    );
    const data = await response.json();
    return data;
}

To run the function, simply add this line:

sendMessage('hello world!');

To send a message along with an attached image from an external URL, we’ll have to modify the code and use FormData, like this:

const BOT_TOKEN = 'xxxxx';
const CHANNEL_ID = '#####';
const FormData = require('form-data');
const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

async function sendMessageAndImage(content, imageUrl) {
    const imageRes = await fetch(imageUrl).then(res => res.body);
    let formdata = new FormData();
    formdata.append("files[0]", imageRes, 'chart.png');
    formdata.append("payload_json", JSON.stringify({
        content
    }));
    const response = await fetch(
        `https://discord.com/api/v9/channels/${CHANNEL_ID}/messages`, {
            method: 'post',
            body: formdata,
            headers: {
                'Authorization': `Bot ${BOT_TOKEN}`,
            }
        }
    );
    const data = await response.json();
    return data;
}

And here is how to invoke the function:

sendMessageAndImage('foobar', 'https://avatars.githubusercontent.com/u/9919');

Stop “npm install” in Heroku

I have a node.js project that I want to run on Heroku, but with my own modified node plugins in the node_modules folder. When deploying the project to Heroku, it keeps installing brand new node dependencies, which overwrites my modified ones.

According to this Stack Overflow answer, “npm install” always runs and cannot be blocked or skipped. However, there is one workaround, which is to create a .npmrc file in the project root with the following contents: dry-run

The dry-run setting tells npm that we do not want to make any changes to the node_modules folder, thus keeping our node plugins unaffected!

Simple Discord Messages in Python

This is a quick and easy way to send a bot message on Discord using Python, without the discord.py library, by simply doing a POST request with the requests library.

First you’ll need your bot’s token, which you can find from: https://discord.com/developers/applications

Next you’ll need the ID of the text channel where you want to send the messages to be sent. Simply right click the channel name and click “Copy ID”.

With those 2 values copied, paste them into the respective variables in the code below.

import requests

BOT_TOKEN = 'xxxxx'
CHANNEL_ID = '#####'

message = 'hello world!'

requests.post(
    url='https://discord.com/api/v8/channels/{}/messages'.format(CHANNEL_ID),
    json={'content': message},
    headers={
        'authorization': 'Bot {}'.format(BOT_TOKEN),
        'content-type': 'application/json',
    }
)

And that’s it! Execute the python script and check the Discord channel for the message!

Deploying a discord.js bot using Heroku and GitHub for free

This post will teach you how to create your own Discord bot using the Node.js discord.js library and how to deploy it using GitHub + Heroku for free if you are a new user. GitHub is great because it lets us store our code in the cloud so that we can access it anywhere and on any device. Hooking it up with Heroku’s automatic deploy is amazing because we don’t need to manually run any commands to build or start the bot. Once new changes are pushed to the GitHub repo, the bot will automatically be updated within minutes. It’s like magic.

1. Discord Application

Visit discord.com/developers/applications, click on New Application, and enter an app name.

After making the app, we’ll need to create the bot that lives within the app. Click on Bot in the menu, and then Add Bot. Update the bot name if necessary and then click on the Copy button below to save the bot’s token in a safe place for now.

Now we can add the newly created bot into our Discord server. Click on Oauth2 in the menu, select the bot OAuth2 scope, and copy the URL.

Paste this URL into your browser’s address bar, and then select your server where you want your bot to join, and click Authorize.

Now the bot has joined your server, but it will be offline until we finish coding and deploying it.

Note: Your bot can be added to other servers if people have your OAuth2 link. You can disable this by flipping the “Public Bot” toggle.

2. Discord.js

Create a new folder somewhere to store your code for your new bot. Inside the folder, initialize it as a new npm project and install discord.js with:

npm init
npm install discord.js

Open up the package.json file and you should see an existing "scripts" object — add a new "start" key inside that object with the value "node index.js". It should look something like this:

"scripts": {
  "start": "node index.js",
  "test": "echo \"Error: no test specified\" && exit 1"
},

This will allow us (and Heroku) to start the bot by running the command: npm start

Create a new index.js file and paste in some sample bot code:

const Discord = require('discord.js');
const client = new Discord.Client();

// log when the bot is ready
client.on('ready', () => {
  console.log(`Logged in as ${client.user.tag}!`);
});

// listen to messages and reply
client.on('message', msg => {
  if (msg.content === 'hello') {
    msg.reply('hey there!');
  }
});

client.login('token');

On the very last line of code, replace the ‘token’ word with the bot’s real token which you should have saved in a safe place earlier.

Now in your terminal, you can run npm start. The bot should log in, and you should see it online in your Discord server.

Type “hello”, and your bot should reply back to you immediately with “hey there!”

Excellent, the bot is working locally! Press Ctrl+C in your terminal to quit the bot application and it should go offline from your server in a minute or two.

3. GitHub

I recommend creating a GitHub repo to store your bot code. We will also set up automatic deploys to Heroku each time new code is pushed into the main branch.

In GitHub, create a new private repository (because the code has your private bot token).

Go back in your terminal and let’s run a few commands to:

  1. Initialize the folder we’ve been working in into a git repo.
  2. Add a .gitignore file that ignores the node_modules folder from git because we don’t need to track/push that into GitHub.
  3. Convert the branch from “master” to “main” to promote more inclusive language.
  4. Link to your GitHub repo (change doobix/seewes-bot to your-username/your-repo).
git init
echo "node_modules" >> .gitignore
git branch -M main
git remote add origin git@github.com:doobix/seewes-bot.git

Now we can commit the files into GitHub:

git add .
git commit -m 'initial commit'
git push origin main

4. Heroku

Heroku has a “Free and Hobby” tier for users to run apps for $0. By default, new accounts get 550 free dyno hours to use per month. If you simply add a credit card to your account, you will receive an additional 450 hours, for a total of 1,000 hours for free. In months with 31 days, you can run your Discord bot for 24 hours straight, and it’ll only use up 744 dyno hours, with 256 hours left to spare! So make sure to add a credit card and your bot will not run into any time usage limits.

Ok now let’s create our first Heroku app. After signing in, click New > Create new app. Enter your app name and then click Create app.

Go to the Deploy section and connect it to the new GitHub repo that we created earlier by clicking on the GitHub icon. Follow the steps to connect your Heroku account to your GitHub account. Once Heroku has access to see your repos, it should let you search and connect to your bot repo.

Below in the Automatic deploys section, click on the Enable Automatic Deploys button. This will enable Heroku to deploy your new bot code every time you push a change to the main branch on GitHub.

Now one last thing is that this new Heroku app defaults to being a web app. This means that it only turns on and uses dyno hours when users visit the web url, and it turns off in 30 minutes if it has no web traffic. Since we are not running a website, we need to convert this Heroku app to a worker app with a Procfile.

Run the following commands in the your terminal to add a new Procfile and push the change to GitHub:

echo "worker: npm start" >> Procfile
git add .
git commit -m 'add procfile'
git push origin main

After that’s done, visit the Resources section in Heroku. Disable the web dyno type, and Enable the worker dyno type.

And that’s all there is to it. Your bot should be up and running, and it should reply to you when you type “hello” in your Discord server!

5. Finish

Now you can continue to extend your bot with more features. Have it reply to other commands. Make it give reactions when it detects certain phrases. Etc. Check out the discord.js docs to see more examples and what API’s are available for you to use. The possibilities are endless!

Thanks for reading and hoped this has helped you.

Here’s my example bot repo if you’re interested: https://github.com/doobix/seewes-bot

Special thanks Linda H’s post which helped get me started: Create & host a Discord bot with Heroku in 5 min

Install a specific yarn version

Need to install a specific version of Yarn? Simply run the command below in your terminal. Replace 1.19.1 with the yarn version you want to install.

curl -o- -L https://yarnpkg.com/install.sh | bash -s -- --version 1.19.1

Unit Testing Private Member Variables in TypeScript with React/Enzyme

So let’s say I have a React component written in TypeScript with a private member variable that I would like to unit test. The component is very complicated and I need to make sure the private variable has the correct value, and it looks something like this:

export class HelloWorld extends React.Component<Props, State> {
  private message = "foobar";
  public render() {
    return <div>Hello World</div>;
  }
}

If I mount the component with Enzyme, I can find the component, but I cannot see the private variables inside it. One thing I can do is to create an interface of that component just for testing purposes. In the interface, I can reveal the private variables, like this:

interface HelloWorldInstance extends React.Component<Props, State> {
  message: string;
}

With this interface created, I can mount the component, get the instance of it, and do a type assertion. Now I can test that private variable without TypeScript complaining:

describe("HelloWorld", () => {
  it("has correct message", () => {
    const wrapper = mount(<HelloWorld />);
    const helloWorld = wrapper.find(HelloWorld);
    const helloWorldInstance = helloWorld.instance() as HelloWorldInstance;
    expect(helloWorldInstance.message).toBe("foobar");
  });
});

Deploying Next.js with Express on Elastic Beanstalk

I recently made a very simple website with Next.js that would display the 5 newest YouTube videos from a particular channel using the YouTube Data API. I quickly learned three things after deploying the code to Netlify and Now:

  1. Deploying to Netlify and Now only created a static version of the website.
  2. The private API key was visible in the HTML code.
  3. The 5 newest YouTube videos were going to stay the same until the next deploy.

At this point, I decided to look online to see how to run an Express server with Next.js so I can keep the private API key hidden in the backend and so I can always display the 5 latest videos without needing to redeploy my code. Here are the steps I took starting from the beginning.

Install Dependencies

Run these 2 lines to initialize the project and install Next.js, React, and Express:

npm init
npm install --save next react react-dom express

Now edit the package.json file to make the scripts section look like this:

"scripts": {
  "dev": "node server.js",
  "build": "next build",
  "start": "next start",
  "deploy": "NODE_ENV=production next build && NODE_ENV=production node ./server.js"
},

Tip: Use “nodemon server.js” when you are devving so every time you make a change to the server.js file, it will automatically restart your server. Run npm install -g nodemon to install the utility.

Create a Next.js Page

Create a folder called “pages” in the root directory with a file named index.js inside the folder. Add the following code into pages/index.js:

function Home() {
  return (<div>Hello next.js on express!</div>);
}
export default Home;

This small block of code simply displays a short message when someone visits the website.

Create Express Server

In the root directory, create a server.js file and copy/paste the following code. Credit to tilomitra’s blog post: Building Server-rendered React Apps with NextJS.

const express = require('express');
const next = require('next');
const dev = process.env.NODE_ENV !== 'production';
const port = process.env.PORT || 3000;
const app = next({ dev });
const handle = app.getRequestHandler();
app.prepare()
.then(() => {
  const server = express();
  server.get('/test', (req, res) => {
    res.send('Hello from express!', 200);
  });
  server.get('*', (req, res) => {
    return handle(req, res);
  });
    
  server.listen(port, (err) => {
    if (err) throw err;
    console.log(`> Ready on http://localhost:${port}`);
  });
})
.catch((ex) => {
  console.error(ex.stack);
  process.exit(1);
});

The ~30 lines of code here basically creates an express server where you can have custom endpoints for you to do API data fetching. For example, you can create a /api/videos endpoint for fetching and returning JSON data by adding this block:

server.get('/api/videos', async (req, res) => {
  const apiResponse = await fetch('https://example.com/api');
  const apiData = await apiResponse.json();
  res.json({
    totalVideos: apiData.totalResults,
    videos: apiData.items,
  });
});

In the /pages/index.js file, you can do a fetch on the /api/videos endpoint and render the data however you’d like.

Deploy to Elastic Beanstalk

Now that the code is done, I decided to deploy to AWS Elastic Beanstalk because I have used AWS for other projects before. It was fairly easy but I will outline the steps.

First, go to the Elastic Beanstalk page and click on “Create New Application” at the top right corner. Fill out the application name and a description.

You should now be on the newly created application page and it’ll tell you to create a new environment.

Click on “Create one now” and select “Web server environment“.

On the next page, you can name the environment anything you’d like, pick a nice domain, select Node.js as the preconfigured platform, and then upload a zip file of the directory with all of the code created from the beginning of this blog post.

Click on “Create environment” to start the process!

After a few minutes, you should see your completed environment.

Almost done. Click on Configuration on the left side and then click Modify in the Software box.

In the Node command input box, enter: npm run deploy. This makes the environment run the deploy script as defined in the scripts section in the package.json file.

Make sure to hit the Apply button, and that’s all there is to it! The code should be deployed and reachable through the elastic beanstalk domain (i.e. <domain>.us-east-1.elasticbeanstalk.com).

Too lazy to create the files and copy/pasting the code? Download the files from the repo I made here: https://github.com/doobix/nextjs-express-demo

Hope this was helpful, let me know your thoughts in the comments section!

Updated to use HTTPS!

I’ve just enabled HTTPS on seewes.com, which was fairly easy to do on Dreamhost! Here is the breakdown done in 3 steps.

1. Enable Let’s Encrypt

In the Dreamhost admin panel, click on Domains and then SSL/TLS Certificates. Now in the list of domains, click on the Add button and select the Let’s Encrypt SSL Certificate option.

2. Update all resources to https

This is probably the longest and most tedious part of converting your website from http to https. Every image, stylesheet, and script source on the website needs to start with https. For me, I manually updated the image URLs on every single post that had an image. Luckily there weren’t that many. If you don’t update the URLs, the browser will show a mixed content warning:

3. Force your site to load securely

Now for the last step, we want people who visit the http version of the website to automatically be redirected to the https version. All we have to do is open up the .htaccess file in the root directory of the website and add these lines to the very top of the file:

RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] 

Success!