Telegram Message On Form Submissions

April 8, 2018

Today i am gonna show you how you can build a Telegram bot that will notify you when a form is submitted on your site using golang and Netlify Functions.

If you wanna jump right into the code here is the Github repo.

Before we begin make sure you have the following

  1. Golang
  2. Git
  3. Github, Gitlab or Bitbucket account
  4. Netlify Account

Here is what we’re gonna do

  1. Setup a simple static site
  2. Create a telegram bot and a channel
  3. Add our bot as admin to our channel
  4. Create your netlify site
  5. Write the backend for the bot using golang
  6. Configure a simple build system
  7. Deploy to netlify

1. Setup simple static site

First we create a simple html file to serve as the index of our site and contain our simple form

site/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Telegram Form Notfication</title>
    <style>

        * {
            margin: 0;
            padding: 0;
            outline: none;
            border: none;
        }

        body, html {
            height: 100%;
        }

        body {
            display: flex;
            align-items: center;
            justify-content: center;
        }

        form {
            box-shadow: 0 0 2px 4px rgba(0, 0, 0, .2);
            padding: 10px 0;
            text-align: center;
        }

        input, textarea {
            height: 40px;
            width: 310px;
            border-radius: 2px;
            margin: 10px;
            display: block;
            border-bottom: 1px solid grey;
        }

        textarea {
            resize: none;
            height: 80px;
        }

        button {
            background: #404040;
            padding: 10px;
            width: 310px;
            color: white;
        }

        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    
    <form id="form" method="POST" action="/.netlify/functions/contact">
        <input type="text" name="honeypot" class="hidden" placeholder="If you're a human being don't fill this field">
        <input type="text" name="name" placeholder="Name..." required>
        <input type="email" name="email" placeholder="Email..." required>
        <textarea name="message" placeholder="Message..."></textarea>
        <button id="send" type="submit">SEND</button>
    </form>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script>
        
        var form = $("#form");

        var send = $("#send");

        form.on("submit", function(e) {

            e.preventDefault();

            send.text("Sending...");

            $.ajax({
                url: "/",
                method: "POST",
                data: form.serialize(),
                complete: function() {
                    send.text("Send");
                }
            });

        });

    </script>
</body>
</html>

Now that we have our bare bones site, commit and push your code to your git repo

2. Create Telegram Bot And Channel

  1. Create your telegram bot and obtain it’s token, checkout the Telegram Docs if you need a refresher on how to create Telegram Bots.
  2. Create your telegram channel.

note: your channel can be either private or public, but if you choose to make your telegram channel private you need to obtain your chat id. you can check out this stackoverflow question if you would like to know how.

3. Add Our Bot As Admin To Our Channel

After you have created your bot and channel, you need to add your bot as administrator to your channel so it can broadcast messages on the channel. you can check out this stackoverflow question if you would like to know how.

4. Create netlify site

Since it’s a potential security issue to commit authentication tokens, passwords… to a git repo we will be injecting sensitive material into our code at build time.

  1. Create a new Netlify site from your git repo
  2. Go to Your Netlify Site > Settings > Build & Deploy > Build Environment Variables
  3. Add the following environment variables
    • TELEGRAM_BOT_TOKEN
    • TELEGRAM_CHANNEL_ID

5. Write Bot Backend In Go

It’s beyond the scope of this article to teach you go so check the go tour if you need a refresher

main.go

package main

import (
	"encoding/json"
	"fmt"
	"log"
	"net/http"

	"github.com/aws/aws-lambda-go/lambda"

	"github.com/aws/aws-lambda-go/events"
)

var (
	TELEGRAM_BOT_TOKEN string
	TELEGRAM_CHAT_ID   string
)

func handler(request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {

	var data url.Values

	var err error

	if data, err = url.ParseQuery(request.Body); err != nil {

		return events.APIGatewayProxyResponse{
			StatusCode: 503,
		}, nil

	}

	if data.Get("honeypot") != "" {

		return events.APIGatewayProxyResponse{
			StatusCode: 403,
		}, nil

	}

	text := fmt.Sprintf("<b>%s</b><pre>\n</pre><b>%s</b><pre>\n</pre><pre>%s</pre>", data.Get("name"), data.Get("email"), data.Get("message"))

	if req, err := http.NewRequest("GET", fmt.Sprintf("https://api.telegram.org/bot%s/sendMessage", TELEGRAM_BOT_TOKEN), nil); err != nil {

		log.Println(err)

		return events.APIGatewayProxyResponse{
			StatusCode: 503,
		}, nil

	} else {

		q := req.URL.Query()

		q.Add("text", text)

		q.Add("chat_id", TELEGRAM_CHAT_ID)

		q.Add("parse_mode", "html")

		req.URL.RawQuery = q.Encode()

		client := http.Client{}

		if _, err := client.Do(req); err != nil {

			log.Println(err)

			return events.APIGatewayProxyResponse{
				StatusCode: 503,
			}, nil

		}

	}

	return events.APIGatewayProxyResponse{
		StatusCode: 204,
	}, nil

}

func main() {
	lambda.Start(handler)
}

6. Configure a simple build system

Then we configure our build system and environment settings

netlify.toml

[build]
  command = "make build"
  functions = "functions"
  publish = "site"
[build.environment]
  # Change this with the path to your repository
  GO_IMPORT_PATH = "github.com/zolamk/telegram-form-notification-bot"

Here we have a simple Netlify configuration file that specifies build command, functions location, publish location and go import path.

Makefile

build:
	mkdir -p functions
	go get ./...
	go build -ldflags "-X main.TELEGRAM_BOT_TOKEN=${TELEGRAM_BOT_TOKEN} -X main.TELEGRAM_CHANNEL_ID=${TELEGRAM_CHANNEL_ID}" -o functions/contact ./...

Then we create a Makefile for our build command the only thing special about our make file is on line 4 we use linker flags to set variables defined in our code at build time.

8. Deploy to netlify

  • Commit and push to your git

And that is how you can get a Telegram message on form submissions.

That’s All Folks