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
- Installing Node
- Installing AWS CLI
- Installing Copilot Cli
- Installing Docker
- Setting up the project
- Creating the Bot
- Letâs code
- Testing the Code
- Configuring dockerfile
- Deploying to ECS with Copilot Cli
- Making some refactoring & updating
- The End
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
Sign in to the AWS Management Console and open the IAM console at here.
On the navigation pane, choose Users.
Choose the name of the user whose access keys you want to create, and then choose the Security credentials tab.
In the Access keys section, choose Create access key.
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/bPxRfiCYEXAMPLEKEYTo 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.
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.
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.
- AWS Access Key ID [None]:Â AKIAI44QH8DHBEXAMPLEÂ
- AWS Secret Access Key [None]:Â je7MtGbClwBF/EXAMPLEKEYÂ
- Default region name [None]:Â us-east-1Â
- 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.
- Find the installed files and delete them, copilot.exe, copilot.asc, and ecs-cli.asc.
- 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
- Type Win + R and write this rundll32.exe sysdm.cpl,EditEnvironmentVariables, it will open your environment variables panel.
- 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.
- 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:
Install Windows 10, version 1903 or higher, or Windows 11.
Enable WSL 2 feature on Windows. For detailed instructions, refer to the Microsoft documentation.
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 âď¸
- Open your Telegram app and search for the BotFather and start the bot.
- Write the command /newbot and give it a name, mine will be crypto-bot and username crptobot
- 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();
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", Â
},
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"]
Also, create a file with the name .dockerignore and add this:
copilot
node_modules
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.
- Write the command copilot init.
- Name de app, I'll use crypto-bot-app.
- We choose the workload, in my case Backend Service.
- Name backend service as bot-main-service.
- 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');
}
},
};
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();
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...
Top comments (0)