Bot error
alpacco
HOBBYOP

10 days ago

Hello Railway Support Team,

I'm experiencing persistent connection issues with my Telegram bot application deployed on Railway. The bot cannot establish outbound connections to Telegram's API api.telegram.org), which prevents it from initializing and processing commands.

## Problem Description

- Service: Telegram Bot Application (Python/FastAPI)

- Issue: Bot cannot connect to api.telegram.org - all connection attempts timeout

- Error Messages:

- httpx.ConnectError: All connection attempts failed

- telegram.error.TimedOut: Timed out

- httpcore.ConnectTimeout

## What I've Verified

1. white_check_mark emojiCode works locally - The bot connects successfully from my local machine

2. white_check_mark emojiAPI and Database work - All other services (FastAPI, PostgreSQL) function normally

3. white_check_mark emojiBot token is valid - Verified the Telegram bot token is correct

4. white_check_mark emojiOld commits also fail - Even previous working versions fail, indicating infrastructure issue

5. white_check_mark emojiApplication starts - FastAPI server starts successfully, but bot initialization fails

## Logs Evidence

```

2025-12-30 19:14:15,230 - app.bot.bot - WARNING - warning emoji [START_BOT] Сетевая ошибка при инициализации (попытка 1/3): Timed out. Повтор через 5с...

2025-12-30 19:14:35,344 - app.bot.bot - WARNING - warning emoji [START_BOT] Сетевая ошибка при инициализации (попытка 2/3): httpx.ConnectError: All connection attempts failed. Повтор через 5с...

```

The bot attempts to initialize 3 times with 5-second delays, but all attempts fail with network timeouts.

## Technical Details

- Connection Timeout: 30 seconds (configured)

- Retry Attempts: 3 attempts with exponential backoff

- Target:api.telegram.org:443 (HTTPS)

- Protocol: HTTPS/TLS

## What I Need

1. Verify outbound connectivity - Can Railway containers establish outbound HTTPS connections to api.telegram.org?

2. Check firewall rules - Are there any firewall rules blocking outbound connections to Telegram's API?

3. Network configuration - Are there any network restrictions or proxy settings that might interfere?

4. DNS resolution - Can Railway resolve api.telegram.org correctly?

## Additional Information

- Service Type: Web Service

- Region: (Please specify your region if known)

- Deployment: Auto-deploy from GitHub

- Runtime: Python 3.10

The bot worked previously, but this issue started recently. This appears to be an infrastructure/network issue rather than a code problem, as even old working commits fail with the same connection errors.

Could you please investigate the outbound network connectivity from Railway containers to api.telegram.org? Any assistance would be greatly appreciated.

Thank you for your time and support.

---

Awaiting User Response

76 Replies

hellomynot
HOBBY

10 days ago

Hello Railway Support Team,

I am experiencing an issue with long polling in my Telegram bot running on your platform.

Symptoms:

- The bot crashes with the error: "HTTP Client says - Request timeout error".

- Telegram API works fine from my local machine using curl:

curl -v https://api.telegram.org/bot<TOKEN>/getMe

Response: 200 OK, JSON with bot information.

- The timeouts occur only on Railway, indicating a possible network or infrastructure problem.

Suspicions:

- Potential issues with long polling / persistent TCP connections.

- Possible IPv6 / routing problems.

- Free tier containers may be unstable with long-lived HTTP connections.

Questions:

1. Are there any known issues with long polling or TCP connections on your infrastructure?

2. Could you check if there is packet loss or restrictions for my project?

Thank you for your help.

Best regards,


akobirismailov
HOBBY

10 days ago

Hello!
I have the same issue.
Failed to contact Telegram while validating the bot token

All my work bots suddenly stopped working.


alpacco
HOBBYOP

10 days ago

Railway, please HELP


cherepinskiykostya-lgtm
PRO

10 days ago

+1


abm1982
PRO

10 days ago

Same here


rohit148-hub
HOBBY

10 days ago

Same


peppay
HOBBY

10 days ago

Having the same issue.

Deployed into us-west-2, using Grammy for NodeJS


natitosmarques
HOBBY

10 days ago

Same here


akobirismailov
HOBBY

10 days ago

Guys, please click on the arrow button on the initial post, hope the issue will be prioritised.
Thanks!


0xpants
FREE

10 days ago

Same here


goldiecoin1
HOBBY

10 days ago

.


natitosmarques
HOBBY

10 days ago

bora railway, agita ai slightly_smiling_face emoji


natitosmarques

bora railway, agita ai

abm1982
PRO

10 days ago

Teu bot é de que? Kkk


akobirismailov
HOBBY

10 days ago


abm1982

Teu bot é de que? Kkk

natitosmarques
HOBBY

10 days ago

Essa carniça aqui: @SuperListaBot , divulgação de grupos


natitosmarques

Essa carniça aqui: @SuperListaBot , divulgação de grupos

abm1982
PRO

10 days ago

O meu é o B


tweaky349
HOBBY

10 days ago

Same here


abm1982

O meu é o B

natitosmarques
HOBBY

10 days ago

Pow legal em , deve ter bastante público

por que pessoal gosta de criar um fake kkkk


cherepinskiykostya-lgtm
PRO

10 days ago

is anyone going to manage this issue????


cherepinskiykostya-lgtm

is anyone going to manage this issue????

natitosmarques
HOBBY

10 days ago

we depend on your beloved railway


akobirismailov
HOBBY

10 days ago

2 hours downtime for services with active marketing promotion... :(


cherepinskiykostya-lgtm
PRO

10 days ago

see support next year


peppay
HOBBY

10 days ago

It's not ideal, but I just found a workaround for this in the meantime.

Create a Cloudflare account, create a new Worker and set the code to the below to make a very cheap/easy proxy using Cloudflare which has a very generous free tier.

export default {
  async fetch(request) {
    const url = new URL(request.url);
    
    // Rewrite the URL to point to Telegram API
    const telegramUrl = `https://api.telegram.org${url.pathname}${url.search}`;
    
    // Forward the request
    return fetch(telegramUrl, {
      method: request.method,
      headers: request.headers,
      body: request.method !== 'GET' ? request.body : undefined,
    });
  },
};

Then in your code, whatever framework you're using, set the URL of the new worker as your proxy/callback URL.

For instance, using Grammy for NodeJS the following resolves by using Cloudflare as a simple proxy:

const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN, {
  apiRoot: process.env.TELEGRAM_API_PROXY_URL,
});

paveldumbrao
PRO

10 days ago

## red_circle emoji Confirmed Issue - Railway-Wide Telegram API Connectivity Problem

English:

I can confirm this is affecting multiple users across Railway. I'm experiencing the identical issue with n8n workflows running Telegram Bot API nodes.

Key Findings:

- white_check_mark emoji DNS resolution works correctly (149.154.167.220)

- white_check_mark emoji Other HTTP/HTTPS requests from Railway function normally

- x emojiOnly connections to api.telegram.org:443 timeout

- x emoji Timeout occurs at TCP connection phase, NOT TLS/HTTP layer

- x emoji Affects ALL Telegram Bot API endpoints

This appears to be a Railway network/firewall issue blocking outbound HTTPS connections specifically to Telegram's IP ranges (149.154.167.0/24 and related blocks). The same bots work perfectly on local machines and other hosting providers.

Temporary workaround: Anonymous user above shared a Cloudflare Workers proxy solution - excellent idea for urgent production needs!

To everyone affected: Stay strong, hang in there! muscle emoji We're all in this together. Hopefully Railway team will resolve this infrastructure issue soon.

---

Русский:

Подтверждаю - проблема массовая, затрагивает множество пользователей Railway. У меня идентичная ситуация с n8n workflows и Telegram Bot API.

Основные выводы:

- white_check_mark emoji DNS резолв работает корректно (149.154.167.220)

- white_check_mark emoji Другие HTTP/HTTPS запросы с Railway работают нормально

- x emojiТолько подключения к api.telegram.org:443 таймаутятся

- x emoji Таймаут на уровне TCP connect, НЕ TLS/HTTP

- x emoji Затронуты ВСЕ эндпоинты Telegram Bot API

Это похоже на проблему сети/файрвола Railway, блокирующую исходящие HTTPS-соединения именно к IP-диапазонам Telegram (149.154.167.0/24 и связанные блоки). Те же боты отлично работают на локальных машинах и других хостингах.

Временное решение: Anonymous выше поделился решением через Cloudflare Workers proxy - отличная идея для срочных production задач!

Всем пострадавшим: Держимся, братцы! muscle emoji Мы все в одной лодке. Надеюсь, команда Railway скоро решит эту инфраструктурную проблему.

Удачи всем! Good luck everyone!rocket emoji


paveldumbrao

## Confirmed Issue - Railway-Wide Telegram API Connectivity ProblemEnglish:I can confirm this is affecting multiple users across Railway. I'm experiencing the identical issue with n8n workflows running Telegram Bot API nodes.Key Findings:- DNS resolution works correctly (149.154.167.220)- Other HTTP/HTTPS requests from Railway function normally- Only connections to api.telegram.org:443 timeout- Timeout occurs at TCP connection phase, NOT TLS/HTTP layer- Affects ALL Telegram Bot API endpointsThis appears to be a Railway network/firewall issue blocking outbound HTTPS connections specifically to Telegram's IP ranges (149.154.167.0/24 and related blocks). The same bots work perfectly on local machines and other hosting providers.Temporary workaround: Anonymous user above shared a Cloudflare Workers proxy solution - excellent idea for urgent production needs!To everyone affected: Stay strong, hang in there! We're all in this together. Hopefully Railway team will resolve this infrastructure issue soon.---Русский:Подтверждаю - проблема массовая, затрагивает множество пользователей Railway. У меня идентичная ситуация с n8n workflows и Telegram Bot API.Основные выводы:- DNS резолв работает корректно (149.154.167.220)- Другие HTTP/HTTPS запросы с Railway работают нормально- Только подключения к api.telegram.org:443 таймаутятся- Таймаут на уровне TCP connect, НЕ TLS/HTTP- Затронуты ВСЕ эндпоинты Telegram Bot APIЭто похоже на проблему сети/файрвола Railway, блокирующую исходящие HTTPS-соединения именно к IP-диапазонам Telegram (149.154.167.0/24 и связанные блоки). Те же боты отлично работают на локальных машинах и других хостингах.Временное решение: Anonymous выше поделился решением через Cloudflare Workers proxy - отличная идея для срочных production задач!Всем пострадавшим: Держимся, братцы! Мы все в одной лодке. Надеюсь, команда Railway скоро решит эту инфраструктурную проблему.Удачи всем! Good luck everyone!

alpacco
HOBBYOP

10 days ago

Держимся, братцы! muscle emoji ахаха :))) надеюсь Railway это переведет :))


cherepinskiykostya-lgtm
PRO

10 days ago

запрацювало!


cherepinskiykostya-lgtm

запрацювало!

paveldumbrao
PRO

10 days ago

смысле само? или ты что то сделал?


paveldumbrao

смысле само? или ты что то сделал?

cherepinskiykostya-lgtm
PRO

10 days ago

само


cherepinskiykostya-lgtm

само

paveldumbrao
PRO

10 days ago

у меня пока нет


alpacco
HOBBYOP

10 days ago

Сделал редеплой, все та же хрень - не работает


alpacco
HOBBYOP

10 days ago

О! заработало!


alpacco

О! заработало!

paveldumbrao
PRO

10 days ago

Где то я уже это слышал)


paveldumbrao
PRO

10 days ago

Кстати у всех с октября за N8N дороже получается платить?) (оффтоп)


alpacco

О! заработало!

hellomynot
HOBBY

10 days ago

what did you do


hellomynot

what did you do

cherepinskiykostya-lgtm
PRO

10 days ago

I did nothing. Bot became alive suddenly in chat and strated to answer missed questions for 2 hours


abm1982
PRO

10 days ago

Some Telegram bots have returned, others have not.


paveldumbrao

Где то я уже это слышал)

alpacco
HOBBYOP

10 days ago

правда slightly_smiling_face emoji причем не после нового деплоя а просто )


abm1982
PRO

10 days ago

My bots have returned to work


abm1982
PRO

10 days ago

One of them I had to redeploy


alpacco
HOBBYOP

10 days ago

и перестало опять :((( And it stopped again


alpacco

и перестало опять :((( And it stopped again

cherepinskiykostya-lgtm
PRO

10 days ago

мої три працюють...

three of mine still work


alpacco

и перестало опять :((( And it stopped again

abm1982
PRO

10 days ago

post in english please


alpacco
HOBBYOP

10 days ago

сrashed again


faisalz
HOBBY

10 days ago

Experiencing same issue. Please resolve it. It does not appear to be a Telegram API issue, although others are experiencing similar delays. One request was able to eke through somehow.


abm1982
PRO

10 days ago

Crashed again


natitosmarques
HOBBY

10 days ago

e lá vamos nós de novo kkkk


akobirismailov

Guys, please click on the arrow button on the initial post, hope the issue will be prioritised.Thanks!

luislimapro
HOBBY

10 days ago

Aqui também!! Vou cancelar minha assinatura tem dias que está assim


luislimapro

Aqui também!! Vou cancelar minha assinatura tem dias que está assim

abm1982
PRO

10 days ago

E vai pra onde? Saí da squarecloud pq bugava e aqui estou


natitosmarques
HOBBY

10 days ago

aqui é bem melhor do que a square


natitosmarques

aqui é bem melhor do que a square

abm1982
PRO

10 days ago

Também acho


abm1982

Também acho

luislimapro
HOBBY

10 days ago

A equipe do railway ainda não deu nenhum parecer sobre esse problema?!


luislimapro

A equipe do railway ainda não deu nenhum parecer sobre esse problema?!

abm1982
PRO

10 days ago

não


Anonymous
PRO

10 days ago

Anyone able to get the connection to the TG API to work? It works sometimes and not stable


Anyone able to get the connection to the TG API to work? It works sometimes and not stable

luislimapro
HOBBY

10 days ago

Faça isso que tudo se resolverá:

Não é o ideal, mas encontrei uma solução alternativa provisória.

Crie uma conta na Cloudflare, crie um novo Worker e defina o código abaixo para criar um proxy muito barato e fácil usando a Cloudflare, que possui um plano gratuito bastante generoso.

export default {

async fetch(request) {

const url = new URL(request.url);

// Rewrite the URL to point to Telegram API

const telegramUrl = `https://api.telegram.org${url.pathname}${url.search}`;

// Forward the request

return fetch(telegramUrl, {

method: request.method,

headers: request.headers,

body: request.method !== 'GET' ? request.body : undefined,

});

},

};

Em seguida, no seu código, independentemente do framework que estiver usando, defina a URL do novo worker como a URL do seu proxy/callback.

Por exemplo, usando o Grammy para NodeJS, o seguinte código é resolvido usando o Cloudflare como um proxy simples:

const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN, {

apiRoot: process.env.TELEGRAM_API_PROXY_URL,

});


Anyone able to get the connection to the TG API to work? It works sometimes and not stable

peppay
HOBBY

10 days ago


peppay

It's not ideal, but I just found a workaround for this in the meantime.Create a Cloudflare account, create a new Worker and set the code to the below to make a very cheap/easy proxy using Cloudflare which has a very generous free tier.export default { async fetch(request) { const url = new URL(request.url); // Rewrite the URL to point to Telegram API const telegramUrl = `https://api.telegram.org${url.pathname}${url.search}`; // Forward the request return fetch(telegramUrl, { method: request.method, headers: request.headers, body: request.method !== 'GET' ? request.body : undefined, }); }, };Then in your code, whatever framework you're using, set the URL of the new worker as your proxy/callback URL.For instance, using Grammy for NodeJS the following resolves by using Cloudflare as a simple proxy:const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN, { apiRoot: process.env.TELEGRAM_API_PROXY_URL, });

Hello all,

Sorry for the delayed ack here on our side. It seems like someone was sending some outbound traffic causing our IP set to be ratelimited. We don't have a relationship with the TG team although we should, we're going to see what we can do in the meantime. In the shortterm, proxying your API calls would be the best workaround for now.


Status changed to Awaiting User Response Railway 10 days ago


angelo-railway

Hello all,Sorry for the delayed ack here on our side. It seems like someone was sending some outbound traffic causing our IP set to be ratelimited. We don't have a relationship with the TG team although we should, we're going to see what we can do in the meantime. In the shortterm, proxying your API calls would be the best workaround for now.

akobirismailov
HOBBY

10 days ago

Do you have any ETA when everything will be fine?


Status changed to Awaiting Railway Response Railway 10 days ago


dash570
HOBBY

10 days ago

Same Issue Here.


alpacco
HOBBYOP

10 days ago

AGAIN!


angelo-railway

Hello all,Sorry for the delayed ack here on our side. It seems like someone was sending some outbound traffic causing our IP set to be ratelimited. We don't have a relationship with the TG team although we should, we're going to see what we can do in the meantime. In the shortterm, proxying your API calls would be the best workaround for now.

alpacco
HOBBYOP

10 days ago

Contact TG support, the problem is massive, we really look forward to a solution https://telegram.org/support


akobirismailov
HOBBY

10 days ago

@Railway team,

Any updates? :)


chandrika
EMPLOYEE

9 days ago

Hi folks, we are unfortunately still waiting to hear back from Telegram (resolution is largely outside our control). As Angelo mentioned, the most reliable workaround in the meantime would be to use a proxy.

We know this is frustrating, especially if you're running production services. We'll post an update here as soon as we have more information.

A note to the community and folks on this thread: if anyone here has been able to find a workaround using a proxy, could you please share a detailed technical explanation of how you did it?

If it works for others as a holdover while Telegram gets back to us, we will be happy to compensate your preferred workspace $50 in Railway creditsfor helping out your fellow users purple_heart emoji

Best, The Railway Team


Status changed to Awaiting User Response Railway 9 days ago


chandrika

Hi folks, we are unfortunately still waiting to hear back from Telegram (resolution is largely outside our control). As Angelo mentioned, the most reliable workaround in the meantime would be to use a proxy.We know this is frustrating, especially if you're running production services. We'll post an update here as soon as we have more information.A note to the community and folks on this thread: if anyone here has been able to find a workaround using a proxy, could you please share a detailed technical explanation of how you did it?If it works for others as a holdover while Telegram gets back to us, we will be happy to compensate your preferred workspace $50 in Railway creditsfor helping out your fellow usersBest, The Railway Team

luislimapro
HOBBY

9 days ago

Essa é a solução temporária:

Não é o ideal, mas encontrei uma solução alternativa provisória.

Crie uma conta na Cloudflare, crie um novo Worker e defina o código abaixo para criar um proxy muito barato e fácil usando a Cloudflare, que possui um plano gratuito bastante generoso.

exportar padrão {

async fetch(request) {

const url = new URL(request.url);

// Reescreva a URL para apontar para a API do Telegram

const telegramUrl = `https://api.telegram.org${url.pathname}${url.search}`;

// Encaminhar a solicitação

retornar fetch(telegramUrl, {

método: método de solicitação,

cabeçalhos: request.headers,

corpo: método da requisição !== 'GET' ? corpo da requisição : indefinido,

});

},

};

Em seguida, no seu código, independentemente do framework que você estiver usando, defina a URL do novo trabalhador como a URL do seu proxy/callback.

Por exemplo, usando o Grammy para NodeJS, o seguinte código é resolvido usando o Cloudflare como um proxy simples:

const bot = new Bot(process.env.TELEGRAM_BOT_TOKEN, {

apiRoot: process.env.TELEGRAM_API_PROXY_URL,

});


Status changed to Awaiting Railway Response Railway 9 days ago


Railway
BOT

9 days ago

Hello!

We're acknowledging your issue and attaching a ticket to this thread.

We don't have an ETA for it, but, our engineering team will take a look and you will be updated as we update the ticket.

Please reply to this thread if you have any questions!


Railway
BOT

9 days ago

🛠️ The ticket Outbound connection issues in EU region has been marked as triage.


Status changed to Awaiting User Response Railway 9 days ago


chandrika

Hi folks, we are unfortunately still waiting to hear back from Telegram (resolution is largely outside our control). As Angelo mentioned, the most reliable workaround in the meantime would be to use a proxy.We know this is frustrating, especially if you're running production services. We'll post an update here as soon as we have more information.A note to the community and folks on this thread: if anyone here has been able to find a workaround using a proxy, could you please share a detailed technical explanation of how you did it?If it works for others as a holdover while Telegram gets back to us, we will be happy to compensate your preferred workspace $50 in Railway creditsfor helping out your fellow usersBest, The Railway Team

peppay
HOBBY

9 days ago

Hi Chandrika,

I posted previously in this thread: https://station.railway.com/questions/bot-error-ef3e0945#nrsa

About using Cloudflare workers as a proxy. I've been using this since yesterday and it has been working consistently.


Status changed to Awaiting Railway Response Railway 9 days ago


peppay

Hi Chandrika,I posted previously in this thread: https://station.railway.com/questions/bot-error-ef3e0945#nrsaAbout using Cloudflare workers as a proxy. I've been using this since yesterday and it has been working consistently.

chandrika
EMPLOYEE

9 days ago

Amazing, thank you so much peppay! I'll go ahead and share this with a few other users not on this thread in the meantime while we're waiting to hear back from Telegram pray emoji

($50 have been added as credits to your workspace)


Status changed to Awaiting User Response Railway 9 days ago


luislimapro
HOBBY

9 days ago

É um absurdo o que a gente paga por uso nesses planos e ainda tem esses problemas!! Lamentavél a ferrovia está enferrujada!


Status changed to Awaiting Railway Response Railway 9 days ago


chandrika

Amazing, thank you so much peppay! I'll go ahead and share this with a few other users not on this thread in the meantime while we're waiting to hear back from Telegram ($50 have been added as credits to your workspace)

dash570
HOBBY

9 days ago

I think affected customers should get some compensation as well, i have a production app, with some angry clients not getting notifications, my entire app is telegram based.


alpacco
HOBBYOP

9 days ago

In my view, I support the idea that compensation should be provided to all affected parties. Today is New Year’s Day, and many people had their most important orders disrupted. I reported the problem yesterday, but it only started being addressed 12 hours later. The instructions shared by the user are incomplete, and it is currently quite difficult to understand and work with them. If everything had been explained step by step, it would have at least partially resolved the issue.


dash570

I think affected customers should get some compensation as well, i have a production app, with some angry clients not getting notifications, my entire app is telegram based.

luislimapro
HOBBY

9 days ago

Também acho fiquei um ou dois dias com esse problema perdi muitas vendas e esse mês a cobrança vem alta ainda por uso.. sem nem mesmo usar direito!!


alpacco
HOBBYOP

9 days ago

FULL WORK GUIDE

## Step 1: Install Wrangler CLI

```bash

npm install -g wrangler

```

## Step 2: Create Worker Project

```bash

mkdir telegram-api-proxy && cd telegram-api-proxy

mkdir src

```

## Step 3: Create Files

*src/index.js:**

```javascript

export default {

async fetch(request) {

const url = new URL(request.url);

const telegramUrl = https://api.telegram.org${url.pathname}${url.search};

const headers = new Headers(request.headers);

headers.delete('Host');

return fetch(telegramUrl, {

method: request.method,

headers: headers,

body: request.method !== 'GET' && request.method !== 'HEAD' ? request.body : undefined,

});

},

};

```

*wrangler.toml:**

```toml

name = "telegram-api-proxy"

main = "src/index.js"

compatibility_date = "2025-01-01"

```

## Step 4: Deploy

```bash

wrangler login

wrangler deploy

```

Copy the Worker URL (e.g., https://telegram-api-proxy.your-subdomain.workers.dev)

## Step 5: Update Your Bot Code

Your bot code should read TELEGRAM_API_PROXY_URL from environment variables and use it if set.

### Python (python-telegram-bot)

```python

from telegram.request import HTTPXRequest

from telegram.ext import Application

from app.core.config import settings # Your settings module

builder = Application.builder().token(settings.TELEGRAM_BOT_TOKEN)

# Use Cloudflare Worker proxy if configured

if settings.TELEGRAM_API_PROXY_URL:

from telegram.request import HTTPXRequest

proxy_url = settings.TELEGRAM_API_PROXY_URL.rstrip('/')

custom_request = HTTPXRequest(

connection_pool_size=8,

connect_timeout=30.0,

read_timeout=30.0,

write_timeout=30.0,

pool_timeout=10.0,

base_url=proxy_url # Worker will forward to api.telegram.org

)

builder = builder.request(custom_request)

logger.info(f"white_check_mark emoji Using Cloudflare Worker proxy: {proxy_url}")

application = builder.build()

```

**In your config file (e.g., config.py):**

```python

from pydantic_settings import BaseSettings

from typing import Optional

class Settings(BaseSettings):

TELEGRAM_BOT_TOKEN: str

TELEGRAM_API_PROXY_URL: Optional[str] = None # Cloudflare Worker URL (from Railway Variables)

```

**Note:** The bot reads TELEGRAM_API_PROXY_URL from Railway Variables. If the variable is set, it uses the proxy. If not set, it uses direct connection to Telegram API.

## Step 6: Set Environment Variable in Railway

1. Go to Railway Dashboard

2. Open your project

3. Navigate to **Variables** (or **Environment Variables**)

4. Click **"+ New Variable"**

5. Add:

- **Name:** TELEGRAM_API_PROXY_URL

- **Value:** https://telegram-api-proxy.your-subdomain.workers.dev (your Worker URL from Step 4)

6. Click **Save**

Railway will automatically restart your service after adding the variable.

## Step 7: Verify It's Working

Railway automatically restarts your service after adding the variable. Check Railway logs for:

```

white_check_mark emoji [CREATE_BOT] Используется Cloudflare Worker прокси: https://telegram-api-proxy.your-subdomain.workers.dev

```

or in English:

```

white_check_mark emoji Using Cloudflare Worker proxy: https://telegram-api-proxy.your-subdomain.workers.dev

```

If you see this message, the proxy is working! Test your bot by sending a command.

## Troubleshooting

**Bot not responding?**

1. Check Railway logs for errors

2. Verify TELEGRAM_API_PROXY_URL is set correctly in Railway Variables

3. Test Worker URL directly:

```bash

curl https://telegram-api-proxy.your-subdomain.workers.dev/bot<your-token>/getMe

```

4. Check Worker logs in Cloudflare Dashboard → Workers & Pages → Your Worker → Logs

**Need to disable proxy?**

1. Go to Railway Dashboard → Your Project → Variables

2. Delete the TELEGRAM_API_PROXY_URL variable

3. Railway will restart the service automatically

4. Bot will use direct connection to api.telegram.org


alpacco

FULL WORK GUIDE## Step 1: Install Wrangler CLI```bashnpm install -g wrangler```## Step 2: Create Worker Project```bashmkdir telegram-api-proxy && cd telegram-api-proxymkdir src```## Step 3: Create Files*src/index.js:**```javascriptexport default {async fetch(request) {const url = new URL(request.url);const telegramUrl = https://api.telegram.org${url.pathname}${url.search};const headers = new Headers(request.headers);headers.delete('Host');return fetch(telegramUrl, {method: request.method,headers: headers,body: request.method !== 'GET' && request.method !== 'HEAD' ? request.body : undefined,});},};```*wrangler.toml:**```tomlname = "telegram-api-proxy"main = "src/index.js"compatibility_date = "2025-01-01"```## Step 4: Deploy```bashwrangler loginwrangler deploy```Copy the Worker URL (e.g., https://telegram-api-proxy.your-subdomain.workers.dev)## Step 5: Update Your Bot CodeYour bot code should read TELEGRAM_API_PROXY_URL from environment variables and use it if set.### Python (python-telegram-bot)```pythonfrom telegram.request import HTTPXRequestfrom telegram.ext import Applicationfrom app.core.config import settings # Your settings modulebuilder = Application.builder().token(settings.TELEGRAM_BOT_TOKEN)# Use Cloudflare Worker proxy if configuredif settings.TELEGRAM_API_PROXY_URL:from telegram.request import HTTPXRequestproxy_url = settings.TELEGRAM_API_PROXY_URL.rstrip('/')custom_request = HTTPXRequest(connection_pool_size=8,connect_timeout=30.0,read_timeout=30.0,write_timeout=30.0,pool_timeout=10.0,base_url=proxy_url # Worker will forward to api.telegram.org)builder = builder.request(custom_request)logger.info(f" Using Cloudflare Worker proxy: {proxy_url}")application = builder.build()```**In your config file (e.g., config.py):**```pythonfrom pydantic_settings import BaseSettingsfrom typing import Optionalclass Settings(BaseSettings):TELEGRAM_BOT_TOKEN: strTELEGRAM_API_PROXY_URL: Optional[str] = None # Cloudflare Worker URL (from Railway Variables)```**Note:** The bot reads TELEGRAM_API_PROXY_URL from Railway Variables. If the variable is set, it uses the proxy. If not set, it uses direct connection to Telegram API.## Step 6: Set Environment Variable in Railway1. Go to Railway Dashboard2. Open your project3. Navigate to **Variables** (or **Environment Variables**)4. Click **"+ New Variable"**5. Add:- **Name:** TELEGRAM_API_PROXY_URL- **Value:** https://telegram-api-proxy.your-subdomain.workers.dev (your Worker URL from Step 4)6. Click **Save**Railway will automatically restart your service after adding the variable.## Step 7: Verify It's WorkingRailway automatically restarts your service after adding the variable. Check Railway logs for:```[CREATE_BOT] Используется Cloudflare Worker прокси: https://telegram-api-proxy.your-subdomain.workers.dev```or in English:```Using Cloudflare Worker proxy: https://telegram-api-proxy.your-subdomain.workers.dev```If you see this message, the proxy is working! Test your bot by sending a command.## Troubleshooting**Bot not responding?**1. Check Railway logs for errors2. Verify TELEGRAM_API_PROXY_URL is set correctly in Railway Variables3. Test Worker URL directly:```bashcurl https://telegram-api-proxy.your-subdomain.workers.dev/bot<your-token>/getMe```4. Check Worker logs in Cloudflare Dashboard → Workers & Pages → Your Worker → Logs**Need to disable proxy?**1. Go to Railway Dashboard → Your Project → Variables2. Delete the TELEGRAM_API_PROXY_URL variable3. Railway will restart the service automatically4. Bot will use direct connection to api.telegram.org

You can use the workaround steps from alpacco (THANK YOU BTW!) or- I spent some time trying to get this experience as one click as possible.

Update: the Railway team is still trying to get in contact with the TG team. We now have a one-click deploy that uses CF Workers to set up a proxy to allow you to proxy requests to get around the connection issue. You can use the above steps from

https://railway.com/deploy/tg-cloudflare-worker-proxy-workaround?referralCode=N8f7Nb&utm_medium=integration&utm_source=template&utm_campaign=generic


Status changed to Awaiting User Response Railway 9 days ago


alpacco

In my view, I support the idea that compensation should be provided to all affected parties. Today is New Year’s Day, and many people had their most important orders disrupted. I reported the problem yesterday, but it only started being addressed 12 hours later. The instructions shared by the user are incomplete, and it is currently quite difficult to understand and work with them. If everything had been explained step by step, it would have at least partially resolved the issue.

akobirismailov
HOBBY

8 days ago

I agree.

Any type of proxy is a workaround, I wasn’t ready to do on New Years eve.

I have my services here and expect that all of them will work.

I had active promotion for 2 my bots and the whole traffic was lost due to the Railway’s infrastructure problem, so I expect that Railway team would compensate all the problems, I had.


Status changed to Awaiting Railway Response Railway 8 days ago


butezyy
PRO

8 days ago

This has been going for too long, it's caused so many issues! Any updates?


brody
EMPLOYEE

7 days ago

We are waiting to hear back from Telegram.


Status changed to Awaiting User Response Railway 7 days ago


Loading...