skip to Main Content

I have tried sending message to a telegram channel using Telegram’s BOT API with Python 3.11.0.

At first I have tried making the channel Public and the code worked fine:

import requests

# Replace YOUR_BOT_TOKEN with your actual bot token
bot_token = BOT_API_KEY

# Replace YOUR_CHAT_ID with the chat ID of the recipient
chat_id = '@testme100'

# The message you want to send
text = 'Hello, world!'

# The URL for the Telegram Bot API
url = f'https://api.telegram.org/bot{bot_token}/sendMessage'

# The data to be sent in the POST request
data = {'chat_id': chat_id, 'text': text}

# Send the POST request
response = requests.post(url, data=data)

# Check the response status code
if response.status_code == 200:
    print('Message sent successfully.')
else:
    print(f'Error sending message: {response.text}')

The output:
output of the code

But then I thought of making it private channel and changed the Channel ID:
The URL is : https://t.me/+vMjFCXBghv00NDZl and I thought the text ahead of + is the channel ID, so I changed the chat_id = '@vMjFCXBghv00NDZl'.

But now it’s not sending the messages to the channel. When I make it public again then it works fine.

The error I received = Error sending message: {"ok":false,"error_code":400,"description":"Bad Request: chat not found"}

2

Answers


  1. The invite link is not the same as the chat_id.

    Public channels do allow sending messages using the @channel-name, but that’s not a replacement of the chat_id, that will still work.

    To send messages from the bot to the private channel, you can only use the chat_id.

    There are tons of ways of getting this, I always forward a message from the channel to an echo bot (one that just response with the json from Telegram).

    (For example, this bot: https://t.me/chatIDrobot, the first you find if you search for ‘echo bot’)

    Then use the ID provided to send messages

    Login or Signup to reply.
  2. If anyone is still wondering, send_message(int(channel_id), "message") works absolutely fine with

    channel_id = "-100123456789"
    or
    channel_id = "123456789"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search