DEV Community

Christian Prado Ciokler
Christian Prado Ciokler

Posted on

Deploying a Telegram Bot to AWS ECS with AWS Copilot. [Step by step] for absolut beginners.

The purpose of this project is to share my experience and hope to be of help to someone. Copilot is a young tool for creating and deploying containerized services without handling all the configuration troubles of ECS, EC2, and Fargate. Maybe there is a better way to deploy this kind of project out there but please humor me, we are having fun and trying new things.

🙏 Hope you like 👍 this post and let's get down to business. 🚀

Table of content


The Stack ☝️

For this project we are going to use the following tools, don’t worry if you don’t know how to use them I’ll leave you the documentation links down below. Anyhow, I would guide you step by step all the way.

OS: Windows -should work on others OS as well-
Node docs installation
AWS CLI v2 docs installation
Copilot Cli docs installation
Docker docs installation
Telegraf docs installation
Binance API docs
Axios docs


Installing Node ☝️

First, we install node, there is not much to say about it just follow this link here to download Node and the installer will guide you through the process. At the moment this post is been created we are using version 16.11.0.


Installing AWS CLI ☝️

First, we need to have an AWS account, so if you don’t have one get down to it.

Once you have the account created we install AWS CLI v2 and check if it is working with the command aws help

With everything in order, the next step is to configure AWS credentials. So we need to create access keys for an IAM user

  1. Sign in to the AWS Management Console and open the IAM console at here.

  2. On the navigation pane, choose Users.

  3. Choose the name of the user whose access keys you want to create, and then choose the Security credentials tab.

  4. In the Access keys section, choose Create access key.

  5. To view the new access key pair, choose Show. You will not have access to the secret access key again after this dialog box closes. Your credentials will look something like this:
    Access key ID: AKIAIOSFODNN7EXAMPLE
    Secret access key: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY

  6. To download the key pair, choose Download .csv file. Store the keys in a secure location. You will not have access to the secret access key again after this dialog box closes.

  7. Keep the keys confidential to protect your AWS account and never email them. Do not share them outside your organization, even if an inquiry appears to come from AWS or Amazon.com. No one who legitimately represents Amazon will ever ask you for your secret key.

  8. After you download the .csv file, choose Close. When you create an access key, the key pair is active by default, and you can use the pair right away.

To add the credentials to AWS CLI we write the command aws configure --profile myprofilename in the terminal and follow the steps.

  1. AWS Access Key ID [None]: AKIAI44QH8DHBEXAMPLE 
  2. AWS Secret Access Key [None]: je7MtGbClwBF/EXAMPLEKEY 
  3. Default region name [None]: us-east-1 
  4. Default output format [None]: json

That’s it, know you have successfully set up AWS CLI !!!!


Installing Copilot Cli ☝️

The instructions for the installation are here, once you are done write copilot --help in your terminal if everything works as it supposes to,!Congratulations, your pc is smarter than mine, if you had an error don’t worry I had the same problem. Here is how you can fix it.

Remember this solution I only tested on Windows OS.

  1. Find the installed files and delete them, copilot.exe, copilot.asc, and ecs-cli.asc.
  2. Install them again using the terminal as administrator but in this folder.

Invoke-WebRequest -OutFile 'C:\Program Files\Amazon\Copilot\copilot.exe' https://github.com/aws/copilot-cli/releases/latest/download/copilot-windows.exe

Invoke-WebRequest -OutFile 'C:\Program Files\Amazon\Copilot\copilot.asc' https://github.com/aws/copilot-cli/releases/latest/download/copilot-windows.exe.asc

Invoke-WebRequest -OutFile 'C:\Program Files\Amazon\Copilot\ecs-cli.asc' https://github.com/aws/copilot-cli/releases/latest/download/copilot-windows.exe

  1. Type Win + R and write this rundll32.exe sysdm.cpl,EditEnvironmentVariables, it will open your environment variables panel.
  2. Go to system variables, select path and click edit, add a new path C:\Program Files\Amazon\Copilot or the path where the copilot.exe file is.
  3. Save the changes and restart.

Write the command copilot --help in your terminal and it should work.


Installing Docker ☝️

Download docker here and follow the instructions.

Before you install the Docker Desktop WSL 2 backend, you must complete the following steps:

  1. Install Windows 10, version 1903 or higher, or Windows 11.

  2. Enable WSL 2 feature on Windows. For detailed instructions, refer to the Microsoft documentation.

  3. Download and install the Linux kernel update package.


Setting up the project ☝️

Create a folder a give it a name of your choice, mine will be crypto-bot-app, open your folder on your IDE and write npm init -y

Now we add the packages. Write on the terminal npm i telegraf axios
All set!!!


Creating the bot ☝️

  1. Open your Telegram app and search for the BotFather and start the bot.
  2. Write the command /newbot and give it a name, mine will be crypto-bot and username crptobot
  3. You should receive a token like this 2098237194:AAH9QoFokuBOn0IqES0IGJdJ_AR-tySMOX4, save it for later.

You created your first bot !!congratulation!!, now let add some code to it.


Let’s code ☝️

Create an index.js file on the project folder where we are going to put this code.

const {Telegraf} = require('telegraf');
const axios = require('axios');

const bot = new Telegraf('2098237194:AAH9QoFokuBOn0IqES0IGJdJ_AR-tySMOX4');//your token

// START-----------------------------------------------
bot.start(async (ctx) => {
  await ctx.reply(`Hi ${ctx.from.first_name}`);
  await ctx.reply(`I still under development but you can use me to get the latest price of a cryptocurrency`);
  await ctx.reply(`For example to know the price of an specific crypto write the command /price and the symbol of the cryptocurrency`);
  await ctx.reply(`/price btc`);
});

// COMMANDS===============================================================
bot.command(['price', 'Price', 'PRICE'], (ctx)=> {
    try {
        const ticker = ctx.message.text.toLowerCase().split('/price ')[1].toUpperCase();
        const {data} = await axios.get(`https://api.binance.com/api/v3/ticker/price?symbol=${ticker}USDT`);
        ctx.reply(ticker+': '+data.price+' USDT');
      } catch (error) {
        ctx.reply('Some error occurred in your request, please try again');
      }
});

bot.launch();
Enter fullscreen mode Exit fullscreen mode

Testing the code ☝️

Before initiating, the code let's add the following piece of code to our package.json

 "scripts": {
    "start": "node index.js", //here
    "test": "test",  
},
Enter fullscreen mode Exit fullscreen mode

Now run the command npm start, go to telegram, open your bot and type /start or /price btc 

Once you receive the expected response we may continue this journey.


Configuring dockerfile ☝️

Create a file in your project directory and name it Dockerfile, add this configuration code

FROM node:16.9.1

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 80

CMD ["npm","start"]
Enter fullscreen mode Exit fullscreen mode

Also, create a file with the name .dockerignore and add this:

copilot
node_modules
Enter fullscreen mode Exit fullscreen mode

Deploying to ECS with Copilot Cli ☝️

Now that we have the dockerfile configured correctly, we are going to deploy the bot to ECS to work 24/7.

  1. Write the command copilot init.
  2. Name de app, I'll use crypto-bot-app.
  3. We choose the workload, in my case Backend Service.
  4. Name backend service as bot-main-service.
  5. Deploy the app with the command copilot app deploy.

Making some refactoring ☝️

At this point, we can make some refactoring to optimize our code. First, we are going to create a folder "src" with a javascript file named "bot-functions.js" and add this code.

bot-functions.js

const axios = require('axios');

module.exports = functions = {
  start_message: async (ctx) => {
    await ctx.reply(`Hi ${ctx.from.first_name}`);
      await ctx.reply(`I still under development but you can use me to get the latest price of a cryptocurrency`);
      await ctx.reply(`For example to know the price of an specific crypto write the command /price and the symbol of the cryptocurrency`);
      await ctx.reply(`/price btc`);
  },
  getCryptocurrencyPrice: async (ctx) => {
    try {
      const ticker = ctx.message.text.toLowerCase().split('/price ')[1].toUpperCase();
      const {data} = await axios.get(`https://api.binance.com/api/v3/ticker/price?symbol=${ticker}USDT`);
      ctx.reply(ticker+': '+data.price+' USDT');
    } catch (error) {
      ctx.reply('Some error occurred in your request, please try again');
    }
  },
};

Enter fullscreen mode Exit fullscreen mode

then go to index.js and make some changes to it.

index.js

const {Telegraf} = require('telegraf');
const functions = require('./src/bot-functions.js');

const bot = new Telegraf('2098237194:AAH9QoFokuBOn0IqES0IGJdJ_AR-tySMOX4');//your token

bot.start((ctx) => functions.start_message(ctx));

bot.command(['price', 'Price', 'PRICE'], (ctx)=> functions.getCryptocurrencyPrice(ctx));

bot.launch();

Enter fullscreen mode Exit fullscreen mode

Now we test that everything is working correctly, we add the changes with the command copilot app deploy.


The End ☝️

Keep in mind that this is a dev project for educational purposes, in the real world you should storage tokens and important information on environment variables, and all the good practices that the job demands. If you like it, give a thumbs-up 👍 and share it.

to the next post...

Discussion (0)