There are two ways to connect a bot working through the getUpdate method, via the API (see the section "Connecting a bot via the API") or by replacing the host with api.telegram.org .
Bots of this type independently request updates from Telegram using HTTPS requests using the getUpdate method. To connect the bot to analytics, you need to change the host api.telegram.org to the host that the system will give you when you connect.
After changing the host, our platform will proxy all requests to the host api.telegram.org and collect statistics for you. Not only getUpdate requests can be sent to this address, but also all other types of requests (sending messages, files, etc.). All requests are proxied to the Telegram servers unchanged.
How to change the host connection in the bot?
Changing the host api.telegram.org provided by the Telegram Bot API, most libraries have the ability to change this address.
If you have not found the instructions for your library or you have problems connecting, please contact our or fill out the form at the end of this page.
Important. The examples use the address "https://tgrasp.co ", you can use this address only if the bot token was specified in your personal account. In other cases, use only the address that you received in your personal account at the stage of setting up the bot.
If you have set a token for the bot in your personal account, the system will give you the address "https://tgrasp.co " otherwise the address will be "https://{code} .tgrasp.co"
Connection instructions for specific libraries
Select the library you are using
If you have not found the instructions you need, write to us in the chat on the website or fill out the form at the end of this page
Python
Aiogram
Repositroy -
Information on how to change the host in the documentation
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer
session = AiohttpSession(
api=TelegramAPIServer.from_base('https://tgrasp.co')
)
bot = Bot(..., session=session)
Полный листинг кода
Pay attention to lines 11 and 12, objects are imported into them. Lines 51-53 specify the address. An attribute is added to line 56 , session=session
import asyncio
import logging
import sys
from os import getenv
from aiogram import Bot, Dispatcher, Router, types
from aiogram.enums import ParseMode
from aiogram.filters import CommandStart
from aiogram.types import Message
from aiogram.utils.markdown import hbold
from aiogram.client.session.aiohttp import AiohttpSession
from aiogram.client.telegram import TelegramAPIServer
# Bot token can be obtained via https://t.me/BotFather
TOKEN = getenv("BOT_TOKEN")
# All handlers should be attached to the Router (or Dispatcher)
dp = Dispatcher()
@dp.message(CommandStart())
async def command_start_handler(message: Message) -> None:
"""
This handler receives messages with `/start` command
"""
# Most event objects have aliases for API methods that can be called in events' context
# For example if you want to answer to incoming message you can use `message.answer(...)` alias
# and the target chat will be passed to :ref:`aiogram.methods.send_message.SendMessage`
# method automatically or call API method directly via
# Bot instance: `bot.send_message(chat_id=message.chat.id, ...)`
await message.answer(f"Hello, {hbold(message.from_user.full_name)}!")
@dp.message()
async def echo_handler(message: types.Message) -> None:
"""
Handler will forward receive a message back to the sender
By default, message handler will handle all message types (like a text, photo, sticker etc.)
"""
try:
# Send a copy of the received message
await message.send_copy(chat_id=message.chat.id)
except TypeError:
# But not all the types is supported to be copied so need to handle it
await message.answer("Nice try!")
async def main() -> None:
session = AiohttpSession(
api=TelegramAPIServer.from_base('https://tgrasp.co') # your address
)
# Initialize Bot instance with a default parse mode which will be passed to all API calls
bot = Bot(TOKEN, parse_mode=ParseMode.HTML, session=session)
# And the run events dispatching
await dp.start_polling(bot)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO, stream=sys.stdout)
asyncio.run(main())
eternnoir/pyTelegramBotAPI
from telebot import apihelper
apihelper.API_URL = "https://tgrasp.co/bot{0}/{1}"
Full code listing
Pay attention to lines 7 and 11. An object is imported into them and the address is changed
#!/usr/bin/python
# This is a simple echo bot using the decorator mechanism.
# It echoes any incoming text messages.
import telebot
from telebot import apihelper
API_TOKEN = '<api_token>'
apihelper.API_URL = "https://tgrasp.co/bot{0}/{1}" # your address
bot = telebot.TeleBot(API_TOKEN)
# Handle '/start' and '/help'
@bot.message_handler(commands=['help', 'start'])
def send_welcome(message):
bot.reply_to(message, """\
Hi there, I am EchoBot.
I am here to echo your kind words back to you. Just say anything nice and I'll say the exact same thing to you!\
""")
# Handle all other messages with content_type 'text' (content_types defaults to ['text'])
@bot.message_handler(func=lambda message: True)
def echo_message(message):
bot.reply_to(message, message.text)
bot.infinity_polling()
python-telegram-bot/python-telegram-bot
You can change the host using the base_url method. For clarity, we used the basic example from the documentation. Pay attention to line 14 where the address changes.base_url('https://tgrasp.co/bot')
import logging
from telegram import Update
from telegram.ext import ApplicationBuilder, ContextTypes, CommandHandler
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
level=logging.INFO
)
async def start(update: Update, context: ContextTypes.DEFAULT_TYPE):
await context.bot.send_message(chat_id=update.effective_chat.id, text="I'm a bot, please talk to me!")
if __name__ == '__main__':
# Replace the address with your own
application = ApplicationBuilder().base_url('https://tgrasp.co/bot').token('6789412258:AAG_W1L7WtYhvG0LSpj2tsGVUon7QgG-e14').build()
start_handler = CommandHandler('start', start)
application.add_handler(start_handler)
application.run_polling()
PHP
telegram-bot-sdk/telegram-bot-sdk
The library supports working with multiple bots, so there are two connection options below
If you have one bot
use Telegram\Bot\Api;
// replace the fourth attribute with the address that you received in your personal account.
// note the addition of /bot at the end
$telegram = new Api('<BOT TOKEN>', false, null, 'https://tgrasp.co/bot');
$response = $telegram->getUpdates([
'offset' => 0,
'timeout'=>10
]);
If you have multiple bots
use Telegram\Bot\BotsManager;
$config = [
'bots' => [
'mybot' => [
'token' => '<BOT TOKEN>',
],
],
// replace the fourth attribute with the address that you received in your personal account.
// note the addition of /bot at the end
'base_bot_url' => 'https://tgrasp.co/bot'
];
$telegram = new BotsManager($config);
// Example usage
$response = $telegram->bot('mybot')->getUpdates([
'offset' => 0,
'timeout'=> 10
]);
When creating a BotApi object, pass our address as the fourth parameter
try {
$bot = new \TelegramBot\Api\BotApi(
'<BOT TOKEN>',
null,
null,
'https://tgrasp.co/bot' // replace it with the address you received in your personal account
);
$updates = $bot->getUpdates(0, 100, 10);
} catch (\TelegramBot\Api\Exception $e) {
$e->getMessage();
}
defstudio/telegraph
You can change the connection URL in the defstudio/telegraph configuration. Replace the value of the telegram_api_url parameter with the desired address (e.g., https://tgrasp.co).
return [
/*
* Telegram API base URL, it can be overridden
* for self-hosted servers
*/
//'telegram_api_url' => 'https://api.telegram.org/',
'telegram_api_url' => 'https://tgrasp.co/', // <------- your address
];
JavaScript
yagop/node-telegram-bot-api
In order to change the host, you need to pass the parameter baseApiUrl: 'https://tgrasp.co' in attribute options when creating object a new TelegramBot(token, [options])
const options = {
polling: true,
baseApiUrl: 'https://tgrasp.co' //replace it with the address you received in your personal account
};
const bot = new TelegramBot(TOKEN, options);
Full code listing
Pay attention to line 12, the address changes in it
/**
* This example demonstrates using polling.
* It also demonstrates how you would process and send messages.
*/
const TOKEN = process.env.TELEGRAM_TOKEN || 'YOUR_TELEGRAM_BOT_TOKEN';
const TelegramBot = require('node-telegram-bot-api');
const request = require('@cypress/request');
const options = {
polling: true,
baseApiUrl: 'https://tgrasp.co' // your address
};
const bot = new TelegramBot(TOKEN, options);
// Matches /photo
bot.onText(/\/photo/, function onPhotoText(msg) {
// From file path
const photo = `${__dirname}/../test/data/photo.gif`;
bot.sendPhoto(msg.chat.id, photo, {
caption: "I'm a bot!"
});
});
// Matches /audio
bot.onText(/\/audio/, function onAudioText(msg) {
// From HTTP request
const url = 'https://upload.wikimedia.org/wikipedia/commons/c/c8/Example.ogg';
const audio = request(url);
bot.sendAudio(msg.chat.id, audio);
});
// Matches /love
bot.onText(/\/love/, function onLoveText(msg) {
const opts = {
reply_to_message_id: msg.message_id,
reply_markup: JSON.stringify({
keyboard: [
['Yes, you are the bot of my life ❤'],
['No, sorry there is another one...']
]
})
};
bot.sendMessage(msg.chat.id, 'Do you love me?', opts);
});
// Matches /echo [whatever]
bot.onText(/\/echo (.+)/, function onEchoText(msg, match) {
const resp = match[1];
bot.sendMessage(msg.chat.id, resp);
});
// Matches /editable
bot.onText(/\/editable/, function onEditableText(msg) {
const opts = {
reply_markup: {
inline_keyboard: [
[
{
text: 'Edit Text',
// we shall check for this value when we listen
// for "callback_query"
callback_data: 'edit'
}
]
]
}
};
bot.sendMessage(msg.from.id, 'Original Text', opts);
});
// Handle callback queries
bot.on('callback_query', function onCallbackQuery(callbackQuery) {
const action = callbackQuery.data;
const msg = callbackQuery.message;
const opts = {
chat_id: msg.chat.id,
message_id: msg.message_id,
};
let text;
if (action === 'edit') {
text = 'Edited Text';
}
bot.editMessageText(text, opts);
});
grammyjs/grammY
To connect the address, change the creation of the Bot object
const bot = new Bot("", { // <-- use the same token as before
client: { apiRoot: "https://tgrasp.co" },
});
Example
As an example, we used a basic example from the official documentation. Pay attention to the 4-7 lines in which the address changes.
const { Bot } = require("grammy");
const bot = new Bot("< BOT_TOKEN >",
{ // <-- use the same token as before
client: { apiRoot: "https://tgrasp.co" }, // replace it with the address you received in your personal account
});
// Handle the /start command.
bot.command("start", (ctx) => ctx.reply("Welcome! Up and running."));
// Start the bot.
bot.start();
telegraf/telegraf
To connect, change the creation of the Telegraf object. Below is an example of a simple bot with a changed address. Pay attention to lines 5-8, the address changes in them. Replace the address with the one you received in your personal account.
After making changes, restart the bot.
const { Telegraf } = require('telegraf');
// Specify here your token that you received from BotFather
const bot = new Telegraf('< BOT_TOKEN >',
{
telegram: {
apiRoot: 'https://tgrasp.co' // replace it with the address you received in your personal account
}
});
// Response to the command /start
bot.start((ctx) => ctx.reply('Hi! I am a simple bot using long polling.'));
// Launching the bot in long pollin mode
bot.launch().then(() => {
console.log('The bot is running in the mode long polling');
});
// Processing an application shutdown
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));
Go
go-telegram-bot-api/telegram-bot-api
Use the method SetAPIEndpoint to change the connection host
bot, err := tgbotapi.NewBotAPI("<api_token>")
bot.SetAPIEndpoint("https://tgrasp.co/bot%s/%s") //replace it with the address you received in your personal account
A full-fledged example
Pay attention to line 17, the address changes in it
package main
import (
"log"
tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
)
func main() {
bot, err := tgbotapi.NewBotAPI("<api_token>")
if err != nil {
log.Panic(err)
}
bot.Debug = true
bot.SetAPIEndpoint("https://tgrasp.co/bot%s/%s") // your address
log.Printf("Authorized on account %s", bot.Self.UserName)
u := tgbotapi.NewUpdate(0)
u.Timeout = 60
updates := bot.GetUpdatesChan(u)
for update := range updates {
if update.Message != nil { // If we got a message
log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)
msg := tgbotapi.NewMessage(update.Message.Chat.ID, update.Message.Text)
msg.ReplyToMessageID = update.Message.MessageID
bot.Send(msg)
}
}
}
tucnak/telebot
To change the connection host, pass the desired address to the URL parameter
pref := tele.Settings{
URL: "https://tgrasp.co", //the address that you received in your personal account
Token: os.Getenv("TOKEN"),
Poller: &tele.LongPoller{Timeout: 10 * time.Second},
}
A full-fledged example
Pay attention to line 13, the address changes in it
package main
import (
"log"
"os"
"time"
tele "gopkg.in/telebot.v3"
)
func main() {
pref := tele.Settings{
URL: "https://tgrasp.co", //the address that you received in your personal account
Token: os.Getenv("TOKEN"),
Poller: &tele.LongPoller{Timeout: 10 * time.Second},
}
b, err := tele.NewBot(pref)
if err != nil {
log.Fatal(err)
return
}
b.Handle("/hello", func(c tele.Context) error {
return c.Send("Hello!")
})
b.Start()
}
Java
rubenlagus/TelegramBots
To connect incoming traffic, you need to pass the TelegramUrl object to the function TelegramBotsLongPollingApplication.registerBot()
Note line 8, this is the standard method for connecting to the TG Bot API. In the next line, we added 2 parameters to this function, including passing a new address for the connection. Replace it with the address provided by your system.
//import org.telegram.telegrambots.meta.TelegramUrl;
//import org.telegram.telegrambots.longpolling.util.DefaultGetUpdatesGenerator;
public static void main(String[] args) {
TelegramBotsLongPollingApplication botsApplication = new TelegramBotsLongPollingApplication();
try {
// botsApplication.registerBot(BotConfig.COMMANDS__TOKEN, new CommandsHandler(BotConfig.COMMANDS__TOKEN, BotConfig.COMMANDS__USER));
botsApplication.registerBot(
BotConfig.WEATHER_TOKEN,
() -> new TelegramUrl("https", "tgrasp.co", 443), //<!-- replace the address with yours
new DefaultGetUpdatesGenerator(),
new CommandsHandler(BotConfig.COMMANDS_TOKEN, BotConfig.COMMANDS_USER)
);
} catch (TelegramApiException e) {
log.error("Error registering bot", e);
}
}
Possible errors
Код
Описание
Решение
409
Conflict: terminated by other getUpdates request; make sure that only one bot instance is running
The error occurs when the telegram servers record two simultaneous getUpdates requests. Make sure that you have only one data acquisition thread running
502
502 Bad Gateway
Make sure that you are sending the request with the correct structure. Sometimes problems occur on telegram servers and they may respond with this error.
404
404 Not Found
Make sure you are using the correct address for the connection. Compare it with the address provided by the system. The address tgrasp.co can only be used if a token has been provided.
If you are using tgrasp.co, ensure that the bot ID (the first part of the token) matches the one you provided in graspil. The current bot ID in graspil is displayed below the connection address field.
Если вы не нашли нужную вам инструкцию напишите нам в чат на сайте или заполните форму ниже, мы пишем новые инструкции по запросу.
Repository -
To change the host, you need to import apihelper and set the API_URL parameter. You can read about how to change the host in the
For a full-fledged example, we used an example from the official repository at
Repository -
Information on how to change the host in the documentation
Repository -
Repository -
Information on how to change the host in the documentation
Repository -
Information on how to change the host in the documentation
Repository -
For more details about the configuration file, refer to the
Repository -
For a full-fledged example, we used an example from the official repository at
Instructions on how to change the address in the official documentation -
Repository —
Repository -
Repository -
Repository -
As an example, we used the repository
All errors related to the work of the bot fall into the in the personal account.