A boilerplate for Node.js Twitter Automation applications.
Hat tip to Sahat Yalkabov for his Hackathon Starter project which is an inspiration.
- Features
- Prerequisites
- Getting Started
- Obtaining API Keys
- Project Structure
- List of Packages
- Useful Tools and Resources
- Recommended Design Resources
- Recommended Node.js Libraries
- Recommended Client-side Libraries
- Pro Tips
- FAQ
- Cheatsheets
- Deployment
- Docker
- Changelog
- Contributing
- License
- API Examples: Twitter
- Node.js 6.0+
- Command Line Tools
- Β Mac OS X: Xcode (or OS X 10.9+:
xcode-select --install
) - Β Windows: Visual Studio
- Β Ubuntu / Β Linux Mint:
sudo apt-get install build-essential
- Β Fedora:
sudo dnf groupinstall "Development Tools"
- Β OpenSUSE:
sudo zypper install --type pattern devel_basis
Note: If you are new to Node or Express, I recommend to watch Node.js and Express 101 screencast by Alex Ford that teaches Node and Express from scratch. Alternatively, here is another great tutorial for complete beginners - Getting Started With Node.js, Express, MongoDB.
The easiest way to get started is to clone the repository:
# Get the latest snapshot
git clone --depth=1 https://github.com/roberjo/TwitterFavorite.git myproject
# Change directory
cd myproject
# Install NPM dependencies
npm install
# Then simply start your app
node index.js
Note: I highly recommend installing Nodemon.
It watches for any changes in your node.js app and automatically restarts the
server. Once installed, instead of node app.js
use nodemon app.js
. It will
save you a lot of time in the long run, because you won't need to manually
restart the server each time you make a small change in code. To install, run
sudo npm install -g nodemon
.
To use any of the included APIs, you will need to obtain appropriate credentials: Client ID, Client Secret, API Key, or Username & Password. You will need to go through each provider to generate new credentials.
- Sign in at https://apps.twitter.com
- Click Create a new application
- Enter your application name, website and description
- For Callback URL: http://127.0.0.1:8080/auth/twitter/callback
- Go to Settings tab
- Under Application Type select Read and Write access
- Check the box Allow this application to be used to Sign in with Twitter
- Click Update this Twitter's applications settings
- Copy and paste Consumer Key and Consumer Secret keys into
.env
file
Name | Description |
---|---|
src/ | Application source directory. |
src/bot.js | Main applicaton. |
src/config.js | Dotenv and configuration settings. |
src/helpers/isReply.js | Detects if a tweet is a reply. |
.gitignore | Git ignore rules. |
eslintrc.json | Linter rules |
.env.example | Your API keys, tokens, etc. |
index.js | The main application file. |
package.json | NPM dependencies. |
package-lock.json | Contains exact versions of NPM dependencies in package.json. |
Note: There is no preference how you name or structure your views.
You could place all your templates in a top-level views
directory without
having a nested folder structure, if that makes things easier for you.
Just don't forget to update extends ../layout
and corresponding
res.render()
paths in controllers.
Package | Description |
---|---|
dotenv | Loads environment variables from .env file. |
twit | Twitter API library. |
languagedetect | Text language classifier. |
log-timestamp | Adds timestampes to console log |
moment | Javascript datetime handler |
underscore | Functional programming helpers |
- JavaScripting - The Database of JavaScript Libraries
- JS Recipes - JavaScript tutorials for backend and frontend development.
- Jade Syntax Documentation by Example - Even better than official Jade docs.
- HTML to Jade converter - Extremely valuable when you need to quickly copy and paste HTML snippets from the web.
- JavascriptOO - A directory of JavaScript libraries with examples, CDN links, statistics, and videos.
- Favicon Generator - Generate favicons for PC, Android, iOS, Windows 8.
- Code Guide - Standards for developing flexible, durable, and sustainable HTML and CSS.
- Bootsnipp - Code snippets for Bootstrap.
- UIBox - Curated HTML, CSS, JS, UI components.
- Bootstrap Zero - Free Bootstrap templates themes.
- Google Bootstrap - Google-styled theme for Bootstrap.
- Font Awesome Icons - Reference page.
- Colors - A nicer color palette for the web.
- Creative Button Styles - awesome button styles.
- Creative Link Effects - Beautiful link effects in CSS.
- Medium Scroll Effect - Fade in/out header background image as you scroll.
- GeoPattern - SVG background pattern generator.
- Trianglify - SVG low-poly background pattern generator.
- Nodemon - Automatically restart Node.js server on code changes.
- geoip-lite - Geolocation coordinates from IP address.
- Filesize.js - Pretty file sizes, e.g.
filesize(265318); // "265.32 kB"
. - Numeral.js - Library for formatting and manipulating numbers.
- Node Inspector - Node.js debugger based on Chrome Developer Tools.
- node-taglib - Library for reading the meta-data of several popular audio formats.
- sharp - Node.js module for resizing JPEG, PNG, WebP and TIFF images.
- Framework7 - Full Featured HTML Framework For Building iOS7 Apps.
- InstantClick - Makes your pages load instantly by pre-loading them on mouse hover.
- NProgress.js - Slim progress bars like on YouTube and Medium.
- Hover - Awesome CSS3 animations on mouse hover.
- Magnific Popup - Responsive jQuery Lightbox Plugin.
- jQuery Raty - Star Rating Plugin.
- Headroom.js - Hide your header until you need it.
- X-editable - Edit form elements inline.
- Offline.js - Detect when user's internet connection goes offline.
- Alertify.js - Sweet looking alerts and browser dialogs.
- selectize.js - Styleable select elements and input tags.
- drop.js - Powerful Javascript and CSS library for creating dropdowns and other floating displays.
- scrollReveal.js - Declarative on-scroll reveal animations.
- When installing an NPM package, add a --save flag, and it will be automatically
added to
package.json
as well. For example,npm install --save moment
. - Use async.parallel() when you need to run multiple asynchronous tasks, and then take action, but only when all tasks are completed. For example, you might want to scrape 3 different websites for some data and render the results in a template after all 3 websites have been scraped.
- Need to find a specific object inside an Array? Use _.find
function from Lodash. For example, this is how you would retrieve a
Twitter token from database:
var token = _.find(req.user.tokens, { kind: 'twitter' });
, where 1st parameter is an array, and a 2nd parameter is an object to search for.
###TODO - Setup FAQ
Declares a read-only named constant.
const name = 'yourName';
Declares a block scope local variable.
let index = 0;
Using the `${}` syntax, strings can embed expressions.
const name = 'Oggy';
const age = 3;
console.log(`My cat is named ${name} and is ${age} years old.`);
To import functions, objects or primitives exported from an external module. These are the most common types of importing.
import name from 'module-name';
import * as name from 'module-name';
import { foo, bar } from 'module-name';
To export functions, objects or primitives from a given file or module.
export { myFunction };
export const name = 'yourName';
export default myFunctionOrClass
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.
myFunction(...iterableObject);
<ChildComponent {...this.props} />
A Promise is used in asynchronous computations to represent an operation that hasn't completed yet, but is expected in the future.
var p = new Promise(function(resolve, reject) { });
The catch()
method returns a Promise and deals with rejected cases only.
p.catch(function(reason) { /* handle rejection */ });
The then()
method returns a Promise. It takes 2 arguments: callback for the success & failure cases.
p.then(function(value) { /* handle fulfillment */ }, function(reason) { /* handle rejection */ });
The Promise.all(iterable)
method returns a promise that resolves when all of the promises in the iterable argument have resolved, or rejects with the reason of the first passed promise that rejects.
Promise.all([p1, p2, p3]).then(function(values) { console.log(values) });
Arrow function expression. Shorter syntax & lexically binds the this
value. Arrow functions are anonymous.
singleParam => { statements }
() => { statements }
(param1, param2) => expression
const arr = [1, 2, 3, 4, 5];
const squares = arr.map(x => x * x);
The class declaration creates a new class using prototype-based inheritance.
class Person {
constructor(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
incrementAge() {
this.age++;
}
}
π Credits: DuckDuckGo and @DrkSephy.
π back to top
Math.floor(Date.now() / 1000);
var now = new Date();
now.setMinutes(now.getMinutes() + 30);
// DD-MM-YYYY
var now = new Date();
var DD = now.getDate();
var MM = now.getMonth() + 1;
var YYYY = now.getFullYear();
if (DD < 10) {
DD = '0' + DD;
}
if (MM < 10) {
MM = '0' + MM;
}
console.log(MM + '-' + DD + '-' + YYYY); // 03-30-2016
// hh:mm (12 hour time with am/pm)
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var amPm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
minutes = minutes < 10 ? '0' + minutes : minutes;
console.log(hours + ':' + minutes + ' ' + amPm); // 1:43 am
var today = new Date();
var nextWeek = new Date(today.getTime() + 7 * 24 * 60 * 60 * 1000);
var today = new Date();
var yesterday = date.setDate(date.getDate() - 1);
π back to top
You will need docker and docker-compose installed to build the application.
After installing docker, start the application with the following commands :
# To build the project for the first time or when you add dependencies
docker-compose build web
# To start the application (or to restart after making changes to the source code)
docker-compose up web
To view the app, find your docker ip address + port 8080 ( this will typically be http://localhost:8080/ ). To use a port other than 8080, you would need to modify the port in app.js, Dockerfile and docker-compose.yml.
Once you are ready to deploy your app, you will need to create an account with a cloud platform to host it. This is not the only choice, but they are my top pick. From my experience, Heroku is the easiest to get started with, it will automatically restart your Node.js process when it crashes, zero-downtime deployments and custom domain support on free accounts.
- Download and install Heroku Toolbelt
- In terminal, run
heroku login
and enter your Heroku credentials - From your app directory run
heroku create
- Run
heroku addons:create mongolab
. This will set up the mLab add-on and configure theMONGODB_URI
environment variable in your Heroku app for you. - Lastly, do
git push heroku master
. Done!
Note: To install Heroku add-ons your account must be verified.
- Initial Setup
If something is unclear, confusing, or needs to be refactored, please let me know. Pull requests are always welcome, but due to the opinionated nature of this project, I cannot accept every pull request. Please open an issue before submitting a pull request. This project uses Google JavaScript Style Guide with a few minor exceptions. If you are submitting a pull request that involves Pug templates, please make sure you are using spaces, not tabs.
The MIT License (MIT)
Copyright (c) 2018 John B. Roberts
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.