How to Create a Telegram Bot and Use Its API

How to Create a Telegram Bot and Use Its API

How to Create a Telegram Bot and Use Its API
3 min read

A. Creating a Telegram Bot

  1. Open BotFather

    • Search for "BotFather" on Telegram and start a chat.

    • Use the /newbot command to create a new bot.

  2. Configure the Bot

    • Provide a name and username for your bot.

    • Once completed, BotFather will provide an API token to interact with Telegram's API.

  3. Save the API Token

    • Keep this token secure, as it will be used in the next steps.


B. Using the Telegram API

Telegram provides an HTTP-based API that allows you to control your bot easily.

a. Sending Requests to the Telegram API Using ReactJS and Axios

Use your API token to access Telegram's endpoints. Here’s an example of sending a message using ReactJS with Axios:

import React, { useState } from "react";
import axios from "axios";

const TelegramBot = () => {
  const [message, setMessage] = useState("");
  const TOKEN = "YOUR_BOT_TOKEN";
  const CHAT_ID = "YOUR_CHAT_ID";
  const URL = `https://api.telegram.org/bot${TOKEN}/sendMessage`;

  const sendMessage = async () => {
    try {
      await axios.post(URL, {
        chat_id: CHAT_ID,
        text: message,
      });
      alert("Message sent!");
    } catch (error) {
      console.error("Error sending message", error);
    }
  };

  return (
    <div>
      <input
        type="text"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
        placeholder="Enter message"
      />
      <button onClick={sendMessage}>Send Message</button>
    </div>
  );
};

export default TelegramBot;

Conclusion

Creating a Telegram bot is simple with BotFather and Telegram’s API. You can develop bots for customer service, automated notifications, or chatbots.

Recommended for you