Telegramis one of the most popular messaging apps and probably the most loved by developers. By championing privacy in a time where it seems increasingly elusive, Telegram has seen its popularity soar - crossing the 500 million monthly active users mark in the first quarter of 2021. This makes it a viable notification medium for web applications - seeing as it is also available on the app store for android and iOS devices. Additionally, being open source and providing a developer-friendly API, integrating a Telegram-based messaging feature on your application is relatively easier than other popular messaging applications.
In this guide, I will show you how to integrate Telegram messaging into your React application. Using Sanity to provide movie content, we will use Telegram to send ourselves movie information- for further research and possibly an outing to the cinema ?. The app we will build (and its messaging functionality) is shown in the gif below.
To keep up with the concepts that will be introduced in this article, you will need a fair grasp of Javascript ES6. You will also need to have an understanding of some basic React concepts like hooks and functional components.
Surprise surprise, there's a bot for creating and managing Telegram bots. His name is the botfather. To create a Telegram bot, send /newbot to the botfather. The next thing to do is select a bot name (which has to be unique) and you will receive an API token.
With your API token, you can track updates (i.e. activity related to your bot) including when messages are sent to your bot. To do this, visit the URL [TOKEN]/getUpdates where TOKEN is the token given to you by the botfather.
Telegram has a different system for identifying users - deviating from phone numbers or email addresses as a unique identifier. To send messages to a user, we need the user id. The simplest way to get our chat id is by starting a conversation with our bot and checking for the chat id in the getUpdates URL. To start a conversation with your bot, visit the URL [BOT_USERNAME]/start where BOT_USERNAME refers to the username for your Telegram bot. You will be directed to the Telegram app where you will see something similar to the screenshot below.
It doesn't stop there, however. While this is extracurricular in the context of this article, it is also possible to get our user id or that of others via Telegram's deep linking mechanism. By adding a start query parameter to your bot URL ( [BOT_USERNAME]), you can identify users on your system and get their Telegram user ID. This can be done via the following steps:
Sending a notification is as simple as sending a GET request to [TOKEN]/sendMessage with chat_id and text as the query parameters. Remember, TOKEN is the token given to you by the botfather. Optionally, you can also include a third query parameter, parse_mode that allows you to send HTML or Markdown content to the recipient.
To see this in action, open the URL [TOKEN]/sendMessage?chat_id=[USER_ID]&text=Hello%20from%20your%20new%20bot in your browser where token is the token given to you by the botfather and USER_ID is the id of the message sender you copied earlier. You will see a response similar to the screenshot below.
Having understood the process of setting up a telegram bot and sending a notification via Telegram, let's see how we can use this in an application. Let's build an application to display the latest movies, along with actors and upcoming screenings. We'll use Next.js for this tutorial. Next.js is a framework built on React.js which provides several extra features, including server-side rendering and generating static websites. Create a new project using the following command.
For styling our pages, we'll use Chakra UI, a simple, modular, and accessible component library that gives you the building blocks you need to build your React applications. Add Chakra and its dependencies using the following command.
While we're developing, we'll need the sanity CLI installed. Additionally, we need to run our next application and sanity studio simultaneously. We can do that using the concurrently package. Install both of them using the command below.
Before we build the pages of our application, let's write some utility functions that will help us with tasks like making requests to Sanity, formatting data, or making API requests. Create a new folder at the root of your project named utility.
Here, we declare a function named makePostRequest which takes the endpoint URL and the values of the POST request and uses Fetch to send a POST request accordingly. The function returns a promise which resolves to the JSON content of the API response.
Next, create a new file called telegram.js in the utility directory. This file will contain a helper function that will help us to interact with the Telegram Bot API easily. In this file add the following code.
The sendNotification function takes the text of the notification and the mode which Telegram should use in parsing it. For this guide, we will use HTML formatted text. You can read more about formatting options for Telegram messages here.
Next, create a new file called objectFormat.js in the utility directory. This file will contain a helper function that we can use to generate the appropriate HTML formatted text for Telegram requests based on the provided object. In this file, add the following code.
The toHtmlFormat function takes the title (the content of the first line of the formatted text) and the body (which is an object). It maps through the object, capitalises the object keys, and then returns the key formatted as a title and the value of the object underneath.
If the value of a key is an array, the formatArray function is used to iterate through each member of the array and format each child. This function is naive in the sense that it assumes that the array provided is comprised only of strings.
Next, create a new file called dateFormat.js in the utility directory. This file will contain a helper function that will allow us to present dates in a human-readable format. In it add the following code.
Finally, we need helper functions to ease the interaction with our Sanity backend as well as provide assistance with Sanity image resources and portable text serialisation. Create a new file called sanity.js in the utility directory. In it, add the following code.
In the components directory, create a new file called MovieCard.js. When we display the movies in a grid, each movie will be rendered with the MovieCard component. In the components/MovieCard.js file, add the following.
This component destructures the movie which it receives as a prop and renders the movie poster (using the urlFor helper function we created earlier), the title, and the release date (formatted using the formatDate helper function we created earlier).
In the components directory, create a new file called MoviePage.js and add the following code to it. This should not be confused with the MoviesPage.js component we built earlier. This component is rendered when a movie card is clicked. It takes a movie as a prop and renders the movie details. It also adds a button which when clicked, shares the movie details via Telegram.
In the MoviePage component, we make a request to api/share to send the movie details, let's create a handler for this endpoint. We can do this in our current project as Next.js provides a solution for us to build APIs with it.
This route only accepts POST requests. When such a request is received, we retrieve the text and parse mode from the request, and using the sendNotification helper function we declared earlier, we send the details to our Telegram bot and eventually us!!
The last thing to do is build the pages for the application. The application will have two pages - the index page which shows all the movies and the movie page which displays the information for a single movie.
Next in the pages directory, create a new folder called movies. In the movies folder, create a new file called [slug].js. By taking advantage of Next.JS's file-based router system, this folder and file naming structure will allow us requests to the URL /movies/slug where slug corresponds to the slug of the selected movie. Add the following code to pages/movies/[slug].js.
In this guide, we saw how telegram can be integrated into a react app, walking through the process of creating a bot to sending a message to a telegram user via the Telegram Bot API. We also saw how to connect our application to Sanity studio for content management.
Sending notifications is just a tip of what developers can take advantage of. Telegram also offers tdlib (Telegram Database Library), a cross-platform, fully functional Telegram client which allows anyone to build their own custom messaging apps operating in the Telegram cloud.
The Voyager Golden Records are two identical phonograph records which were included aboard the two Voyager spacecraft launched in 1977.[1] The records contain sounds and images selected to portray the diversity of life and culture on Earth, and are intended for any intelligent extraterrestrial life form who may find them. The records are a time capsule.
Although neither Voyager spacecraft is heading toward any particular star, Voyager 1 will pass within 1.6 light-years' distance of the star Gliese 445, currently in the constellation Camelopardalis, in about 40,000 years.[2]
Carl Sagan noted that "The spacecraft will be encountered and the record played only if there are advanced space-faring civilizations in interstellar space, but the launching of this 'bottle' into the cosmic 'ocean' says something very hopeful about life on this planet."[3]
This is a present from a small, distant world, a token of our sounds, our science, our images, our music, our thoughts and our feelings. We are attempting to survive our time so we may live into yours.
The contents of the record were selected for NASA by a committee chaired by Carl Sagan of Cornell University. The selection of content for the record took almost a year. Sagan and his associates assembled 116 images (one used for calibration) and a variety of natural sounds, such as those made by surf, wind, thunder and animals (including the songs of birds and whales). To this they added audio content to represent humanity: spoken greetings in 55 ancient and modern languages, including a spoken greeting in English by U.N. Secretary-General Kurt Waldheim and a greeting by Sagan's six-year-old son, Nick; other human sounds, like footsteps and laughter (Sagan's);[1] the inspirational message Per aspera ad astra in Morse code; and musical selections from different cultures and eras. The record also includes a printed message from U.S. president Jimmy Carter.[5]
3a8082e126