Rushikant Pawar
Rushikant Pawar

Reputation: 458

Send text message via python to the Telegram Bot

I have been trying since the morning but earlier there were errors, so i had the direction but now there is no error and even not a warning too..

How code looks like :

import requests

def send_msg(text):
token = "TOKEN"
chat_id = "CHATID"
url_req = "https://api.telegram.org/bot" + token + "/sendMessage" + "?chat_id=" + chat_id + "&text=" + text 
results = requests.get(url_req)
print(results.json())

send_msg("hi there 1234")

What is expected output : It should send a text message

What is the current output : It prints nothing

It would be great help is someone helps, Thank you all

Edit : 2

As the below dependancies were not installed, it was not capable of sending the text .

$ pip install flask
$ pip install python-telegram-bot
$ pip install requests

Now can somebody help me with sendPhoto please? I think it is not capable of sending image via URL, Thank you all

**Edit 3 **

I found a image or video sharing url from here but mine image is local one and not from the remote server

Upvotes: 6

Views: 24905

Answers (3)

Arjun Sreepad
Arjun Sreepad

Reputation: 155

This works for me:

import telegram
#token that can be generated talking with @BotFather on telegram
my_token = ''

def send(msg, chat_id, token=my_token):
    """
    Send a mensage to a telegram user specified on chatId
    chat_id must be a number!
    """
    bot = telegram.Bot(token=token)
    bot.sendMessage(chat_id=chat_id, text=msg)

Upvotes: 1

Amit kumar
Amit kumar

Reputation: 2694

There is nothing wrong with your code. All you need to do is proper indentation.

This error primarily occurs because there are space or tab errors in your code. Since Python uses procedural language, you may experience this error if you have not placed the tabs/spaces correctly.

Run the below code. It will work fine :

import requests

def send_msg(text):
   token = "your_token"
   chat_id = "your_chatId"
   url_req = "https://api.telegram.org/bot" + token + "/sendMessage" + "?chat_id=" + chat_id + "&text=" + text 
   results = requests.get(url_req)
   print(results.json())

send_msg("Hello there!")

To send a picture might be easier using bot library : bot.sendPhoto(chat_id, 'URL')

Note : It's a good idea to configure your editor to make tabs and spaces visible to avoid such errors.

Upvotes: 7

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83768

Here is an example that correctly encoded URL parameters using the popular requests library. This is a simple method if you simply want to send out plain-text or Markdown-formatted alert messages.

import requests


def send_message(text):
    token = config.TELEGRAM_API_KEY
    chat_id = config.TELEGRAM_CHAT_ID

    url = f"https://api.telegram.org/bot{token}/sendMessage"
    params = {
       "chat_id": chat_id,
       "text": text,
    }
    resp = requests.get(url, params=params)

    # Throw an exception if Telegram API fails
    resp.raise_for_status()

For full example and more information on how to set up a Telegram bot for a group chat, see README here.

Below is also the same using asyncio and aiohttp client, with throttling the messages by catching HTTP code 429. Telegram will kick out the bot if you do not throttle correctly.

import asyncio
import logging

import aiohttp

from order_book_recorder import config


logger = logging.getLogger(__name__)


def is_enabled() -> bool:
    return config.TELEGRAM_CHAT_ID and config.TELEGRAM_API_KEY


async def send_message(text, throttle_delay=3.0):
    token = config.TELEGRAM_API_KEY
    chat_id = config.TELEGRAM_CHAT_ID

    url = f"https://api.telegram.org/bot{token}/sendMessage"
    params = {
       "chat_id": chat_id,
       "text": text,
    }

    attempts = 10

    while attempts >= 0:
        async with aiohttp.ClientSession() as session:
            async with session.get(url, params=params) as resp:
                if resp.status == 200:
                    return
                elif resp.status == 429:
                    logger.warning("Throttling Telegram, attempts %d", attempts)
                    attempts -= 1
                    await asyncio.sleep(throttle_delay)
                    continue
                else:
                    logger.error("Got Telegram response: %s", resp)
                    raise RuntimeError(f"Bad HTTP response: {resp}")

Upvotes: 1

Related Questions