3

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?

parsecer
  • 4,758
  • 13
  • 71
  • 140

3 Answers3

2

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)

Andre0512
  • 139
  • 1
  • 5
  • 1
    I took a look and it says you can pass a `@username` string. And I send message to a user like that earlier. – parsecer Aug 23 '19 at 00:43
  • 1
    No, you did read wrong @parsecer "Unique identifier for the target chat" _OR_ "Unique identifier for the target chat". – PythoNic Jan 31 '21 at 02:00
1

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()
mujad
  • 643
  • 7
  • 15
1

you need to change: chat_id = @myname fro a number de id. example: chat_ id = 43672587. this number you get. 1.- enter telegram 2.- search @userinfobot and enter 3.-In automatic you get you id