Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Telegram can get chat by id, can't by @name: Chat not found

So I've made a bot using @BotFather and I messaged it from my account. Then I found out the id of my account using @userinfobot and sent this request:

https://api.telegram.org/botTOKEN/sendMessage?chat_id=id&text=test and it works fine ok:true.

However if I try to use my @username instead of id:

https://api.telegram.org/botTOKENg/sendMessage?chat_id=@username&text=test

I get an error:

{
    "ok": false,
    "error_code": 400,
    "description": "Bad Request: chat not found"
}

Looking at my past code, the @ method used to work for me before. Have things changed?

like image 538
parsecer Avatar asked Nov 05 '25 20:11

parsecer


2 Answers

You have to use the id, you cannot use the username.

Giving the username as parameter does only work for public channels.

Have a look at the Telegram Bot API documentation:

Description
Unique identifier for the target chat or username of the target channel (in the format @channelusername)

like image 154
Andre0512 Avatar answered Nov 08 '25 11:11

Andre0512


you can't send message with username you should to use of bot updates and get from_user or effective_user then access to id (chat_id)

  • you can't send message to user who never used your bot.

after user doing some action in your bot now you can find and send every thing you want

import requests
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

def pure_api(chat_id, text):
    # don't forget to set bot + TOKEN
    r = requests.get(f"https://api.telegram.org/botTOKEN/sendMessage?chat_id={chat_id}&text={text}")
    print(r.json())

def start(bot, update):
    user_id = update.effective_user.id
    print(user_id)
    bot.send_message(user_id, "any message you want")
    # or 
    update.message.reply_text("any message you want")
    pure_api(user_id, "any message you want")


def main():
    """Start the bot."""
    updater = Updater(TOKEN)
    dp = updater.dispatcher
    dp.add_handler(CommandHandler("start", start))
    updater.start_polling()
    updater.idle()


if __name__ == '__main__':
    main()
like image 23
mujad Avatar answered Nov 08 '25 11:11

mujad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!