How to build a responsive landing page in 10 min

Build a responsive layout using mainly CSS (Grid and Flex)

To skip the tutorial, feel free to download the source code template from my Github repo here.

There are quite a few templates and tutorials out there for building landing pages. However, most tend to overcomplicate or add heavy design (such as multiple pages, forms, etc), to what in most cases requires very simple and lean design. Moreover, I’ll be showing you how to use mainly CSS (Grid and Flex) to create a responsive UI, instead of using old school CSS libraries (such as bootstrap). So let’s get to it! 💪

We’re going to build a basic landing page layout, and focus mainly on the fundamentals so you can hopefully take it from there on to the landing page you desire. Here’s an example of the result:


The page will be constructed of four main components: Navigation bar, cover image, a grid of cards and finally the footer. 

The index.html is pretty straight forward, which contains mainly div tags and overall page structure:

<!DOCTYPE html>
  <title>Basic LP Layout</title>
  <link rel="stylesheet" type="text/css" href="./style.css">
  <nav class="zone blue sticky">
      <ul class="main-nav">
          <li><a href="">About</a></li>
          <li><a href="">Products</a></li>
          <li><a href="">Our Team</a></li>
          <li class="push"><a href="">Contact</a></li>
  <div class="container">
      <img class="cover" src="img/cover.jpg">
      <div class="coverText"><h1>Making the world a better place</h1></div>
  <div class="zone blue grid-wrapper">
      <div class="card zone">
          <img src="./img/startup1.jpg">
          <div class="text">
              <h1>Team play</h1>
              <p>We work together to create impact</p>
              <button>Learn more</button>
    <div class="card zone"><img src="./img/startup2.jpg">
        <div class="text">
            <p>Every goal is part of our strategy</p>
            <button>Learn more</button>
    <div class="card zone"><img src="./img/startup3.jpg">
        <div class="text">
            <p>We're focused on thinking different</p>
            <button>Learn more</button>
  <footer class="zone"><p>2019 Assaf Elovic All right reserved. For more articles visit <a href=""></a></p></footer>

Therefore, we’ll focus strictly on the styling (CSS). If you’re new to html and page structure, click hereto learn the basics before moving forward.

Styling layouts with Grid and Flex

Rule of thumb: Use Grid when you need grid-like views such as tables, cards, album media (like in Instagram). In all other use cases consider using Flex. I highly recommend diving deeper into both, since once you master them, you won’t need much else to create beautiful responsive web pages.

Navigation bar

We’ll use flex so we have a one direction row as needed for our navigation bar. Since we’re using a <nav> tag, we want to remove the dots (list-style). Finally, we’d like to remove any default margins set by the browser, so we reset margin: 0.

.main-nav {
    display: flex;
    list-style: none;
    margin: 0;
    font-size: 0.7em;

When changing the width size of our browser, we can see some of the nav bar cut out, so we need to modify how it’ll look when the width is smaller:

@media only screen and (max-width: 600px) {
    .main-nav {
        font-size: 0.5em;
        padding: 0;

We’d like the ‘Contact’ option to stick to the right so we set margin-left to ‘auto’. This will automatically set a maximum margin to the left of the hyperlink:

.push {
    margin-left: auto;

Finally, we’d like the navigation bar to stay sticky and always appear at the top of the page. Also, we’d like it to appear above all other elements (z-index):

.sticky {
  position: fixed;
  z-index: 1;
  top: 0;
  width: 100%;


We use Flex since we want to keep things simple (just center content). After setting our display to flex, justify-content centers content horizontal (X axis) within the container and align-items centers vertical (Y axis). We want the image to fit the entire screen so we set the height to 100vh, which means 100% of view height:

.container {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;

Also, we’d like the cover text to appear above the image and in the center:

.coverText {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
    color: white;
    font-weight: bold;

See the full CSS style sheetfor additional minor adjustments.

Grid of cards

As described above, we want to create a grid of cards so we’ll use Grid this time. grid-template-columns sets the style of each column (or div). FYI: If we were to just set 1fr, we would see just one block per column. So we set it to repeat (just like typing 1fr 1fr …) and autofill display with anything from min 350px to whole screen (1fr). Finally, we set the gri-gap (padding between grid objects) to 20px:

.grid-wrapper {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
    grid-gap: 10px;

Next, we’ll style each cardwithin the grid. The below is pretty straight forward for setting the margin per card and background color:

.card {
    background-color: #444;
    margin: 50px;

We’d like each card to have an image fit the entire top area, and under it have a title and paragraph and a button for ‘read more’. Also, we just want to manipulate images, titles and paragraphs within the class card, so we set it with the below:

.card > img {
    max-width: 100%;
    height: auto;

.card h1 {
    font-size: 1.5rem;

.card p {
    font-size: 1rem;

While the image fits 100% of the card’s width, we’d like to add some nice padding to the text area of the card:

.card > .text {
    padding: 0 20px 20px;

Finally, we set the button design that appears within each card. We’ll set the border to 0 (since default appears with a border), and add some padding, color, etc:

button {
    cursor: pointer;
    background: gray;
    border: 0;
    font-size: 1rem;
    color: white;
    padding: 10px;
    width: 100%;

button:hover {
    background-color: #e0d27b;


Last but not least, our footer is pretty straight forward. We’d like the inner text to be smaller than default, and pad the footer with some color:

footer {
    text-align: center;
    padding: 3px;
    background-color: #30336b;

footer p {
    font-size: 1rem;

That’s it! Following this simple responsive layout, you can further build almost any landing page your heart desires. To take this layout to the next level with some amazing animation libraries, here are some of my favorites:

  1. Sweet Alert — Add stylish alerts

  2. Typed.js — Add typing animation to your headers.

  3. Auroral — Add animated gradient backgrounds.

  4. Owl Carousel — Add animation to you elements

  5. Animate.css — Add styling animations upon loading elements.

To download the full source code click here!

What I wish I knew when I became VP R&D of a large startup

When I started my position as VP R&D at a growing startup, I thought my biggest challenges would be mainly technical. That is, provide state of the art architecture solutions, conduct code reviews, help solve complex algorithmic challenges and maybe even push some code. That’s because my previous technical leading positions were at small startups, where anyone who can code is needed when dealing with limited resources in a fast pace environment.

A few mistakes straight into the position, made me realize very quickly that leading an R&D of over 20 employees requires a whole different set of skills and focus. Just to clarify, my team was constructed of five divisions — Front End, Back End, Mobile, Research (mostly machine learning) and QA. So here are 6 lessons I wish I knew when starting this positions:

1. Don’t be the Hero

I truly agree with the saying “You’re only as successful as your team”. As engineers, we are constantly striving to be the ones solving complex problems, or in other words, being the hero. As the leader of your R&D, your job is to have a capable team that can solve any challenge on their own, without you. The more you try and solve for them, the more they’ll rely on you for future challenges. 

“You’re only as successful as your team”

I found this rule to be very hard to accomplish since sometimes it feels much more effective to bring out a solution from experience, than have your team research for days on days. However, down the line, it’s proven to be the most valuable lesson I’ve learned. With an independent and capable team, you’ll have much more time and focus to push and improve areas of your R&D that only you are capable of.

2. Get to know your people

Understanding what empowers and motivates your team members is power. It’s important to remember that every person is different: they need different things, have different communication styles, and focus on different things. Get to know what motivates each of your team members and what are their passions and career goals. This way you can leverage tasks and responsibilities based on it and maximize productivity and motivation within your team. It’ll also help retain your employees and make them feel more resourceful and self-fulfilled.

I schedule a weekly 1on1 meeting with each team leader and a monthly 1on1 with the rest of my team. In these meetings, I try to focus mainly on the personal level. Some meetings are very short, and some suddenly take hours. This policy provides me with a constant pulse of my teams’ status and motivation level, allowing me to prioritize who and when needs that extra push and attention. And believe me, there was always someone who needed it.

3. Never be a Bottleneck

The first mistake I did into the position, was took on a coding task. Coding is my comfort zone which is why I probably fell back to it. Very quickly I was flooded with unexpected top priority issues to deal with, hours and hours of staff, business and product meetings, not finding almost a single hour to focus on the coding task. Even when I did find some time, we all know coding requires getting “into the zone”, which was hard when constantly getting interrupted. In the end, I was creating a bottleneck in my own team, which almost delayed deployment. 

I am still amazed at how many unexpected issues can occur on a daily basis. From HR and external relations to technical and political company challenges. As a leader, you should make sure you’re always available to deal with urgent issues. If you take on yourself tasks such as deployment, you’ll either be risking being a bottleneck or not have enough time to deal with urgent tasks that only you can help solve effectively.

4. Always be the technical voice

Although you should understand and pursue business requirements as a leader in the company, there are enough people in high ranks prioritizing business and marketing needs over your R&D needs. You should trust that others will try and push needs which might contradict your teams’ needs. Your job is to be the technical voice within the staff. You should make sure all R&D requirements and needs are considered with the staff while taking other requests into consideration. In the end, if you don’t, your internal priorities will be constantly pushed down and your team will feel neglected.

For example, my team and I greatly wanted to migrate our services to AWS, from a private cloud. This would require a 40% capacity of my team for 3 months. It was immediately translated within the staff to 3 months of time that could be focused on building more product and marketing features to help the business grow. Then how do you prove what’s more important? If I was to take their approach, I would risk retaining my top talent engineers, have challenges acquiring new talent, suppress innovation and eventually decrease team motivation. By politically succeeding in selling the business advantages of the migration (it’ll reduce costs and speed up development) it was finally approved. Six months later, my top talent is still retained and motivated, deployment speed has risen by 50%, costs have been reduced by 65% (by taking advantage of AWS services such as Spot instances) and we’ve even got $100K in credits.

5. Focus on building processes and strategy

As someone who’s constantly aware of both the high-level business needs, and internal requirements and pains, you’re in the best position for focusing on building external processes. When I started the position, the first process I focused on, was how to conduct code reviews. While this is something that might be expected of a VP R&D, it is a process my team can probably build better than me. Since they face the daily challenges of deployment, understand each other’s styling preferences and coding standards, this was definitely an internal process I could give my team leaders to build, while I’d focus on external processes. Also, by having your team lead such internal processes, you’d increase overall engagement, sense of responsibility that would ultimately lead to more initiatives within your team.

An example of an external process would be the delivery process between the product and R&D team. Each division has its own requirements, culture, and needs. I’d conduct meetings with the VP Product, interview product managers, and my team leaders, to fully understand how to build a process that’s aligned with everyone’s needs and maximize delivery productivity. Only you have the time and resources to fully understand and see the high-level picture of what’s needed to accomplish such cross-functional external processes.

6. Always strive to be clear and aggressive about estimates

We’ve all been asked this questions before — “how long will this take?”, “why is it taking so long?”, etc. Surprisingly, we are often asked this kind of questions when things are not taking any longer than estimated. We are often asked these questions when our peers, either didn’t really like the original estimation or didn’t ask for it in the first place, and now they’re upset, despite nothing going wrong. Therefore, you must always be aggressive about sharing estimates and updating accordingly, even when people don’t ask. It is your job to make it clear, as best you can, what “long” actually is by providing your best view into the timescale of a project, and proactively updating that view when it changes.

Nonetheless, you should also be aggressive about getting estimates from your team, and constantly strive to improve their estimation process and instincts. Try to take part in estimation meetings, and don’t be afraid to challenge their input and cut scope toward the ends of projects in order to make important deadlines. Your role in these meetings may be to play a tiebreaker and make decisions about which features are worth cutting, and which features are essential to the project’s success.

Despite requiring several skills that are different from other technical roles, there are also some similarities. For example, just like in engineering, where each task brings on new unexpected challenges and constraints to deal with, so is here. In my opinion, the main skill for success in such a role (and I guess in almost any other role) is being able to embrace new, unexpected and dynamic challenges, while constantly striving to provide out of the box efficient and analytical solutions. 

I have no doubt many more lessons are to be learned as I continue my journey in such roles, so I hope to continue sharing them with you.

How to build a code review process

The ultimate guide for building your team’s code review process

After conducting hundreds of code reviews, leading R&D teams and pushing several unintentional bugs myself, I’ve decided to share my conclusions for building the ultimate code review process for your team.

This article assumes you know what is a code review. So if you don’t, click herefor a great intro.

Let’s quickly state some straight forward reasons as to why you should do code reviews:

  1. Can help reduce bugs in code.

  2. Validate that all coding requirements have been filled.

  3. An effective way to learn from peers and get familiar with the code base.

  4. Helps maintain code styling across the team.

  5. Team cohesion — encourage developers to talk to each other on best practices and coding standards.

  6. Improves overall code quality due to peer pressure.

However, code reviews can be one of the most difficult and time-consuming partsof the software development process.

We’ve all been there. Either you might have waited days until your code was reviewed, or once it was reviewed you started a ping pong with the reviewer of resubmitting your pull request. All of sudden you’re spending weeks going back and forth and context switching between new features and old commits that still need polishing.

If the code review process is not planned right, it could have more cost than value.

This is why it’s extremely important to structure and build a well defined process for code reviews within your engineering team.

In general, you’ll need to have in place well-defined guidelines for both the reviewer and reviewee, prior to creating a pull request and while it’s being reviewed. More specifically:

Define perquisites for creating pull requests.

I’ve found that the following greatly reduces friction:

  1. Make sure code compiles successfully.

  2. Read and annotate your code.

  3. Build and run tests that validate the scope of your code.

  4. All code in codebase should be tested.

  5. Link relevant tickets/items in your task management tool (JIRA for example) to your pull request.

  6. Do not assign a reviewer until you’ve finalized the above.

Define reviewee responsibilities

While the reviewer is last in the chain of merging your PR, the better it’s handed over by the reviewee, the fewer risks you’ll run into in the long term. Here are some guidelines that can greatly help:

  1. Communicate with your reviewer — Give your reviewers background about your task. Since most of us pull request authors have likely been reviewers already, simply put yourself in the shoes of the reviewer and ask, “How could this be easier for me?”

  2. Make smaller pull requests — Making smaller pull requests is the best way to speed up your review time. Keep your pull requests small so that you can iterate more quickly and accurately. In general, smaller code changes are also easier to test and verify as stable. When a pull request is small, it’s easier for the reviewers to understand the context and reason with the logic.

  3. Avoid changes during the code review — Major changes in the middle of code review basically resets the entire review process. If you need to make major changes after submitting a review, you may want to ship your existing review and follow-up with additional changes. If you need to make major changes after starting the code review process, make sure to communicate this to the reviewer as early in the process as possible.

  4. Respond to all actionable code review feedback — Even if you don’t implement their feedback, respond to it and explain your reasoning. If there’s something you don’t understand, ask questions inside or outside the code review.

  5. Code reviews are discussions, not dictation — You can think of most code review feedback as a suggestion more than an order. It’s fine to disagree with a reviewer’s feedback but you need to explain why and give them an opportunity to respond.

Define reviewer responsibilities

Since the reviewer is last in the chain before merging the code, a great part of the responsibility is on him for reducing errors. The reviewer should:

  1. Be aware to the task description and requirements.

  2. Make sure to completely understand the code.

  3. Evaluate all the architecture tradeoffs.

  4. Divide your comments into 3 categories: Critical, Optional and Positive. The first are comments that the developer must accept to change, and the latter being comments that let the developer know your appreciation for nice pieces of code.

I’ve also found that a following checklist is a great tool for an overall better and easier reviewing process:

  • Am I having difficulty in understanding this code?

  • Is there any complexity in the code which could be reduced by refactoring?

  • Is the code well organized in a package structure which makes sense?

  • Are the class names intuitive and is it obvious what they do?

  • Are there any classes which are notably large?

  • Are there any particularly long methods?

  • Do all the method names seem clear and intuitive?

  • Is the code well documented?

  • Is the code well tested?

  • Are there ways in which this code could be made more efficient?

  • Does the code meet our teams styling standards?

There are various effective and different code review approaches that vary based on team’s needs. So assume this is my personal opinion and that there are other ways that might work for your team. In the end, building such a sensitive process should be subjective to your companies goals, team’s culture and overall R&D structure.

If you have any questions or feedback for improving these guidelines, please feel free to add a comment below!

How my app grew by over 1M users in one month

Building and promoting a new consumer product is one of the most challenging things you can do as an entrepreneur. While there are many approaches on how to design, test, build and promote apps, usually they don’t seem to bring real results. 

Then you start wondering, maybe it’s the product? Maybe there’s not enough market fit? Or is it bad execution? Or maybe we should grow the marketing/branding budget? Maybe we’re not targeting the right audience? Maybe we should build more features!


When you start questioning everything, things usually get even worse. You start defocusing from the main goal and start wasting energy and money on all kinds of wide approaches.

The worst is when you think it’s all a matter of growing your marketing or branding budget.

Your goal should always be one — improving customer retention. For those who are not familiar with what is customer retention, click here.

To make my point clear, I’ll let you in on a story I heard from a friend of mine, who’s the Co-founder and CTO of a very successful productivity B2C company. In 2012, they’ve released the first version of their app to the Google store and a crazy thing happened. A few days since the launch, 500K users worldwide downloaded the app. The reason for that crazy growth was due to no good apps in the productivity space back then. Over the next few months, they’ve grown to a few million users and raised over 5M dollars from VCs. 

Four years later, they still couldn’t reach a decent business model, and he realized that despite the big numbers, there were very few actually using the product long term. So he decided to dig into the data and look for the reason. He found out that retention was very low, and what’s even worse, that it hasn’t improved much in four years! That’s when it hit him to focus on retention instead of user growth.

Back then, VC’s poured millions of dollars into companies with large user growth because they didn’t know how to deal or measure the crazy scale that mobile app stores and websites brought with them. Today the case is different. The first thing you’ll need in order to raise money in B2C is to show retention growth. And there’s a very good reason for that. Back to my friend’s story, with no retention, it didn’t matter how many users have downloaded their app. After a week, 95% of users have stopped using the product. So even if they had a billion users, after a few weeks all it would be is just a number in their database.

If you have 100K users using your product every day, it’s 100X more valuable than having 100M users using your product once a month.

Most importantly, once you’ve reached a decent retention rate, you can be sure that your marketing budget will lead to a sustainable growth of your product and business.

Too many startups begin with an idea for a product that they think people want. They then spend months, sometimes years, perfecting that product without ever showing the product, even in a very rudimentary form, to the prospective customer. This is where the Lean startupcomes in. In short, Lean Startup is a methodology that every startup is a grand experiment that attempts to answer one main question — “Should this product be built?”. 

A core component of Lean Startup methodology is the build-measure-learn feedback loop. The first step is figuring out the problem that needs to be solved and then developing a minimum viable product (MVP) to begin the process of learning as quickly as possible. Once the MVP is established, a startup can work on tuning the engine. This will involve measurement and learning and must include actionable metrics that can demonstrate cause and effect question.

So that’s exactly what we did at, with a few of our own twitches. FYI, Tiv.aiis a startup building an AI memory assistant which I’ve co-founded in January 2017. You can check out our product here.

Here are the steps we’ve taken in each iteration of building our product:

  1. Define the most important product assumption

  2. Design and build an MVP of how this assumption should be tested

  3. Target early adopters to test our MVP

  4. Apply the test results on the product

  5. Repeat

This is how our growth looked in the first year (2017) of iterations:

User activity from March 2017 to January 2018

User activity from March 2017 to January 2018

Slowly but surely right? Now let’s do an example together and see what happend after enough iterations.

1. Define the main assumption

We believed that there are no decent reminder apps that people actually like to use. The main reason in our opinion is that there’s a lot of friction in setting a single reminder. Either you need to fill a long form on a mobile app, or naturally ask an assistant like Siri, but realize she doesn’t understand 50% of your requests. So that’s when we defined our most important product assumption  —  If we could achieve understanding for almost every reminder request in natural language, users would use such a product long term.


2. Design and build an MVP

Since our assumption is focused on NLU (natural language understanding), we decided to focus solely on that. No branding, UX or other features. Just focus on improving the understanding. We’ve hired data scientists to build a state of the art NLU algorithm for understanding complex reminder requests. Secondly, since all we’re validating is this assumption, we’ve decided to build the MVP as a chatbot on Facebook Messenger, instead of going through the long and annoying process of building a mobile app. 

Please note! If we were to build a mobile app, this would not add anything to testing our assumption, and make our MVP longer and more complicated to design and build. Moreover, it might have even defocused us from the main assumption. For example, what if users just don’t like to use new apps anymore? We might’ve concluded that our assumption is wrong even though it was for a whole other reason. 

It’s important to narrow your MVP as much as possible, so there are no distractions from your main assumption.


3. Target early adopters

We needed English speakers since our algorithms only supported it. Also, we believed that millennial moms would eagerly want a product like this, since they’re always on the move and very busy, while constantly needing to remember things. So we targeted some Facebook pages (with no budget) which were based on a community of moms, and successfully brought onboard a few hundred beta testers to try it out.


4. Apply the test results on the product

After our first iteration, we’ve learned the following:

  1. There were much more ways to ask for reminders than we thought. But users extremely enjoyed the ease of setting reminders with a simple request.

  2. Users don’t always ask for reminders in a single request but break it to a few steps.

  3. When working with chatbots, users would like the assistance of buttons to make it faster and easier to handle.

With these results, we went on to our next main assumption, which was to add buttons to the flow of setting a reminder (conclusion 3). And guess what, that assumption also turned out to be true. For more proven assumptions, you can read my article on How to improve your chatbot.

Little by little, we improved our overall product and retention rate on a weekly basis. We never went on to tackle more than one assumption at a time. Slowly but surely, we started discovering users who were with us for over 6 months! After a year of weekly iterations, we’ve finally decided it was time to launch our product. We’ve reached a Week 1 retention rate of 92% and Week 4 of 16%. It’s way above the market standard which was enough for us.

We’ve published our chatbot on FB Messenger on mid Feb 2018 and within a month, have grown by over 5,800% as you can see below. 

Daily new users from Feb 17 to March 17

Daily new users from Feb 17 to March 17

This was mostly due to delivering a lean product that we knew people enjoyed and would recommend to others. Since then, we’ve grown to over 1M users worldwide and are growing by tens of thousands of users a day. 

User activity from Jan 01 to May 01

User activity from Jan 01 to May 01

We’re continuing to work with this methodology, and it’s proven a success every day. 

Not only did this methodology help us focus solely on what’s the most important set of features users want, but it also helped us filter out features we believed are valuable, but that are actually not. 

As said with customer service that the customer is always right, the same goes for product development. Trust your customers, listen to them and engage with them, understand what they want and don’t want. Never build things out of your own intuition unless it’s for assumption testing. At the end of the road you’ll reach one of two conclusions:

  1. The product does not have enough market fit, time to move on.

  2. You have a product people want. Good job, you’re on the way to building a company!

Either way, you win.

How to mine Ethereum in 5 min

How to mine Ethereum in 5 min

I’m sure you’ve already heard of the cryptocurrency craze way before reading this post. Cryptocurrencies are slowly and quietly revolutionizing the way financial systems and transactions work (and should work in my opinion).

With Bitcoin hitting its $6K mark not awhile ago, a current total of $158B in market cap and hundreds of ICOs (Initial Coin Offering) conducted since August, there’s a current bubble in the cryptocurrency space. What’s more, is that it doesn’t seem this bubble is going anywhere, anytime soon.



So what would be the best way to enter this space and enjoy the growth? I’m not a cryptocurrency expert, however, from my research I’ve found that the answer is pretty clear:

If you’re looking for quick earnings, just invest in coins. 

However, due to this ever-growing crypto market, mining in the short term could lead to significant earnings in the long term.

Personally, I’m very interested in Ethereum, and have found an effortless way to start mining it quickly on AWS! This post will walk you through the process.


What is Ethereum?

Ethereum is an open software platform based on the blockchain technology that enables developers to build and deploy decentralized applications. The advantage of Ethereum over Bitcoin, is that it can support many different types of decentralized applications.

Ethereum has gained massive growth in the last year with over 230% as you can see below:


However, increasing growth in the price leads to an increasing demand for Ethereum mining and therefore to an increase in mining difficulty:



So what is crypto mining?

Mining originates from the gold analogy of the cryptocurrency sphere. In simple, crypto mining is a process of solving complex math problems. “Miners” are people that spend time and energy solving these math problems. They provide the solution to the issuers, who verify it and reward the miners with a block of Ether. Intuitively, an increase in mining difficulty means it becomes harder to solve complex problems, and therefore to fewer rewards.


Is it worth it?

As more miners join the Ethereum network, the harder it becomes to solve the problem, which leads to an increase in the mining difficulty. This is why it’s currently costly to mine Ethereum. The returns are very low and equipment is pretty expensive. However, as Ethereum price continues to rise, it could become worthwhile in the future.

Nonetheless, Ethereum will be switching to a proof-of-stake framework later this year, which means mining could no longer be relevant. Take in mind, that this could also lead to a significant increase in Ethereum price.

If you’ve reached this far and still eager to mine Ethereum, let’s get to it!


How to start your AWS Mining instance

The steps are pretty simple:

  1. Go to your EC2 console in AWS and change the zone to US East (N.Virginia). This zone happens to be the cheapest for the type of instance we’ll be using, and also contains a community AMI that has all the required mining libraries already installed for instant use.
  2. Under Instances, select Spot Instances and click ‘Request Spot Instances’.
  3. Search for a community AMI called ami-cb384fdd and select it.
  4. Under Instance type choose g2.8xlarge.
  5. Review and Launch!


How to start mining

To start mining, you’ll need an Ethereum wallet and to join a mining pool. 

To generate a wallet, simply go to and follow the steps. By the end of the process, you’ll receieve a wallet address.

We’ll be using Dwarfpool for mining, which is rated in the top best mining pools. Feel free to use others if you like.

Simply SSH to your instance and type:

> tmux
> ethminer -G -F{WALLET ADDRESS}/{YOUR_EMAIL ADDRESS} --cl-local-work 256 --cl-global-work 16384

Tmux allows you to run a process when exiting your SSH connection.

Ethminer is an Ethereum GPU mining worker. Entering your email address allows you to receive notifications on payouts. The other parameters are for mining optimizations.

That’s it!

You should soon see a DAG file generated and right afterward, your mining should start. To view your stats, simply go to and in ‘Worker stats’ enter your wallet address.

Personally, I’ve concluded that due to the very high Ethereum mining difficulty, it’s not really worth it in the short and mid-term. No one can know for sure what the future of cryptocurrencies holds and if this is just a bubble that will soon pop. Some even say cryptocurrency trading is equivalent to buying lottery tickets. 

However, being a tech enthusiast and a believer in disruptions, I truly believe there’s a bright future for cryptocurrencies. If so, the current rise in Bitcoin and Ethereum is just the start. And one coin might be worth 100x its price today, which justifies mining it today.

Bots are here to stay. Here are strong reasons why.

For the past several years, I’ve been dedicating my life to learn, design, build and write about chatbots. The main reason chatbots fascinate me and conversational interfaces in general, is because they offer the most natural way for humans to interact with machines. Not only is the interaction natural, but also simple, clean and focused on what you need instantly. Think of Google’s search interface. All you can do is input search queries into a little text box. Everything that comes afterwards is magic.

Chatbots are still in their very early stage due to a few factors:

1. Lack of expectations between what chatbots can do and what users expect (or in other words, bad user experience). This leads to an instant disappointment and therefore to low usability. It starts with the largest bots such as Siri and all the way down to the very basic ones, which confuse users about their actual capabilities. In theory, Siri claims she can do almost anything related to your iPhone device, calendar and other internal Apple apps.

Screen Shot 2017-09-06 at 09.33.32.png

In reality, over 60% of what you ask Siri is not understood or results in general web search results. Just so you can get an idea of what she can do, here’s a list of Siri commands. Did you know she can do most of it? I didn’t before.

2. Educating users on creating new habits. The last bot I’ve built, was focused purely on conversation, and therefore did not have any buttons or menus. Retention was very low, despite the fact that most of the conversations between the bot and users were held successfully. What I’ve discovered, was that the more buttons and menus I added, the more retention grew. This led me to the conclusion that the majority of users are still not used to talking with machines naturally, but rather prefer to click on buttons as we’ve been used to for the past 30 years. Secondly, clicking buttons are faster than typing sentences. However, buttons are not faster than voice, which is why voice will eventually dominate the bot space. The transition from buttons to a natural conversation is growing but is still in its early adaption stage.

3. Artificial intelligence might have improved, but is still in its early stages. The reason this last and not first, is because I truly believe we can build great chatbots with todays current AI solutions (such as,, etc.) if bots were more focused on how to create user habits and offering a well designed user experience that meets user expectations. You can read more about how to do this in a previous post I’ve written on how to improve your chatbot with 3 simple steps. Obviously, AI will only improve with time as more and more data is collected and trained across a multitude of domains.

For all the reasons above and more, we’re still far from seeing the true potential of chatbots. However, there’s strong reasons why chatbots are here to stay and will improve exponentially over time:

The optimal Human to Machine interaction

If you think about it, we’ve learned over the past 30 years to adjust ourselves to the complexity and limitations of machines. This has been done via websites, applications, buttons, icons, etc. But in my opinion, the optimal scenario should be just the opposite - Machines should be able to adjust themselves to us humans, both from a natural language understanding perspective, and personalization.

Humans should be able to ask a machine anything naturally, instead of having to learn new interfaces, products, and habits for every service they need.

For example, let’s say you’d like to know the weather. Until recently, you’d have to find and pick a service of your choice out of many alternatives and learn how to use it functionally. Now, since every service tries to be innovative and different from its alternatives, this usually results in various UX/UI which means more learning and effort required by users. The optimal solution would be if you could just ask. Thankfully there’s many great solutions today for weather assistants (such as Siri or Poncho), and there’s many more to come in other domains.

Domain specific AI

Not very long ago, companies built virtual assistants which tried to go very wide and open, but quickly realized how hard it is to understand natural language. Going back to Siri’s example, Apple tried to capture many domains in order to display Siri as the ultimate personal assistant. This ambition failed very quickly. On the other hand, AI solutions that have succeeded, are the ones that focus narrowly on one specific domain.

Take for example Getdango - an AI solution for predicting emojis. They’re doing a great job predicting emojis based on natural language and it’s due to their narrow focus. Another example is Meekan, a scheduling assistant for teams on Slack. Meekan is a chatbot dedicated to providing the best solution for scheduling events as easily as possible.

The power of synergy where individual bots focus on specific domains, is the right approach for solving bigger AI challenges. You can see companies moving in this direction like FB Messenger’s latest release of handover protocol which enables two or more applications to collaborate. More importantly, Amazon partnered with Microsoft to collaborate on Alexa with the help of Cortana in order to provide a more powerful virtual assistant. If every bot was to focus on one specific domain, the race to AI in a whole, would be solved faster and more efficiently. Happily, that’s where we’re heading.

The power of long term relationships

The way most products are designed today, is to maximize instant short term value for users once they enter an application. While web and mobile applications focus on short term value, bots can and should focus on long term value. Bot developers should focus on how to build relationships with users over time so that value is gained and grows constantly with every single interaction. With time, bots should know enough about what they need, to maximize and personalize the user experience and minimize input friction. 

For example, say you’re looking for a travel planning service. The way you would go by it today, is to look at travel sites, fill the proper forms, and basically teach the site about your preferences and filters every single time. The way a bot should work, is to know which information is relevant to learn about the user, like personal information, preferences, budgets, places the user has already been to and etc. Bots should constantly learn from user’s behavior and offer much more personalized responses. 

The optimal way you’d be conversing with such a bot after some time, would be as follows:

Screen Shot 2017-09-06 at 09.23.02.png

The bot should know by now how many people are in your family, their ages, where you’ve already been to, where you’re at right now, what you like to do, what you don’t like and much more. In other words, the bot shouldn’t be any different from a real travel agent.

To see how much are users willing to share regarding their personal information within a conversation, I’ve conducted a research with one of my bots. The bot started asking users basic questions like “how old are you” all the way to more personal questions like “what are you most insecure about?”. Guess how many users answered all questions truthfully?… Over 85%. More specifically, 89% of women answered all questions truthfully, while “only” 81% of men answered all questions. So if you’re a bot developer, don’t be worried about users not sharing their information. Worry about what questions you should be asking in order to enhance the users long term value. This kind of information retrieval is something todays applications cannot achieve, and where chatbots have a huge advantage.

Cross platform usability

In just a few years, mobile apps have transformed to must-haves for smartphone users. But despite the increase in app usage and app choices, the number of apps used per user is staying the same, according to a recent report from Nielsen. Most people are tired of downloading mobile apps and learning about how to use new interfaces. 

In addition, research says that US citizens own in average 3.6 connected device. These devices can vary from mobile devices to Smart TVs and products like Amazon Alexa. That’s a lot of connected devices! Now obviously, users would like to interact with your service on any device they’re using. But what do you do? Build an application for iOS, Android, Smart TV, Alexa, Smart watch, iPad, Windows and Mac and more? Sounds like a lot of work. And it’s going to be very hard for you to get users to download your app in the first place, since they’re already flooded with other apps. 

This is where the beauty of messaging platforms comes in. At present, approximately 75% of all smartphone users use some sort of messaging apps such as WhatsApp, WeChat, Facebook Messenger, etc. Over 1.2 billion people worldwide have and use Messenger on their devices, all people that have mobile devices have SMS and obviously most have an email account. The list goes on. Instead of building applications and spending hundreds of thousands of dollars, just focus on building your bots back end. For the front end, just integrate your bot across multiple messaging platforms that are already on users devices and you’re set. If your service brings value, users will come. More importantly, turns out it’s what users want.

The future and success of chatbots depends not only on the big 4 tech companies, but on developers and entrepreneurs who continue to innovate and push boundaries in AI and conversational interfaces. Most of todays mistakes in the conversational user interface space, are tomorrows improvements and solutions. Eventually, bots will bring great value that cannot be achieved with most todays applications.

To learn more about chatbots go ahead and read the chatbots beginners guide. If you want to start building one, read this post on how to develop a Facebook Messenger bot.

How to Integrate your bot with Alexa in under 10 minutes

Why Alexa?

There’s no doubt Amazon's Alexa is currently one of the best consumer virtual assistants to find. In general, it seems consumers feel more comfortable speaking to a virtual assistant at home than in public (yet). More particularly, Alexa currently has over 8.2 million active users in the U.S. and awareness of the devices increased to 82% as of Dec. 31, 2016, up from 47% a year before that and 20% on March 31, 2015. Lastly, Alexa high demand for 3rd party service integrations. For these reasons and many more, I’d say it’s a smart move to integrate your service as well.

The Challenge

The challenge with integrating with Alexa when your service's interface is a bot, is that Alexa isn’t really set up for conversation. Since most services don’t provide a conversational interface, Alexa provides an interaction model that offers basic pattern matching and NLP. If you’ve built your own NLP engine, this is really bad news. It means you’ll need to classify thousands of patterns to enable the same ability you've already achieved with your bot. 

Luckily, I’ve found a work around thats actually so simple, it shouldn’t take you more than 10 minutes! In general, all you need to use is a slot type called AMAZON.LITERAL. From the Alexa Skills Kit documentation: "AMAZON.LITERAL passes the recognized words for the slot value with no conversion. You must define a set of representative slot values as part of your sample utterances." A while back, Amazon deprecated this solution but recently announced its return for good, so have no worries!

How Alexa works

For this tutorial, I’ll use a weather bot called Weabo, configured with a custom HTTPS endpoint (you can also use an AWS lambda function if you'd like). This is what happens when a user says something to Alexa:

  1. A Voice message comes in from user. The message pattern could be: “Alexa, ask Weabo what’s the weather in San Fransisco”
  2. An Alexa NLP engine classifies the message intent and extracts entities defined in advance. For example, the intent here could be “weather.get” and the entities “location=San Fransisco”.
  3. Results from the NLP engine are constructed into a request.
  4. The request is routed to a custom HTTPS endpoint of your choice, or to an AWS lambda function.
  5. A message response is returned from the request, and back to the user. A message response could be: "The weather in San Fransisco is 70 degrees".


We won't go into details of how to set up your Alexa skill, since there's so many great tutorials out there. Take a look at this one by Amazon, on developing an Alexa skill in under 5 minutes with a Lambda function, or this one for developing with a HTTPS endpoint.

Let's assume this is our endpoint function (written in Node.js):

function respond_to_incoming_message(req, res) {
  // Extract text message from request
  var text = req.body.text;
  // Extract text intent, entities and generate bot response
  var bot_response = respond_to_user_message(text);
  // Return response 

What we'd like to do, is to make sure a message sent to Alexa, arrives to the above endpoint as is, so your bot can take care of the parsing it and returning a proper response.

Once you've reached the 'Interaction Model' area of your Alexa skill configuration, add the following to the Intent Schema section :

  "intents": [
      "slots": [
          "name": "MessageText",
          "type": "AMAZON.LITERAL"
      "intent": "FreeText"

After that, add the following to the 'Sample Utterances' section:

FreeText {this is a sentence|MessageText}
FreeText {this is another sentence|MessageText}

Looking back at our endpoint function above, replace the first line with the following:

var text = req.body.intent.slots.MessageText.value;

That’s it! This will allow your users to talk freely with Alexa while using your own NLP engine.

Estimating an article's average reading time (Python)

Offering an article's reading time estimation to your site's content, can contribute greatly to your end users.  First of all, it allows end users to prepare the time they needs to read an article in full. Secondly, it could help them choose the right article for the right amount of available time they have. Lastly, it opens a whole new range of features, sorting options and filter improvements you can offer (like filtering articles by reading time).

In this post, I will walk you through on how to estimate the reading time of any public article url by crawling and making simple calculations (written in Python). By the way, this post was estimated to be 6 minutes.


Estimating words per minute

Words per minute, commonly abbreviated WPM, is a measure of words processed in a minute, often used as a measurement of the speed of typing or reading. WPM has many meanings and complications. The first is, that average reading time is subjective. Secondly, the length or duration of words is clearly variable, as some words can be read very quickly (like 'dog') while others take much longer (like 'rhinoceros'). Therefore, the definition of each word is often standardized to be five characters long. There are other parameters that effect the reading time such as font type and size, your age, rather you're reading on a monitor or paper, and even the number of paragraphs, images and buttons in the article's site. 

Based on research done in this field, people are able to read English at 200 WPM on paper, and 180 WPM on a monitor (the current record is 290 WPM).  

For the sake of simplicity, we'll define a word as five characters (including spaces and punctuation), and WPM = 200. Feel free to add additional parameters to your calculation. Note that if all you're looking for is a broad estimation, what we've defined will suffice.


From URL to Estimating reading time

Lets design the simple algorithm process:

  1. Extract visible webpage text (title, subtitle, body, page buttons, etc.) from given url.
  2. Filter unnecessary content from text.
  3. Estimate filtered text reading time.

1. Extracting visible webpage text

In order to extract a webpage's text content, we'll use Python libraries called BeatifulSoup and Urllib:

import bs4
import urllib, re

def extract_text(url):
    html = urllib.urlopen(url).read()
    soup = bs4.BeautifulSoup(html, 'html.parser')
    texts = soup.findAll(text=True)
    return texts

2. Filter unnecessary page content

Once we've extracted the desired text content, we need to filter out all the unnecessary content such styles (CSS), scripts (JS), html headers, comments, etc:

def is_visible(element):
    if in ['style', 'script', '[document]', 'head', 'title']:
        return False
    elif isinstance(element, bs4.element.Comment):
        return False
    elif element.string == "\n":
        return False
    return True

def filter_visible_text(page_texts):
    return filter(is_visible, page_texts)

3. Estimate reading time

To estimate the article's reading time, we need to count number of words (as defined above) and divide by defined WPM (200):

WPM = 200

def count_words_in_text(text_list, word_length):
    total_words = 0
    for current_text in text_list:
        total_words += len(current_text)/word_length
    return total_words

def estimate_reading_time(url):
    texts = extract_url(url)
    filtered_text = filter_visible_text(texts)
    total_words = count_words_in_text(filtered_text, WORD_LENGTH)
    return total_words/WPM

That's it! Feel free to test it out with any string url, by calling the method estimate_reading_time.

To view the source code, please visit my GitHub page. If you have any questions, feel free to drop me a line.

How to improve your chatbot in 3 simple steps

I have tested hundreds of chatbots and came to realize a key factor to why they fail in user experience. You may be thinking it has to do with the the chatbots purpose or the lack of powerful AI, but thats not usually the case. Actually, many of the chatbots have a very good purpose, and do solve a real problem or pain. 

The main reason these chatbots fail is because of a key element developers miss - Users are expecting to chat with your chatbot, not fill a form.  I will use a Weather Bot called Weabo as an example throughout this post. Lets take a look at the following conversation:

Screen Shot 2017-04-14 at 17.38.30.png

The above conversation usually occurs when your conversation logic looks something like this:

function generate_response(message, current_state) {
  if (current_state == "zipcode.get") {
    response = "This is not a valid Zipcode. Please try again";
    if (is_valid_zipcode(message)) {
      response = get_weather(message);
  return response

As much as we would hope so, users don't always follow the conversation flows we as bot developers have designed and expected. For most users this might even be the first time talking to a chatbot. They don’t understand the complexity of NLP/NLU and how fragile a bots understanding can be. So you can’t blame them for doing what they’re supposed to do - simple chat. Thats why you shouldn’t assume specific and strict user input because in many cases the user will be stuck in a infinite loop, lose patience and dump your chatbot. 

Here are 3 steps you can take to significantly improve your conversational experience without much work:

1. Provide small talk context understanding

In my opinion, every chatbot should standardize itself to understand and respond to basic small talk. You don't need to be an NLP or Machine expert to supply small talk to you chatbot. Just get familiarized with one of the many great 3rd party solutions out there such as,, Lex, etc… These solutions offer simple out of the box solutions for small talk. So for example if the user asked “What can you do”, you can easily catch that via 3rd party APIs and provide the appropriate response. Check out’s solution for small talk which I personally recommend and have found very useful - CLICK HERE.

To summarize thus far, supply small talk understanding for anything from a basic “hello” or “thank you”, to specific questions such as “what can you do?” In my opinion, this shouldn’t take you more than a days work. More strongly, once you’re obligated to provide answers to questions such as “what can you do?”, this will push you to really tighten your bots purpose and understand whats unique about it.

2. Keep your conversation flow logic loose

Conversation states are crucial to any chatbot so if you’re going in that direction - good job. However,  don’t build your flow logic such that you’re expecting a specific and strict answer from users, because thats where you can seriously fail. Instead, loosen your logic and accept the fact that users might decide to deviate from the flow you’ve built.

All you have to do, is reverse your current logic. If you’re expecting a Zip code as input at some conversation state, match the current state with the appropriate response only if you’ve first identified that there’s a valid Zip code in the users input. Otherwise, treat the current user input as a stateless message, ignore the users current state and respond accordingly. Also, take into consideration the retrieved intent from the 3rd party you've decided to integrate. Lets look at a refined example of the flow chart above:

function generate_response(message, current_state, intent) {
  if (intent == "") {
    response = "My name is Weabo :)";
  } else if (intent == "") {
    response = "Sure! You can type 'What is the weather in X?'"
  } else if (intent == "weather.get") {
    response = get_weather(message)
  } else if (is_valid_zipcode(message)) {
    if (current_state == "zipcode.get") {
      response = get_weather(message);
  return response

After implementing this logic, the conversation example above would look like this:

Screen Shot 2017-04-14 at 17.37.50.png

To summarize, try to first understand the intent/meaning of every incoming message, and only in the right cases, match them with users current states and respond accordingly.

3. Redirect unknown intents to what you do know

Lastly, I want to talk focus on unknown intents. Unknown intents are messages that the chatbot did not understand or knows how to respond to. I have identified that between 70%-80% of all users input falls into unknown intents. There are hundreds of blog posts I can write regarding how to improve your bots logic in this case, but for now I’ll focus on one - redirect the user to what your bot can understand. Think of the conversation as a pinball game. The user shoots a ball and your mission is to make sure the ball doesn’t enter the drains. In order to achieve that, is to provide hints and responses of what your bot can understand. For example: “I might understand this in the future. For now, I can tell you the weather. Try this: whats the weather in new york”.

Most users just want to understand your chatbots limits, what it can do, but mostly what it can’t do. The more you assist your users in understanding what your bot can’t do, the less users input will fall into the unknown intents category.


There is still so much you can do to improve your chatbots conversational experience. Whats important to understand, is the simplicity of significantly improving your chatbots user experience. More importantly, users want to chat, but mostly understand your chatbots abilities and how to improve their relationship with it. Treat the conversational interface as you would treat any basic human to human conversation, and forget what you’ve learned about web/app interfaces.

Last note: If you’re not planning to provide basic free text understanding, consider moving to persistent menus/quick replies. Its better to limit the users expectations at first, rather than to disappoint them.

I hope this post helped you in some way and thank you for taking the time to read it. Feel free to drop a comment if you have any thoughts!


URL text summarizer using Web Crawling and NLP (Python)

To skip this tutorial, feel free to download the source code from my Github repo here.

I’ve been asked by a few friends to develop a feature for a WhatsApp chatbot of mine, that summarizes articles based on URL inputs. So when a friend sends an article to a WhatsApp group, the bot will reply with a summary of the given URL article. I like this feature because from my personal research, 65% of group users don’t even click the shared URLs, but 97% of them will read a few lines of the articles summary.

As part of being a Fullstack developer, it is important to know how to choose the right stack for each product you develop, depending on the requirements and limitations. For web crawling, I love using Python. The Python community is filled with efficient, easy to implement open source libraries both for web crawling and text summarization. Once you’re done with this tutorial, you won’t believe how simple it is to implement the task.



For this tutorial, we’ll be using two Python libraries:

  1. Web crawling - Beautiful Soup. Beautiful Soup is a Python library for pulling data out of HTML and XML files. It works with your favorite parser to provide idiomatic ways of navigating, searching, and modifying the parse tree. It commonly saves programmers hours or days of work.
  2. Text summarization - NLTK (Natural Language Toolkit). NLTK is a leading platform for building Python programs to work with human language data. It provides easy-to-use interfaces to over 50 corpora and lexical resources such as WordNet, along with a suite of text processing libraries for classification, tokenization, stemming, tagging, parsing, and semantic reasoning, wrappers for industrial-strength NLP libraries.

Go ahead and get familiar with the libraries before continuing, and also make sure to install them locally. If you’re having trouble installing the libraries, follow this commands in your Terminal:

pip install beautifulsoup4
pip install -U nltk
pip install -U numpy
pip install -U setuptools
pip install -U sumy

After that, open Python command line and enter:

import nltk“stopwords”) 



Lets describe the algorithm:

  1. Get URL from user input
  2. Web crawl to extract the natural language from the URL html (by paragraphs <p>).
  3. Execute the summarize class algorithm (implemented using NLTK) on the extracted sentences.
    1. The algorithm ranks sentences according to the frequency of the words they contain, and the top sentences are selected for the final summary.
  4. Return the highest ranked sentences (I prefer 5) as a final summary.

For section 2 (1 is self explanatory), we’ll develop a method called getTextFromURL as shown below:

def getTextFromURL(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.text, "html.parser")
    text = ' '.join(map(lambda p: p.text, soup.find_all('p')))
    return text

The method initiates a get request to the given URL, and returns the extracted natural language from the URL html page.

For sections 3-4, we’ll develop a method called summarizeURL as shown below:

def summarizeURL(url, total_pars):
    url_text = getTextFromURL(url).replace(u"Â", u"").replace(u"â", u"")
    fs = FrequencySummarizer()
    final_summary = fs.summarize(url_text.replace("\n"," "), total_pars)
    return " ".join(final_summary)

The method calls the method above to retrieve the text, and clean it from html characters and trailing new lines (\n). Secondly, execute the Summarize algorithm (inspired by this post) on the given text, which then returns a list with the highest ranked sentences which is our final summary.



That’s it! Try it out with any URL and you’ll get a pretty decent summary. The algorithm proposed in this article as as stated, inspired by this post, which implements a simple text summarizer using the NLTK library. There are many summarization algorithms which have been proposed in recent years, and there’s no doubt there are even better solutions. If you have any suggestions, recommendations I’de love to hear about them so comment below!

Feel free to download directly the source code via my Github account.

How to develop a Facebook Messenger bot (using Node.js and MongoDB)

To skip the tutorial, feel free to download the source code from my Github repo here.

In very little time, there are quite a few very good tutorials out there for beginners about how to develop a Facebook Messenger bot. However, these tutorials describe a stateless bot. What that means is, that for every user who send a message to your bot, there is no info saved regarding his current state in the conversations, and other basic info. This is why I've decided to write this tutorial, which consists of a basic implementation of a Facebook Messenger bot, in addition to a functional working MongoDB library. 

Saving end users specific states dynamically within a conversation, is crucial for the UX of any basic chat bot. Saving states allows the bot to communicate with the end users in a flow which follows some pattern, that otherwise would not be possible. 

Getting started

For starters, you'll need a Facebook developers account which can be found here.

Secondly, follow the beginning of the process for creating a Facebook page and set up a 'Webhook' (up until step 5) by clicking here. Note: You should write down the verification code which you've provided to the web hook in the tutorial. Secondly, once you've got a Facebook page up and running, look up the page token, and send a POST request with the following:<TOKEN_GOES_HERE>

You should get a response 'true' which means you've synced your Facebook page with the provided API.

Lastly, please get familiar with the basics of Node.js and MongoDB. It is recommended to learn the basics of MongoDB. In addition, you should understand the basics of writing in Node.js and ES6.

Now let's create you very first Facebook messenger chat bot!

Facebook API Structured messages

First things first. Understand and learn the basic concepts of the Facebook API - click here. Let's look at an example:

"welcome_message": {
  "attachment": {
    "type": "template",
      "payload": {
        "template_type": "button",
          "text": "Hello and welcome to your first bot. Would you like              to get see our products?",
            "buttons": [
                "type": "postback",
                "title": "Yes",
                "payload": "get_options"
                "type": "postback",
                "title": "No",
                "payload": "no_options"

In the example above, you can see that for every message sent to Facebook, we need to declare the type of message, which is in this case a template (for basic text, text is enough). In addition, we declare the template type which is buttons in this case, and the buttons themselves. For every button, we need to declare the button title, type and payload. Type is so we'll know how the button click is handled, and payload is so we can identify which button the user clicked (a further example is described in the source code). 

Server side

The basic and required implementation for the server side, is to set up a GET handler for the url/webhook/, and a POST for the same url/webhook/. The GET handler is for Facebook verification when applying your url webhook and should be as follows:

function facebookVerification(req, res) {
    if (req.query['hub.verify_token'] === WEBHOOK_TOKEN) {
    } else {
        console.error("Failed validation. Make sure the validation          tokens match.");

Note: the WEBHOOK_TOKEN above is to be stated as you've declared when initializing the webhook. Facebook shows an example with 'my_voice_is_my_password_verify_me'. You can leave it as is and update the source code.

The second and most important method is the POST. Facebook Messenger sends every ICM (Incoming message) sent to your bot page, via POST to the url you've declared in the developers portal. The method should handle all ICM either those which arrived by user clicks, or by free text. I will describe three methods which are used in this case:

// 0 MongoDB info
const mongoose = require('mongoose');
const User = mongoose.model('User', {_id: String, name: String, profile_image_url: String, phone_number: String, current_state: String});
// 1'/webhook/', facebook_parser.facebookWebhookListener);
// 2
function facebookWebhookListener(req, res) {
    if (!req.body || !req.body.entry[0] ||                      !req.body.entry[0].messaging) {
        return console.error("no entries on received body");
    let messaging_events = req.body.entry[0].messaging;
    for (let messagingItem of messaging_events) {
        let user_id =;
        db_utils.getUserById(user_id, messagingItem, parseIncomingMSGSession);
// 3
function getUserById(user_id, incomingMessage, callback) {
    var result = null;
    //Lets try to Find a user
    User.findById(user_id, function (err, userObj) {
        if (err) {
        } else if (userObj) {
            result = userObj;
            console.log('User ' + user_id + ' exists. Getting current user object:', userObj);
        } else {
            console.log('User not found!');
        // After getting user object, forward to callback method.
        callback(user_id, incomingMessage, userObj);
// 4
function parseIncomingMSGSession(user_id, messageItem, userObj) {
    var current_state = "welcome_message";
    if (userObj != null) {
        current_state = userObj.current_state;
    // If we recieve any text message, parse and respond accordingly
    if (messageItem.message && messageItem.message.text) {
        // Currently support a static welcome message only
        sendFacebookGenericMsg(user_id, message_templates.templates["welcome_message"]);
    // If the user sends us a button click
    if (messageItem.postback && messageItem.postback.payload) {
        var button_payload_state = messageItem.postback.payload;
        switch (button_payload_state) {
            case "get_options":
                sendFacebookGenericMsg(user_id, message_templates.templates["options_message"]);
            case "no_options":
                sendFacbookTextMsg(user_id, "Ok. There is so much you can do with stateful bots!");
    // Save new user state. If user does not exist in DB, will create a new user.
    db_utils.setUserFieldById(user_id, "current_state", "");

The first step (commented) is for listening to POST requests and forwarding them to a method called facebookWebhookListener (method 2). This method then retrieves from the POST body the relevant info such as the message item (consists of user unique id, message text, etc) and forwards the content to a method called getUserById (method 3).

The method getUserById (method 3), uses the info set at the top (comment 0), and tries to retrieve a user with the given id in the DB. If the user is not found, a null will be returned, and the info is passed to a callback function which is in our case, parseIncomingMSGSession (method 4). 

The method parseIncomingMSGSession (method 4), is in charge of sending an OGM (Outgoing message) based on the user info. In the case above, the default state is "welcome_message". Secondly, the method obtains the type of the ICM, which could either be a text message, or a clicked message (when user clicks on buttons the bot provided). Based on the ICM and users state, a relevant message is sent. There are additional methods declared in the code above, which I will not explain, since they are pretty much self explanatory and can be found in full in the source code provided at the top of this post (or at the end). Feel free to ask me any questions regarding any of the methods and general flow of the server side.

Finally, in order to send back a response to the end user, you'll need to send a POST request with the message template as described above and with the following structure:

// Send generic template msg (could be options, images, etc.)
function sendFacebookGenericMsg(user_id, message_template) {
        url: '',
        qs: {access_token: TOKEN},
        method: 'POST',
        json: {
            recipient: { id: user_id },
            message: message_template
    }, facebookCallbackResponse);

function facebookCallbackResponse(error, response, body) {
    if (error) {
        console.log('Error sending messages: ', error)
    } else if (response.body.error) {
        console.log('Error: ', response.body.error)

The TOKEN shown above is the page token you've received via the Facebook developers portal page. Congratulations! You've completed your very first Facebook messenger bot. The source code is built in such a way, that it'll be very easy for you to scale it up to a fully functional chatbot.

To view the full project source code, click the button below. Feel free to ask any questions you might have, and I'll answer you ASAP! 

Chatbots - The beginners guide

If you search for chatbots on Google, you'll probably come across hundreds of pages starting from what is a chatbot to how to build one. This is because we're in 2016, the year of the chatbots revolution.

I've been introduced to many people who are new to this space, and who are very interested and motivated in entering it, rather they're software developers, entrepreneurs, or just tech hobbyists. Entering this space for the first time, has become overwhelming in just a few months, particularly after Facebook announced the release of the messenger API at F8 developer conference. Due to this matter, I've decided to simplify the basic steps of entering this fascinating world.

What is a chatbot?

To fully understand what is a chatbot and its potential, lets start by watching the following example:

Get the idea? The conversation example above, was conducted between an end user and a chatbot, built on the Facebook messenger platform.

So what is a chatbot? It is a piece of software that is designed to automate a specific task. More specifically, a chatbot is essentially a conversational user interface which can be plugged into a number of data sources via APIs so it can deliver information or services on demand, such as weather forecasts or breaking news. 

Why now?

Chatbots have been around for decades right? So what is all this noise all of a sudden? This question has many different answers, depending on who you ask. If you ask me, there are two main reasons:

1. Messaging has become the most essential and most popular tool for communication. 

2. We're closer to AI (Artificial intelligence) and NLP (Natural Language Processing) breakthroughs than ever before. This means that talking to a chatbot can closely become as real as talking to a human. Today, developers can find many APIs that offer AI/NLP services, without even understanding how AI/NLP works - This is HUGE. A few examples I recommend are,, (a must!), and

Basically, the point I'm trying to make is, that messaging platforms are the place we all go to on a regular basis. So why not bring all the other places into this platforms? This is what Facebook did with Facebook Messenger.

Facebook Messenger is far more than a messenger app. It is a store for thousands of apps which are integrated into our daily conversations. Furthermore, as stated above, Facebook has released its chatbot platform in April, 2016. Since then, more than 11,000 bots have been added to Messenger by developers.

Where are the chatbots?

The first chatbot I built was on WhatsApp. The reason I chose WhatsApp, is because all my friends use it as their main messaging platform. Unfortunately, WhatsApp doesn't offer an official API. What this means is, that WhatsApp doesn't approve building chatbots on its platform (not a surprise since WhatsApp is a Facebook company, which itself offers an extensive API). This doesn't mean that there aren't any work arounds. If you're as stubborn as I am, take a look at yowsup and start from there. You'll also need a registered phone number before starting the process. So to conclude, WhatsApp is probably not the place you'll find rich and powerful chatbots. 

Platforms that do offer official APIs are:

1. Facebook Messenger

2. Slack

3. Telegram

4. Kik

There are other deployment channels such as Android and iOS (via SMS), Skype and even Email. However, the listed above are the ones I would focus on.

You can find a rich list of most of the chatbots out there by clicking here, thanks to our friends at that did an amazing job. 

How do I build a chatbot?

This requires a long answer. An answer I will save for my next blog post, in which I will describe how to build your very first chatbot using Node.js and MongoDB.

If you're not a developer, or is looking for an easier approach which does not require programming, here are a few solutions for you:

1. Chatfuel - My first choice. No coding required. Easily add and edit content— what you see is what you get.

2. Botsify - Build a facebook messenger Chatbot without any coding knowledge. 

3. - Meya helps with the mechanics of bot building so you can concentrate on the fun stuff.

There is some downsides to using a service instead of building your own. Using the above services limit your creativity in many ways, enabling you only a glimpse of what can be done. Secondly, you are using a third party hosting service, which means you're stuck with them. Nevertheless, these are great solutions for services that will get you started with chatbots, without the need for any coding knowledge.


There has been a lot of controversy rather bots will succeed or fail in the near future. To understand the controversy, you have to understand the differentiation between "stupid" bots and "smart" bots. "Stupid" bots work with structured input, while "smart" bots process your natural language and provide a more human-to-human experience.

The main issue with "stupid" bots is that as soon as people start bundling things up, changing their minds, going back to what has been mentioned earlier in the chat, etc., the bot falls apart. Therefore, as long as chatbots can't fully conduct a conversation naturally, while understanding the intent of the user at every stage, bots will be limited and ineffective. 

Having said that, in my opinion, chatbots don't have to be smart in order to succeed. There are thousands of use cases in which a "stupid" chatbot can simplify both the end users experience, and the business side productiveness. Take for example ordering Pizza. You can create a flow in which the user needs to enter inputs based on questions and options. You can deliberately state the input you're expecting from the user, and therefore the need for NLP or AI becomes irrelevant. I would prefer ordering pizza from a "stupid" bot then over the phone, or some cheap website any day. 

To fully summarize the above and much more, have a look at the Chatbot ecosystem, brought together by Business Insider.

Stay tuned for my next blog post, about how to develop your very first Facebook Messenger chatbot, using Node.js and MongoDB.


Recursively find all duplicate files in a directory (Java)


Sure this could be implemented using a few lines of basic Linux commands. However, understanding how to write such code in Java, requires understanding in several topics - Hash tables, recursion, lists, file system, and more.

That is why I love this problem. Not only does it concern understanding much of Java's fundamentals, but also there is great deal of required efficiency regarding time complexity and space complexity.

Duplicate detection using hash

The first problem to take into consideration is, how do I detect duplicated files? Should I only consider file names? What about file size? Maybe both? Considering both is still not enough. It's pretty easy to come up with a counter example for this approach. Take for example File A thats called fileA.txt and file B called fileB.txt. fileA.txt contains the word "hello" however fileB.txt contains the word "world". Both files contain the same name and size, however are not identical. That is why my approach will contain reading the files bytes, and saving a unique hash id for each file.

    private static MessageDigest messageDigest;
    static {
        try {
            messageDigest = MessageDigest.getInstance("SHA-512");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("cannot initialize SHA-512 hash function", e);

In the above code, we apply a notable secure hash function called SHA-512. We will use this function to create a unique id for each of the files in the file system.

Duplicated files retrieval using Hash Table

Our second problem, is how to store the files id hash efficiently for future retrieval in an efficient way. One of the best methods for retrieval efficiently is of course Hash Tables which if implemented properly, enable retrieval in O(1) complexity time. What we'll do is store the hash unique id's as keys, and for every key, the value will be a Linked List containing all of the duplicated String paths associated to the same key. Such hash id's are very very big which is why we'll also use the Java library BigInteger.

And finally, we'll traverse all sub directories and files recursively, such that for each directory, traverse all of it's files. The final implementation is as follows:

public static void findDuplicatedFiles(Map<String, List<String>> lists, File directory) {
        for (File child : directory.listFiles()) {
            if (child.isDirectory()) {
                findDuplicatedFiles(lists, child);
            } else {
                try {
                    FileInputStream fileInput = new FileInputStream(child);
                    byte fileData[] = new byte[(int) child.length()];
                    String uniqueFileHash = new BigInteger(1, md.digest(fileData)).toString(16);
                    List<String> list = lists.get(uniqueFileHash);
                    if (list == null) {
                        list = new LinkedList<String>();
                        lists.put(uniqueFileHash, list);
                } catch (IOException e) {
                    throw new RuntimeException("cannot read file " + child.getAbsolutePath(), e);

All thats left is to run the above method and print out the Hash tables key values if such exists (that is that the associated linked lists hold duplicates.

Map<String, List<String>> lists = new HashMap<String, List<String>>();
        FindDuplicates.findDuplicateFiles(lists, dir);
        for (List<String> list : lists.values()) {
            if (list.size() > 1) {
                for (String file : list) {

The source code can be found in the download link below:

Feel free to ask any related questions in the comments below.

How to create a dynamic HTML Email Template

HTML automated emails  have come a long way in the past couple of years. What used to be a text-only email, today contains various forms, dynamic links, images, depending each company on there personal style displays.

Today, receiving HTML emails is a standard to most leading companies, which is why adapting this principle over regular text only emails has become a must. 

Developing HTML templates doesn't require a lot of coding skills, however knowing how to code the template to appear correctly on all devices and old email clients is the real challenge.

In this blog post I will go through a step by step guide of how to build a dynamic email template via HTML and PHP.

Basic guidelines

As I've described above, the biggest challenge with developing an HTML email template, is making sure it's cross-platform-compatible. There are so many email clients such as Google Mail, Apple Mail, Outlook, AOL, Thunderbird, Yahoo!, Hotmail, Lotus Notes and etc. Some of these clients and others are light years behind the eight-ball in terms of CSS support, which means we must resort to using HTML tables to control the design layout if we really want our email template to display consistently for every user. In fact, using HTML tables is the only way to achieve a layout that will render consistently across different mail clients. Think of the template as being constructed of tables within tables within tables...

Secondly, we must use inline CSS to control elements within your email, such as background colors and fonts. CSS style declarations should be very basic, without use of any CSS files.

To emphasize the HTML tables rule above, see the example below, where I've modified the border attribute of each table to be visible. Please note that the %s is a placeholder where dynamic text and images will be filled as I'll see soon describe (Scroll to the end to see the final email template):

Screen Shot 2016-04-29 at 14.12.47.png

As you can see above, the whole layout is built by HTML tables. We'll be using PHP libraries to parse the %s place holder and fill it with dynamic text before an email is sent to the user.

Developing the static template

So let's start programming! Before we begin the template itself, you'll need to begin your HTML file with an XHTML document:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>Demystifying Email Design</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>

I recommend defining all tables with border="1" as seen above since it's easier to spot errors and see the skeleton of the layout as you go along. At first, let's create the basic layout:

<body style="margin: 0; padding: 0;">
 <table border="1" cellpadding="0" cellspacing="0" width="100%">
    My first email template!

Set your cellpadding and cellspacing to zero to avoid any unexpected space in the table. Also set the width to 100% since this table acts as a true body tag for our email, because styling of the body tag isn't fully supported.

Now we'll add instead of the text 'My first email template!' another table which will present the actual email template display.

<table align="center" border="1" cellpadding="0" cellspacing="0" width="600" style="border-collapse: collapse;">
   This is the email template body

As you can see, the width is set to 600 pixels. 600 pixels is a safe maximum width for your emails to display correctly on most email clients. In addition, set the border-collapse property to collapse in order to make sure there are no unwanted spaces between the tables and borders.

In the example above, you can see that our email template consists of five sections (rows) which is why we'll create these rows and then add tables accordingly to each in order to complete the template.

<table align="center" border="1" cellpadding="0" cellspacing="0" width="600">
   Row 1
   Row 2
   Row 3
   Row 4
   Row 5

At each row, we'll create a new table in which the mythology is similar to the above. We'll also add columns accordingly and the right paddings to align all objects to reach the desired template.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>Automatic Email</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<body style="margin:0; padding:10px 0 0 0;" bgcolor="#F8F8F8">
<table align="center" border="1" cellpadding="0" cellspacing="0" width="95%%">
        <td align="center">
            <table align="center" border="1" cellpadding="0" cellspacing="0" width="600"
                   style="border-collapse: separate; border-spacing: 2px 5px; box-shadow: 1px 0 1px 1px #B8B8B8;"
                    <td align="center" style="padding: 5px 5px 5px 5px;">
                        <a href="http://url-goes-here" target="_blank">
                            <img src="http://logo.png" alt="Logo" style="width:186px;border:0;"/>
                    <td align="center">
                        <!-- Initial relevant banner image goes here under src-->
                        <img src="%s" alt="Image Banner" style="display: block;border:0;" height="100%%" width="600"/>
                    <td bgcolor="#ffffff" style="padding: 40px 30px 40px 30px;">
                        <table border="1" cellpadding="0" cellspacing="0" width="100%%">
                                <td style="padding: 10px 0 10px 0; font-family: Avenir, sans-serif; font-size: 16px;">
                                    <!-- Initial text goes here-->
                    <td bgcolor="#E8E8E8">
                        <table border="1" cellpadding="0" cellspacing="0" width="100%%" style="padding: 20px 10px 10px 10px;">
                                <td width="260" valign="top" style="padding: 0 0 15px 0;">
                                    <table border="1" cellpadding="0" cellspacing="0" width="100%%">
                                            <td align="center">
                                                <a href="tel:phone number goes here" target="_blank">
                                                    <img src="url for call image goes here.png" alt="Call us"
                                                         style="display: block;"/>
                                            <td align="center"
                                                style="font-family: Avenir, sans-serif; color:#707070;font-size: 13px;padding: 10px 0 0 0;">
                                                GIVE US A CALL
                                <td style="font-size: 0; line-height: 0;" width="20">
                                <td width="260" valign="top">
                                    <table border="1" cellpadding="0" cellspacing="0" width="100%%" >
                                            <td align="center">
                                                <a href="">
                                                    <img src="url for email image goes here" alt="Email us"
                                                         style="display: block;"/>
                                            <td align="center"
                                                style="font-family: Avenir, sans-serif; color:#707070;font-size: 13px;padding: 10px 0 0 0;">
                                                EMAIL US
                                <td style="font-size: 0; line-height: 0;" width="20">
                                <td width="260" valign="top">
                                    <table border="1" cellpadding="0" cellspacing="0" width="100%%">
                                            <td align="center">
                                                <a href="url to faq page goes here" target="_blank">
                                                    <img src="url for faq image goes here" alt="FAQ Page"
                                                         style="display: block;"/>
                                            <td align="center"
                                                style="font-family: Avenir, sans-serif; color:#707070;font-size: 13px;padding: 10px 0 0 0;">
                                                BROWSE FAQ PAGE
                    <td bgcolor="#66989c" style="padding: 15px 15px 15px 15px;">
                        <table border="1" cellpadding="0" cellspacing="0" width="100%%">
                                <td align="center">
                                    <table border="1" cellpadding="0" cellspacing="0">
                                                <a href="facebook url goes here" target="_blank">
                                                    <img src="facebook image goes here" alt="Facebook" width="50" height="50"
                                                         style="display: block;" border="1"/>
                                            <td style="font-size: 0; line-height: 0;" width="20">&nbsp;</td>
                                                <a href="youtube page link goes here" target="_blank">
                                                    <img src="youtube image link goes here" alt="Youtube" width="50" height="50"
                                                         style="display: block;" border="1"/>
                                            <td style="font-size: 0; line-height: 0;" width="20">&nbsp;</td>
                                                <a href="twitter page goes here" target="_blank">
                                                    <img src="twitter image goes here" alt="Twitter" width="50" height="50"
                                                         style="display: block;" border="1"/>
                                            <td style="font-size: 0; line-height: 0;" width="20">&nbsp;</td>
                                                <a href="linkedin page goes here" target="_blank">
                                                    <img src="linkedin image goes here" alt="Linkedin" width="50" height="50"
                                                         style="display: block;" border="1"/>
                                            <td style="font-size: 0; line-height: 0;" width="20">&nbsp;</td>
                                                <a href="home page goes here" target="_blank">
                                                    <img src="homepage image goes here" alt="GreenIQ" width="50" height="50"
                                                         style="display: block;" border="1"/>

A few observations: 

  1. Add alt attributes where needed in order to present text instead of images incase the email client was unable to load them properly. 
  2. Add %s place holders where you'd like the data to appear dynamically depending on the email use case.
  3. If you look carefully, the percentage values appear with an extra '%'. This is so the PHP library used to making this dynamic, knows how to parse the text properly.

Note! I've removed the URLs for security and privacy issues. You can replace them with your own images and personal links.

And that is it! You've successfully developed your own email static template. Now let's get our hands dirty and make it dynamic!

Developing the dynamic template

Save the above code as a template.html file. Now let's create a new PHP file.

On the server side, create the email send method below:

function send_mail_template($to, $from, $subject, $message)
  $headers = "MIME-Version: 1.0" . "\r\n";
  $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
  $headers .= "From: ContactNameGoesHere <" . $from . ">\r\n";
  $response = mail($to, $subject, $message, $headers);

Now if you look carefully back to the HTML email template, you'll see that I've added %s place holders in certain places. More particularly, in the image banner element, and body text. Now all we need to do is import the above HTML template, parse it like regular text, add the relevant text in place of the '%s' and use the above send_mail_template method.

function build_email_template($email_subject_image, $message)
    // Get email template as string
    $email_template_string = file_get_contents('template.html', true);
    // Fill email template with message and relevant banner image
    $email_template = sprintf($email_template_string,'URL_to_Banner_Images/banner_' . $email_subject_image. '.png', $message, $mobile_plugin_string);
    return $email_template;

After we've got that taken care of, we can use both methods and send are very first dynamic email! Let's use an example. Say a new user has just verified his email. We'd like to automate that use case on the server side and send the user a 'Your email has been successfully verified' email. 

Assume we have the users verified email '' and the company's email is ''. We can now send an automated email:

$from = "";
$to = "";
$body_text = "Your email has been successfully verified...";
$banner_image_subject = "account_verified";
$final_message = build_email_template($banner_image_subject, $body_text);
send_email($to, $from, "You email has been verified", $final_message);

Finally! You can now use this methodology any way needed. After sending this example, while applying the GreenIQ's company images and text, this is the final email template sent to the user:

Feel free to ask any question below!

How to send push notifications with PHP

Sending push notifications to an iOS/Android Application can enhance the user experience exponentially, while allowing you to deliver key information easily. However, sending the push notification to users can be a bit tedious at times, and at times confusing. You need to ensure that you pack your integers, and times correctly - failing to do this and you'll probably get an unhelpful status from Apple or Google.

I've came across some online PHP Scripts for either iOS or Android implementation however not for both. This PHP script includes implementation for both mobile operating systems.

PHP Script (For a description, scroll below the script):

function send_mobile_notification_request($user_mobile_info, $payload_info)
    //Default result
    $result = -1;
    //Change depending on where to send notifications
    $pem_preference = "production";
    $user_device_type = $user_mobile_info['user_device_type'];
    $user_device_key = $user_mobile_info['user_mobile_token'];
    if ($user_device_type == "iOS") {
        $apns_url = NULL;
        $apns_cert = NULL;
        //Apple server listening port
        $apns_port = 2195;
        if ($pem_preference == "production") {
            $apns_url = '';
            $apns_cert = __DIR__.'/cert-prod.pem';
        //develop .pem
        else {
            $apns_url = '';
            $apns_cert = __DIR__.'/cert-dev.pem';
        $stream_context = stream_context_create();
        stream_context_set_option($stream_context, 'ssl', 'local_cert', $apns_cert);
        $apns = stream_socket_client('ssl://' . $apns_url . ':' . $apns_port, $error, $error_string, 2, STREAM_CLIENT_CONNECT,                                   $stream_context);
        $apns_message = chr(0) . chr(0) . chr(32) . pack('H*', str_replace(' ', '', $user_device_key)) . chr(0) . chr(strlen($payload_info)) .                               $payload_info;
        if ($apns) {
            $result = fwrite($apns, $apns_message);
    else if ($user_device_type == "Android") {
        // API access key from Google API's Console
        // prep the bundle
        $msg = array
            'message' => json_decode($payload_info)->aps->alert,
            'title' => 'This is a title. title',
            'subtitle' => 'This is a subtitle. subtitle',
            'tickerText' => 'Ticker text here...Ticker text here...',
            'vibrate' => 1,
            'sound' => 1,
            'largeIcon' => 'large_icon',
            'smallIcon' => 'small_icon'
        $fields = array
            'registration_ids' => array($user_device_key),
            'data' => $msg
        $headers = array
            'Authorization: key=' . API_ACCESS_KEY,
            'Content-Type: application/json'
        $ch = curl_init();
        curl_setopt( $ch,CURLOPT_URL,                     '' );
        curl_setopt( $ch,CURLOPT_POST, true );
        curl_setopt( $ch,CURLOPT_HTTPHEADER, $headers );
        curl_setopt( $ch,CURLOPT_RETURNTRANSFER, false );
        curl_setopt( $ch,CURLOPT_SSL_VERIFYPEER, false );
        curl_setopt( $ch,CURLOPT_POSTFIELDS, json_encode( $fields ) );
        $result = curl_exec($ch);
    return $result > 0;

function create_payload_json($message) {
    //Badge icon to show at users ios app icon after receiving notification
    $badge = "0";
    $sound = 'default';
    $payload = array();
    $payload['aps'] = array('alert' => $message, 'badge' => intval($badge),'sound' => $sound);
    return json_encode($payload);


Let's start. The first method builds the body of the notification request depending on the users operating system and sends accordingly. The flow process for sending push notifications is first to Apple/Google servers, and only then to the end user. Therefore, each end user holds on his mobile device, a unique token. Learn more about how to retrieve the user device key in Android or iOS.

Personally, I wrote the main method such that the input contains $user_mobile_info - An array containing the user's device and unique device key, and $payload_info - A JSON which contains the body message for sending the push notification request (Found in the second method). The $pem_preference variable inside the method is also hard coded, however can be changed to your preference. Apple offers two servers for development - sandbox for QA ( and regular for production ( If you're in the testing phase of your development, just change the url or the variable itself.

The second method builds the message body. I've hard coded some variables such as the sound and badge. Sound can be changed to various options, and badge describes the badge to be shown when the user receives the notification. I've modified it to "0", meaning there will be no badge icon when receiving notifications.

Usage Example

The main part of the push notification is the message itself. Let's say the notification we want to send is "I know how to send push notifications!". We'll first create the payload JSON using the second method:

$payload = create_payload_json("I know how to send push notifications!");

Let's say the user has an iOS (This info can be kept on a server, database etc... for each user) and the array is as follows:

$user_mobile_info = ['user_device_type'=>"iOS", 'user_mobile_token'=>'1234ABCD'];

Now we can send the notification itself using the first method: 

send_mobile_notification_request($user_mobile_info, $payload);

They're many minor sections which have not been covered by this blog post. Feel free to leave me comments if you have any further questions.