DEV Community

Tanishq Sharma
Tanishq Sharma

Posted on • Edited on

How I made a Telegram Bot to report Gumroad Sales in less than 30 mins!

Hey everyone πŸ‘‹ Weekend is here and you guys must be looking for a new side-project to start and shortly ditch? I get you! But what if you could finish it in 30 mins. Wouldn't that be lovely?

Well, you have come to the right place. A couple of days ago, my company launched a Gumroad product in a niche category and we kept a target of '5000' number of sales. We decided that each day each morning, we would send a message saying something like this:

Day 2: 0/5000 sold

We realised it would keep us motivated to keep pushing every day.

It went good for a couple of days, then we realised – doing it manually every day wasn't realistic at all. We did forget it for a couple of days. So then I did what I normally do, I went onto find solutions to automate this completely.

I ended up making a Telegram Bot using the Gumroad API within 30 mins, then spent the next 90 mins polishing the way it worked, the messages it contains and much more.

But fret not! Since I have done the hard work, you can finish this work in less than 15 mins.

So buckle up to make your own Telegram Bot to report sales at your own chosen frequency.

This tutorial assumes you know

  • a little bit of NodeJS
  • Express and
  • you have a Gumroad Account with a product live on it.
  • You have a Heroku account (if not, we can create it.)

If all the boxes above tick for you, let us begin with it.

Part 1 - Create Express App

Open terminal, start by creating a directory using mkdir gumroad-telegram-bot followed by command cd gumroad-telegram-bot && npm init. This takes you in the directory and initiates npm config. Once you followed through the default configuration by pressing Enter Key in all the options. Open the folder in your favourite Code Editor.

Once you have opened your project folder in your code editor, we need to install some packages, so follow up with me.

In the integrated code-terminal, type the following command

npm install express body-parser cors dayjs dotenv node-fetch nodemon telegraf
Enter fullscreen mode Exit fullscreen mode

This is what the above packages will do:

  • Express - A Framework to create a NodeJS web application
  • body-parser - It is used as a middleware
  • cors - It is used for cross-origin requests
  • dayjs - A minimalist momentjs-alternative library to manipulate time
  • dotenv - Used to store and access environment variables
  • node-fetch - Used to create fetch request, you can use any alternative if you want, such as axios
  • nodemon - Used in Dev Environment to restart the server whenever there is a change
  • telegraf - A telegram client to access its apis

Once all the packages are installed, create a file called index.js & .env in root with the following code. I have written comments in the code to explain them.

Index.js

/*
 * Import All The Packages We Installed
 */
const express = require('express');
const fetch = require('node-fetch');
const cors = require('cors');
const bodyParser = require('body-parser');
var dayjs = require('dayjs');
const { Telegram } = require('telegraf');

/*
 * Requiring ENV file for variables
 */
require('dotenv').config();

/**
 * Get the mandatory keys to access various platforms
 */
const tg = new Telegram(process.env.BOTID);
const API_KEY = process.env.API_KEY;
const SENDERID = process.env.GROUPID;

/** Initiating the express app */
const app = express();

/*
 * Configure your express application to use body-parser
 */
app.use(bodyParser.json());
app.use(
  bodyParser.urlencoded({
    extended: true,
  })
);

/** Configure your express application to use CORS  */
app.use(cors());

/*
 * This function uses the / method API to get the stats
 */
async function getProducts() {
  const products = await fetch(`https://api.gumroad.com/v2/products`, {
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    method: 'GET',
  });
  return await products.json();
}

/**
 * These constants are completely made up and 
 * for me to use it in my text! You can change
 * it to anything you like, to compose
 * any message you want.
 */

const started = new Date(2019, 11, 10);
var startedOn = dayjs(started);
const today = dayjs();
const daysSince = startedOn.diff(today, 'day') + 365;

/**
* The products object which is received as a response from Gumroad API contains various fields. In this tutorial, we have chosen the first product (products[0]) and its sales_count property to display! You can explore the products array to display a whole lot more :)
*/

app.get('/', (req, res) => {
  getProducts().then((products) => {
    const txt = 'Day ' + daysSince * -1 + ': ' + (products.products[0].sales_count) + '/' + 5000; /** Composing the text from above constants */
    tg.sendMessage(SENDERID, txt); /** Sending the composed text using telegraf client */
    /** Once everything is done, send the response to end the api wait */
      res.send({
      sales: products.products[0].sales_count - 1,
      target: 5000,
      startedOn,
      today,
      daysSince: daysSince * -1,
    });
  });
});

/**
 * Checks if the port is available as a environment variable, if not, allots 3000 
 */
const port = process.env.PORT || 3000;

app.listen(port, () => {
  console.log(`App Is Running On http://localhost:${port}`);
});


Enter fullscreen mode Exit fullscreen mode

and this is what your .env file looks like

API_KEY=''
BOTID=''
GROUPID=''
Enter fullscreen mode Exit fullscreen mode

Now, all that's left is to fill these three items with their proper API Keys.

Part 2 - Generate Gumroad Access Token

Now, since you have made it to this point. Let me assure you, it takes less than 5 mins from here.

  • Go to Advanced Tab in your Gumroad Profile

Gumroad Profile

  • Create an application
    Application

  • Click On Generate Access Token
    Generate Token

  • Copy the Application Secret Generated
    Secret

Paste the application secret in .env file and you are done with 1/3 items you need.

API_KEY='XXXXXXXXXXXX'
BOTID=''
GROUPID=''
Enter fullscreen mode Exit fullscreen mode

Onto the next one πŸš€

Part 3 - Create A Telegram Bot

This is the fun part! And it involves no-coding. Thanks to excellent Bot-Father bot on Telegram.

Let's go:

  • Go to telegram and search for BotFather
  • Start the bot using the command /start
  • Use the command /newbot
  • Enter the Name for your bot, it can be anything you like
  • Enter the Username for your bot, it has to be unique and should end with ...bot like GumroadBot, TelegramBot etc
  • Once the bot is successfully created, it will give you an API KEY.

TelegramBotMaking

Copy the Token and paste it in .env file.

API_KEY='XXXXXXXXXXXX'
BOTID='YYYYYYYYYYYYY'
GROUPID=''
Enter fullscreen mode Exit fullscreen mode

and now the last parameter step πŸ₯³

Part 4 - Get The Group ID / Sender ID you want to send the messages too

Now, in this tutorial, we will use a GROUPID to make sure our bot sends messages in a group.

To do this, follow these steps

  • Create a group with your co-worker / team etc
  • Go to this url [https://api.telegram.org/YYYYYYYYYYYYY] - Make sure you replace YYYYYY with your bot id which you copied in last step.
  • You will see a JSON tree, in which you will have your GROUP object containing your GROUP ID, Group Name etc.

GroupIDChat

Copy the group ID and add it to your .env file.

API_KEY='XXXXXXXXXXXX'
BOTID='YYYYYYYYYYYYY'
GROUPID='ZZZZZZZZZZZ'
Enter fullscreen mode Exit fullscreen mode

We are done with collecting stuff! πŸ˜…

Now, Go to your package.json and set it up like this

{
  "name": "gumroad-telegram-bot",
  "version": "1.0.0",
  "description": "for accessing sales and sending to telegram",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "dev": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.19.0",
    "cors": "^2.8.5",
    "dayjs": "^1.9.7",
    "dotenv": "^8.2.0",
    "express": "^4.17.1",
    "moment": "^2.29.1",
    "node-fetch": "^2.6.1",
    "nodemon": "^2.0.6",
    "telegraf": "^3.38.0"
  }
}
Enter fullscreen mode Exit fullscreen mode

You can test your bot by running the command npm run dev on the integrated terminal and going to the path 'https://localhost:3000/'. It should automatically send a message to your Group!

AutomaticMessage

Now, let's automate it.

Part 5 - Host it on Heroku

  • This is a fairly simple process, so I am not going to cover in this to make sure this tutorial doesn't get too long.

How I did it is as follows:

  • Create a private repository on Github and push the code
  • Open Heroku account and use Deploy Via GitHub
  • Once you import the repository it should automatically give you a Heroku app URL for your deployed app.
  • Every time you visit on that URL, it will send a message to the group.

For more read, use this Deploy Express To Heroku

Pretty fancy! Right?

Part 6 - Setup Up Automated Message Frequency

This is easy-peasy! We will use CRON Jobs to send automated pings to your Heroku URL.

  • Visit EasyCRON
  • Create an account if not!
  • Click on Create New CRON JOB
  • Enter your Heroku URL
  • Choose Interval from Dropdown
  • and FINALLY click on 'Create CRON JOB'.

CronJob

Your work is done πŸ’ͺ πŸŽ‰

Part 7 - Follow Tanishq

I hope you had fun creating the Side Project that you actually shipped 🀭

Connect with me on Twitter - Tanishq - @tanishqxyz where I keep posting about building, selling and meta physics!

You have officially created a Bot that runs on intervals selected by you and reports the Gumroad Sales of your product. You create multiple bots using this for multiple aspects. You can create reminders, sales notification and a lot more!

πŸŽ‰

Top comments (1)

Collapse
 
brdlysmth profile image
bradley smith

nicely done