MAIS AMOR POR FAVOR

Gatsby Functions on Netlify: Telegram Contact Form Bot

Gatsby Cloud Functions reCAPTCHA

Gatsby Functions on Netlify: Telegram Contact Form Bot

SHARE:

✨ Introducing Gatsby Functions on Netlify

Gatsby Functions on Netlify: Gatsby Functions do not restrict you just to Gatsby Cloud, you can also use them on other services with support. Today we look at using them on Netlify. We previously looked at using Gatsby Cloud Functions to create an accessible contact form for your site. In that post we used email to notify you whenever a visitor leaves a new message. This time while seeing how to use Gatsby Functions on Netlify we will learn how to get a Telegram Bot to message you each time a site visitor uses your contact form.

Why use Telegram? The Telegram Bot API is a nice one to set up and use. Sending a Telegram message as well as an email has a few advantages. You can add whomever you want to the Telegram group to receive messages from your bot. This is great if you don't want to keep clients waiting while you are in meetings or travelling as it is easy for someone else in your team to pick up messages. You're not limited to using Telegram on your phone either you can set up the Desktop app to get customer messages as your work. As well as this, you won't miss messages if there's an issue with your email system. It's also just plain fun! If you're interested let's continue by setting up some Telegram API keys.

πŸ”‘ Telegram API Keys

Gatsby Functions on Netlify: Telegram Contact Form Bot: Telegram Bot API Key

The process is quite simple, just follow step by step and you will have API keys in a couple of minutes.

  1. Bots are created by Telegram's Bot Father β€” isn't that cute! Open up a new chat with @BotFather .

  2. You interact with bots in Telegram by typing commands which begin with a / in the chat window. Create a new bot using the command /newbot. Bot Father will ask you for a name and then a username. The name can be anything but the username needs to end bot and should only contain alphanumeric characters and underscores. I will use β€œGatsby Functions Netlify Site” as the name and gatsby_functions_netlify_bot as the username. Bot Father will respond with the new API key for your bot make a note of this.

  3. Next we need to create a new group chat and add the bot to it (you can also add anyone whom you want to receive bot messages). From the Telegram menu select New Group. Enter a name for the group when prompted then in the Add Members window type the username of your bot.

Retreive Chat ID

  1. We're almost done. Next we need to get the ID for this new group chat so we can send messages to it form the Gatsby Function. From the group send a message to the bot by typing the following command as a message β€œ/my_id @my_bot” replace my_bot with the name of your bot.

  2. In the terminal use curl to see the bot's updates. Remember to replace 123456789:AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQq with the API key you got earlier:

curl -L https://api.telegram.org/bot123456789:AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQq/getUpdates

If you don't have curl on your machine,just paste the link into your browser instead. If you are working on a shared machine, be sure to clear the link from the Browser history as it contains an API key.

You will get a response back something like this:

{
"ok": true,
"result": [
{
"update_id": 741497477,
"message": {
"message_id": 2,
"from": {
"id": 1234567890,
"is_bot": false,
"first_name": "Rodney",
"last_name": "Lab",
"username": "askRodney"
},
"chat": {
"id": -123456789,
"title": "Gatsby Functions Netlify",
"type": "group",
"all_members_are_administrators": true
},
"date": 1623667295,
"text": "/my_id @gatsby_functions_netlify_bot",
"entities": [
{ "offset": 0, "length": 6, "type": "bot_command" },
{ "offset": 7, "length": 29, "type": "mention" }
]
}
}
]
}

Ok this is just some JSON. It contains two ids, although we just need one. The first is the message ID. We don't need this one. The second, within the chat object, starts with a β€œ-”, this is the chat ID we need, including the β€œ-”.

We have all the API data we need to proceed. Let's carry on by setting up or function.

πŸ—³οΈ Poll

Will you use a Telegram Bot in a future Web App or site you build?
Voting reveals latest results.

βš™οΈ Add API Keys to Site

To save time, we will clone the final result repo from the post on Gatsby Cloud Functions. Start by cloning the repo and then preparing the site to run locally:

git clone https://github.com/rodneylab/gatsby-cloud-functions-recaptcha.git gatsby-functions-netlify
cd gatsby-functions-netlify
npm install
cp .env.EXAMPLE .env.development
cp .env.EXAMPLE .env.production
gatsby develop

That will spin up a dev server for you. Go to localhost:8000/contact in your browser and you will see the contact form is all set up.

The contact form uses an accessible reCAPTCHA to check the user is not a bot. When the user clicks the Submit your message button, the form data, together with a reCAPTCHA token is posted to the serverless function for processing.

For all of this to work, you will need to have a reCAPTCHA API key, if you don't already have one. This is really easy to set up and I included instructions on setting up a reCAPTCHA API keys in the earlier post. The function also sends you an email with message details whenever someone submits the form. As you probably guessed, I included setup instructions for this in the earlier post too! Update the .env.development and .env.production files with your own keys.

With all that set up we just need to add the new API keys for our Telegram bot. Edit .env.development and .env.production, replacing the placeholders with your own new credentials:

.env.development
plaintext
14SMTP_USER="smtp-server-username"
15TELEGRAM_BOT_API_TOKEN="123456789:AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQq"
16TELEGRAM_BOT_CHAT_ID="-123456789"

πŸ”§ Enable Gatsby Functions on Netlify

This step is pretty easy... one think I love about Netlify is how simple they make things! Two steps:

  1. Install @netlify/plugin-gatsby from the command line:

    npm i -D @netlify/plugin-gatsby
  2. Enable the Gatsby Functions Netlify plugin, updating netlify.toml:

netlify.toml
toml
10[[plugins]]
11 package = "@netlify/plugin-gatsby"

That's all there is to it. If you really need to know more, check out the Netlify docs .

☁️ Gatsby Function

There is a Telegram Node package , but we will use axios instead as it is already installed in our project. Gatsby functions are placed in the src/api folder. You will see in the contact form code (line 21 in src/components/ContactForm.jsx) we post the form data to the /api/submit-message endpoint. The corresponding function in our project is located at src/api/submit-message. Including an API endpoint is just as simple as creating a corresponding file with a matching name. Let's edit src/api/submit-message to add the Telegram bot function:

src/api/submit-message
jsx
import axios from 'axios';
import nodemailer from 'nodemailer';
const notifyViaTelegramBot = async ({
email,
googleCaptchaScore,
markedSpam,
message: userMessage,
name,
}) => {
const data = JSON.stringify(
{ email, googleCaptchaScore, markedSpam, userMessage, name },
null,
2,
);
const text = `Contact Form Message: ${data}`;
const result = (async () => {
try {
await axios({
url: `https://api.telegram.org/bot${process.env.TELEGRAM_BOT_API_TOKEN}/sendMessage`,
method: 'POST',
data: {
chat_id: process.env.TELEGRAM_BOT_CHAT_ID,
text,
},
});
return { successful: true, message: '' };
} catch (error) {
let message;
if (error.response) {
message = `Telegram server responded with non 2xx code: ${error.response.data}`;
} else if (error.request) {
message = `No Telegram response received: ${error.request}`;
} else {
message = `Error setting up telegram response: ${error.message}`;
}
return { successful: false, message };
}
})();
return result;
};

Finally, we need to call this function from the main handler. We'll modify the existing code a touch. We already await a promise from the sendEmail function. We will generate a new promise from our Telegram function, and do not need to wait for the first promise to resolve before starting work on the second. This sounds like a job for Promise.all . Let me know if this needs more explanation. Here's the code changes:

src/api/submit-message
jsx
if (!recaptchaValidationResult.successful) {
res.status(400).send(recaptchaValidationResult.message);
} else {
const googleCaptchaScore = recaptchaValidationResult.message;
const sendEmailPromise = sendEmail({
email,
googleCaptchaScore,
markedSpam,
message,
name,
});
const notifyViaTelegramBotPromise = notifyViaTelegramBot({
email,
googleCaptchaScore,
markedSpam,
message,
name,
});
const [sendEmailResult, notifyViaTelegramBotResult] = await Promise.all([
sendEmailPromise,
notifyViaTelegramBotPromise,
]);
if (!sendEmailResult.successful) {
res.status(400).send(sendEmailResult.message);
} else if (!notifyViaTelegramBotResult.successful) {
res.status(400).send(notifyViaTelegramBotResult.message);
} else {
res.status(200).send('All good!');
}
}
}
}

πŸ’― Check Your Work

Gatsby Functions on Netlify: Telegram Contact Form Bot: Telegram Bot API Key

That's it! Let's test by sending a message on the contact form and making sure we receive it in Telegram. When you are ready to deploy to a live server using Netlify, don't forget to add the environment variables to the Netlify dashboard.

You can see the full code for this project on the Rodney Lab GitHub page as well as other Rodney Lab projects.

πŸ™ŒπŸ½ How Much Fun Was That!?!

In this post we learned:

  • how to use Gatsby functions on Netlify,
  • create Telegram API tokens,
  • how to send a message from a Telegram Bot using a serverless function.

I hope you have found this valuable and worth the time you invested. Let me know if there is anything in the post that I can improve on, for any one else creating this project. You can leave a comment below, @ me on twitter or try one of the other contact methods listed below.

πŸ™πŸ½ Gatsby Functions on Netlify: Feedback

As I say, I hope you enjoyed following along and creating this project as well as learned something new. I also hope you will use this code in your own projects. I would love to hear what you are using Telegram bots for. Also fill me in on how you are using Gatsby functions on Netlify. Finally be sure to let me know ideas for other posts you would like to see. Read on to find ways to get in touch, further below. If you have found this post useful, even though you can only afford even a tiny contribution, please consider supporting me through Buy me a Coffee.

Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as Gatsby JS among other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.