How to get them working together
The following guide is how you can create a basic Telegram bot that will retrieve basic information from a smart contract on a Blockchain, and then serve the response directly into the Telegram group of your choice. Rather than hosting the code on a local server, we’ll host it (for FREE) on Netlify!
In case you didn’t already know, Netlify supports serverless AWS Lambda functions!
So what does this actually mean? It means that functions in your code don’t require an AWS account or any kind of API gateways. They can all be managed by Netlify!
Considering Netlify is free to get you started, it makes it an ideal solution to serve your websites and projects.
Let’s get started!
Step 1. Getting things in Place
You’ll need Telegram installed on your PC and a Telegram account! — https://desktop.telegram.org/
You’ll also need a Github account — https://github.com/
Finally, you’ll need a Netlify account — https://www.netlify.com/
Step 2. Getting a Token from the BotFather!
visit this link https://t.me/botfather and then click “send message”
Then type in /start to view the list of commands:
now type in /newbot so that we can create a new bot. It will respond with the following message:
give it a name — For example MyAmazingCryptoBot
It will respond with another message…
Follow the instructions, and give the bot a username — for example MyAmazingCryptoBot_bot
You’ll then receive your token in the response. It’s usually around 10 digits, followed by a colon, and then around 35 random characters
For example:
40284672037:hioef_RFtgjore434354o5354433kjGFgfr
You can click on the link to open a direct chat with your bot…
The bot is now created and ready for testing, and eventually inviting to a group, but if you want to “personalize” the bot, with for example a logo, you can do so by going back to the “botfather” chat window, and typing in /mybots where you’ll be prompted to click on your bot, which will then bring up a menu where you can select to “Edit Bot”
Here is my bot after adding a 150px X 150px photo (Note: must be compressed as photo when sending to BotFather, not an uncompressed file)
Step 3. Creating the necessary files for Github
Actually using Github is outside of the scope of this tutorial, as it will simply take too long, but there are plenty of tutorials on how you can do it, particularly if you want to push and pull “commits” to and from Github to your PC. For now, we’ll just stick with the basics.
Create a new Repo and call it something useful. I’ll call mine “MyAmazingCryptoBot” and create a README.md file that will come in useful for your own instructions when you come back to it.
Ok firstly, we want to create a netlify.toml file, and add the following code to the file:
[build]
functions = "functions"
command = "netlify-lambda install && mkdir ./public"
[[redirects]]
from = "/api/*"
to = "/.netlify/functions/:splat"
status = 200
?This file is use by Netlify to tell it that the functions are located in the “functions” directory. Netlify Lambda is what builds our function into a single file for delivery to AWS Lambda.
Next we’re going to create a package.json file to instruct Netlify what node packages are needed:
{
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {
"netlify-lambda": "^2.0.15",
"telegraf": "^4.11.2",
"web3": "^1.8.1"
}
}
We’ll also create a .gitignore file with the following:
node_modules
Now we’ll actually create the bot script file itself.
As per the documentation for serverless functions, we’ll store this in /functions/bot/ folder.
We’ll call the file bot.js and to check we have connectivity between Telegram and Netlify, we’ll create a very basic script that will respond with a basic message when you sent it the /start command.
Congrats! You’ve connected to Netlify!
const { Telegraf } = require("telegraf")
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start(ctx => {
console.log("Received /start command")
try {
ctx.reply("Congrats! You've connected to Netlify!")
} catch (e) {
console.error("error in start action:", e)
ctx.reply("Error occured")
}
})
exports.handler = async event => {
try {
await bot.handleUpdate(JSON.parse(event.body))
return { statusCode: 200, body: "" }
} catch (e) {
console.error("error in handler:", e)
return { statusCode: 400, body: "This endpoint is meant for bot and telegram communication" }
}
}
Note: in the code above, we will use the Telegraf object from the Telegraf node package, and we will also reference the Telegram token we generated earlier, which will be stored in, and pulled from Netlify
Once we’ve saved this file, your overall file structure should look like this in Github:
Step 4. Deploy the project to Netlify
Login to Netlify and go to “Add New Site” -> “Import an existing project”
Now connect to Github:
Once authorized, click on your Github repo that you created.
For your basic build settings, leave both the Basic directory, and the Publish Directory field blank (if there is anything in either of them, delete it)
The Build command should have auto-filled, but if it hasn’t the command in the field should be: netlify-lambda install && mkdir ./public
Now click on the “Show Advanced” button, so that we can add a new environment variable, with a key of BOT_TOKEN, and a value which is the Telegram token that you first retrieved from Botfather. In the example we used above it was:
40284672037:hioef_RFtgjore434354o5354433kjGFgfr
Also ensure “functions” is being displayed in the functions directory field, and then click “Deploy site”
At this point you should see that the site deployment is in progress:
If you click where it says “Site deploy in progress” it will open up the Deploy Log to show the progress of the install:
If all goes well, you’ll see the “Site is live message at the bottom of the Deploy Log after a minute or two…
you can now go back to the “Sites” section of netlify, where you’ll see details of your deployed site, and also the URL of the site you created. It will be some strange name that Netlify automatically assigns to it. You can actually assign your own domain name to your site if you want to, but for the purpose of this bot its not necessary.
As you can see in my case, it generated the following address:
https://venerable-alfajores-c6f46a.netlify.app
Step 5. Setting up a Web hook
The next thing to do is set up a web hook so that Telegram knows where to forward messages to when a user types them in.
The webhook is called in a browser, and needs to be set in the following format, which includes both the Telegram token and the new Netlify URL:
https://api.telegram.org/bot40284672037:hioef_RFtgjore434354o5354433kjGFgfr/setWebhook?url=https://venerable-alfajores-c6f46a.netlify.app/api/bot
It’s very important to note the “bot” in front of the actual Telegram token!!
If all went well, you’ll see the following response in the borwser:
{"ok":true,"result":true,"description":"Webhook was set"}
Step 6. Test connectivity from the Telegram bot to Netlify
Now that everything is setup, we should be able to test our bot. Head back to Telegram, and send the bot the message /start
If all goes well, and everything connected, you’ll see the following message back to you:
You’re now connected! The next steps are to expand upon what we want our bot.js functions (hosted on Netlify) to retrieve when we type in commands!
Step 7. Adding functionality to your bot
Now that the core connectivity is in place, and that your Github repository is being served to Netlify (which will automatically update whenever you make changes to your Github code) it’s a case of going back to Github and making some changes to your code to add in that extra functionality.
Here’s what the bot.js file has so far:
const { Telegraf } = require("telegraf")
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start(ctx => {
console.log("Received /start command")
try {
ctx.reply("Congrats! You've connected to Netlify!")
} catch (e) {
console.error("error in start action:", e)
ctx.reply("Error occured")
}
})
exports.handler = async event => {
try {
await bot.handleUpdate(JSON.parse(event.body))
return { statusCode: 200, body: "" }
} catch (e) {
console.error("error in handler:", e)
return { statusCode: 400, body: "This endpoint is meant for bot and telegram communication" }
}
}
So we’re making use of the Telegraf bot.start command at the moment (https://telegraf.js.org/) but that’s about all. Let’s add in a bot.command command function…
const { Telegraf } = require("telegraf")
const bot = new Telegraf(process.env.BOT_TOKEN)
bot.start(ctx => {
console.log("Received /start command")
try {
ctx.reply("Congrats! You've connected to Netlify!")
} catch (e) {
console.error("error in start action:", e)
ctx.reply("Error occured")
}
})
bot.command('thumbsup', async (ctx) => {
try {
ctx.reply('Here you go 👍!')
} catch (error) {
console.log('error', error)
ctx.reply('error sending image')
}
})
exports.handler = async event => {
try {
await bot.handleUpdate(JSON.parse(event.body))
return { statusCode: 200, body: "" }
} catch (e) {
console.error("error in handler:", e)
return { statusCode: 400, body: "This endpoint is meant for bot and telegram communication" }
}
}
If you hadn’t already guessed, it’s looking for a prompt in Telegram of /thumbsup and will return the response Here you go 👍!
So you can see from that last function we created, we are issuing a bot.command, then stating what command we’re expecting from Telegram (‘thumbsup’) and then stating what should be returned as the reply.
bot.command('thumbsup', async (ctx) => {
try {
ctx.reply('Here you go 👍!')
} catch (error) {
console.log('error', error)
ctx.reply('error sending image')
}
})
Now let’s try intruding some crypto information…