I just want to send a simple message from bot to a user in python by using telebot library. I wrote the code like the followings.
import telebot
bot = telebot.TeleBot(token="BOT_TOKEN")
username = "@keiru"
bot.send_message(username, "Hello, World!")
But this code gives me error like this
raise ApiTelegramException(method_name, result, result_json) telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 400. Description: Bad Request: chat not found
But if I use chat_id like this,
import telebot
bot = telebot.TeleBot(token="BOT_TOKEN")
bot.send_message(5*91*2*728, "Hello, World!")
it works.
So what I want to do is to get chat_id from the username because I have list of usernames and need to send messages.
Please help me how to get chat_id from the username. I have already tried to use get_chat() method like this
chat_info = bot.get_chat(username)
chat_id = chat_info.id
But this didn't work.
You can't get ChatID
from username: It's telegram privacy policy. The only way you can obtain user's ID is from their message:
# Assume msg is variable holding your message object
user_id = msg.chat.id
bot.send_message(user_id, "Hello, World!")
Personally I always keep user_id
- usernames
pairs for all users that have ever written to bot in some kind of local database.