Introducing Livops 2.0! Promo codeCEOgives you 8,000 so‘m on your balance.What’s new

Telegram 401 Unauthorized, InvalidToken, TokenValidationError — how to fix the bot token

401 Unauthorized means Telegram does not accept your bot's token: it is mistyped, has a space, quote or newline around it, was replaced in @BotFather, belongs to a deleted bot, or never reached the server because the variable is not set. Call getMe with curl to see what Telegram says, put the current token from @BotFather in the variable, and start the bot again.

By Livops team, the people who build and run LivopsUpdated

The error, as the Telegram Bot API returns it for a token it does not accept:

{"ok":false,"error_code":401,"description":"Unauthorized"}

Each library wraps it in its own words:

Library What you see
aiogram 3 TelegramUnauthorizedError: Telegram server says - Unauthorized[8][9], or TokenValidationError: Token is invalid! before any request[5]
python-telegram-bot telegram.error.InvalidToken: The token ... was rejected by the server.[12]
grammY GrammyError: Call to 'getMe' failed! (401: Unauthorized)[13]
Telegraf TelegramError: 401: Unauthorized[15]

This page explains what the error means, shows how to check a token with one curl command, lists the causes from the most common, and ends with what to do if the token leaked and what Livops does when it sees this error.

What does the error mean?

Every Bot API request carries the token in its address: https://api.telegram.org/bot<token>/METHOD_NAME[1]. Each bot gets a unique token when it is created[1], and the token is what authorizes the bot to send requests[2]. A 401 means Telegram received the request and does not accept the token in it.

Two neighbouring errors look the same in a library’s log but come from somewhere else:

  • aiogram’s TokenValidationError is not from Telegram. Bot(...) checks the token’s shape before any request: it must be a string, contain no whitespace, and be digits, a colon, then more text[5][6]. Its messages are Token is invalid! It can't contains spaces. and Token is invalid![5]. aiogram’s error for Telegram’s 401 is TelegramUnauthorizedError[7][9].
  • python-telegram-bot’s InvalidToken covers 401 and 404. It is raised when the token is invalid[10], and the library’s own comments say Telegram returns 404 Not Found for malformed tokens and 401 Unauthorized for correctly formatted tokens that are not valid; it raises InvalidToken for both[11].

Several libraries ask for the bot’s own details with getMe when they start: grammY does it on startup[14], and python-telegram-bot’s initialize() does it and raises InvalidToken if the token is refused[12]. So a bad token usually stops the bot within seconds of starting.

Check the token with getMe

getMe is Telegram’s simple method for testing a bot’s token; it takes no parameters[1]. Telegram’s own tutorial suggests opening it in a browser[3]. From the machine where the bot runs, with the token from the same variable the bot reads:

curl -s "https://api.telegram.org/bot$BOT_TOKEN/getMe"
  • {"ok":true,"result":{...,"username":"your_bot",...}} — the token works. Check that username is the bot you expect; if it is, the 401 came from somewhere else, such as a different variable or a wrong base URL in the code.
  • {"ok":false,"error_code":401,"description":"Unauthorized"} — Telegram refuses this token. Go through the causes below.
  • {"ok":false,"error_code":404,"description":"Not Found"} — the URL is wrong: a path that does not start with /bot gets 404 Not Found from the Bot API server[4]. Look for the missing word bot, a space before the token, or an empty variable.

To see what is really in the variable, print it with its hidden characters:

python3 -c 'import os; print(repr(os.environ.get("BOT_TOKEN")))'
# None          -> not set
# '"123:AA..."' -> quotes inside the value
# '123:AA...\n' -> a newline at the end

Do not post the output anywhere: it is the token.

Causes, most common first

1. The variable is not set where the bot runs

The token is in .env on your computer, but the server never got it: .env is in .gitignore, or the variable has a different name there. python-telegram-bot raises InvalidToken: You must pass the token you received from https://t.me/Botfather! for an empty token[12], aiogram raises TokenValidationError for a token that is not a string, such as the None that os.getenv returns for a missing variable[5], and grammY throws Empty token![14]. Set the variable on the server under the exact name the code reads.

2. A space, quote or newline around the token

Copied with a trailing space, wrapped in quotes in a dashboard that keeps them, or read from a file that ends with a newline. aiogram refuses any whitespace inside the token[5]; the other libraries pass it on, and the request fails. Paste the token again without quotes, or strip it in code:

token = os.environ["BOT_TOKEN"].strip().strip('"').strip("'")

3. The token was replaced in @BotFather

/token in @BotFather generates a new token for a bot whose token was compromised or lost[2], and a token can be revoked at any time via @BotFather[3]. If you, a teammate or an old script did that, the copy on your server is the old one. Get the current token from @BotFather and update the variable.

4. The token belongs to a different or deleted bot

A token from another bot of yours, or from a bot removed with /deletebot — which cannot be undone[2]. getMe shows which bot a working token belongs to. A token from Telegram’s test environment belongs to a completely separate environment, with its own accounts and bots, and its requests go to https://api.telegram.org/bot<token>/test/METHOD_NAME[2]; use the main environment’s token with the main address.

5. The API base URL is wrong

The word bot goes right before the token: https://api.telegram.org/bot<token>/getMe[1][2]. Building the URL by hand without it gives 404 Not Found[4], which python-telegram-bot reports as InvalidToken[11].

The same happens with a local Bot API server, which you can run and send requests to instead of https://api.telegram.org[1]. python-telegram-bot’s base_url defaults to https://api.telegram.org/bot and the token is appended to it[12], so a custom one must end in /bot too, for example http://localhost:8081/bot. Before moving to a local server, the bot must call logOut; after that it cannot log back in to the cloud Bot API server for 10 minutes[1].

How to fix it

  1. Open @BotFather and get the current token for the bot (/token generates a new one[2]).
  2. Put it in the variable the code reads, with no quotes and no spaces, on the machine or platform where the bot runs. Keep it out of the repository; Telegram’s tutorial advises environment variables over keeping it in code[3].
  3. Run the getMe check above with that variable. Go on only when it returns "ok":true and the right username.
  4. Restart the bot, and make sure only one copy runs: two copies with one token give 409 Conflict instead.

If the token leaked

The token can be used by anyone to control your bot, so keep it secure[2] and treat it like a password[3]. Never paste it into a public paste site, a chat, a screenshot or a repository — .env files and old commits included.

Logs leak it too. python-telegram-bot’s startup error includes the token itself in its message (The token ... was rejected by the server.)[12], so a traceback copied into a forum shares it. aiogram keeps the token out of its network errors, but the original exception it keeps may contain it, and aiogram advises not to log that[7].

If it leaked, send /token to @BotFather, generate a new token[2], put the new one in the variable, and restart the bot. Then check the bot’s description, commands and webhook for changes you did not make.

On Livops

  • The token is checked when you create the bot. In a new bot project, paste the token into the Bot token field and press Check: the cabinet asks Telegram and shows the bot’s username, or tells you Telegram does not accept the token, before anything is built.
  • The token is a variable. It lives under Settings → Variables, often as BOT_TOKEN, with no quotes. Mark it as a secret and its value is never shown again, only its name. New values take effect on the next deploy; restart the service to apply one now. See Variables.
  • A refused token fails the deploy. If the bot stops right after it starts and its log says TokenValidationError or InvalidToken, the deploy fails as start_failed and the Logs page adds a Tip: line — the bot’s token is empty or wrong; put the token BotFather gave you in Variables under the name the code reads. A missing variable shows up as KeyError: 'BOT_TOKEN'. See The app did not start. A bot’s old version is stopped before the new one starts, so the bot stays down until a deploy succeeds.
  • A token revoked later is reported. If Telegram starts refusing the token while the bot runs, the project page stops showing the bot as working and you get a notification: the bot is not answering, Telegram rejected your token; get the current token from @BotFather, put it in Variables → BOT_TOKEN and press Deploy.
  • The assistant never sees the value. It sees variable names, not values, so it can point at a missing BOT_TOKEN but not at a wrong one; the getMe check above is how you tell.

A bot costs 19 credits a month (19,000 so’m); see Pricing.

Questions

What does 401 Unauthorized mean for a Telegram bot?

Telegram received a request with a token it does not accept. The token is mistyped, cut short, has a space or a quote in it, was replaced with a new one in @BotFather, or belongs to a bot that was deleted. The code is usually fine; the token is not.

How do I check if my bot token is valid?

Call getMe: curl https://api.telegram.org/bot<token>/getMe with your token in place of <token>. A valid token returns ok true and the bot's username; a rejected one returns error_code 401 and Unauthorized. Run it on the machine where the bot runs, with the token from the same variable the bot reads.

What is the difference between TokenValidationError and 401 Unauthorized in aiogram?

TokenValidationError comes from aiogram itself, before any request: the token is empty, not a string, contains whitespace, or is not digits, a colon and more text. TelegramUnauthorizedError is Telegram's own 401, for a token of the right shape that Telegram does not accept.

Why do I get 404 Not Found instead of 401?

Usually the URL is wrong rather than the token. Every Bot API URL is https://api.telegram.org/bot<token>/METHOD, and a path without the word bot before the token gets 404 Not Found. python-telegram-bot reports a 404 as InvalidToken too, so check the base URL when you use a local Bot API server.

My token leaked. What do I do?

Send /token to @BotFather to generate a new token, then put the new one wherever the bot runs and restart it. Anyone with the old token could control the bot, so do this even if you only pasted it for a minute.

Can a new token fix 401 Unauthorized?

Yes, when the old one was replaced or leaked. Get the current token from @BotFather, update the variable the bot reads, and restart or redeploy. If the new token is refused too, look for a space, quote or newline around it, or a wrong API URL.

Sources

  1. Telegram Bot API — Authorizing your bot, Making requests, getMe, logOut, Local Bot API Server (core.telegram.org). Checked .
  2. Telegram — Bot features (BotFather, tokens, test environment) (core.telegram.org). Checked .
  3. Telegram — From BotFather to 'Hello World' (core.telegram.org). Checked .
  4. Telegram Bot API server source — telegram-bot-api/HttpConnection.cpp (raw.githubusercontent.com). Checked .
  5. aiogram source — aiogram/utils/token.py (raw.githubusercontent.com). Checked .
  6. aiogram source — aiogram/client/bot.py (raw.githubusercontent.com). Checked .
  7. aiogram — Errors (docs.aiogram.dev). Checked .
  8. aiogram source — aiogram/exceptions.py (raw.githubusercontent.com). Checked .
  9. aiogram source — aiogram/client/session/base.py (raw.githubusercontent.com). Checked .
  10. python-telegram-bot — telegram.error (docs.python-telegram-bot.org). Checked .
  11. python-telegram-bot source — telegram/request/_baserequest.py (raw.githubusercontent.com). Checked .
  12. python-telegram-bot source — telegram/_bot.py (raw.githubusercontent.com). Checked .
  13. grammY source — src/core/error.ts (raw.githubusercontent.com). Checked .
  14. grammY source — src/bot.ts (raw.githubusercontent.com). Checked .
  15. Telegraf source — src/core/network/error.ts (raw.githubusercontent.com). Checked .

Put your project online today

Connect GitHub or drop a folder. No card is asked for.

Deploy your bot

Got a question? — @livops_uz