メインコンテンツにスキップ

GAS-Telegram-bot

A base code that shows how to make a telegram bot on google app script

AI Summary

GAS Telegram Bot Base Code

Provides boilerplate code for quickly building and deploying a Telegram bot on Google Apps Script.

Target Users

Beginner- to intermediate-level GAS developers who want to publish a Telegram bot for internal tools or personal projects without managing servers.

Problems Solved

Handling the Telegram Bot API in GAS requires boilerplate for webhooks, API calls, and error handling, which is time-consuming to build from scratch.

Tags

Main Features

1
Instant deploy without external server

Pre-built doPost handler with UrlFetchApp lets you receive Telegram webhooks by simply pasting the code into GAS and publishing it.

2
Simplified Telegram API calls

Includes examples for basic API endpoints like sendMessage, enabling replies and notifications with a few lines.

3
Minimal and easy-to-understand structure

Single-file structure keeps the code base small, making it easy for GAS newcomers to follow and customise.

Usage Examples

Minimal echo bot example

/*
 Replace with your actual bot token in the form "123456:ABC...".
 You can keep tokens in Script Properties as well.
*/
const TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN';
const API_URL = `https://api.telegram.org/bot${TOKEN}`;

// Receive Telegram webhook
function doPost(e) {
  // Parse incoming update JSON
  const update = JSON.parse(e.postData.contents);
  const message = update.message;
  if (!message || !message.text) return ContentService.createTextOutput('no message');

  // Echo back the received text
  sendText(message.chat.id, `You said: ${message.text}`);
  return ContentService.createTextOutput('ok');
}

// Helper to call Telegram API
function sendText(chatId, text) {
  const payload = {
    chat_id: chatId,
    text: text
  };
  const options = {
    method: 'post',
    contentType: 'application/json',
    payload: JSON.stringify(payload)
  };
  // Request to sendMessage endpoint
  UrlFetchApp.fetch(`${API_URL}/sendMessage`, options);
}

Paste the code into Code.gs, deploy the project as a Web App, and set the resulting URL as your Telegram Webhook. You now have a working echo bot.