Send text message via python to the Telegram Bot
Asked Answered
V

3

6

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

Valenciavalenciennes answered 26/7, 2020 at 16:52 Comment(1)
Try bot.sendPhoto(chat_id, 'URL') to send photos.Picard
P
7

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.

Picard answered 26/7, 2020 at 17:23 Comment(8)
Kindly have a look over the edited question again and if possible please helpValenciavalenciennes
Replace your_token and your_chatId with the one you are using and it will work. Let me know if you are still facing issues after trying it. To send photos try : bot.sendPhoto(chat_id, 'URL')Picard
I am successfully abled to send a text message, but not getting how to change it to be able to send photo as i am using url_req and actually do not want it to be url basedValenciavalenciennes
Refer to this : core.telegram.org/bots/api#sendphoto . This should help you out.Picard
I seen that official sendPhoto parameters description .. I am not getting the basic implementation of that via pythonValenciavalenciennes
bot.send_photo(chat_id=chat_id, photo=open('tests/test.png', 'rb')) . Just replace tests/test.png with the image that you have in your local.Picard
What is bot variable, How to initialise it, Which library to import?Valenciavalenciennes
Install or upgrade python-telegram-bot with : $ pip install python-telegram-bot --upgrade. I suggest you to first go through the documentation to have better understanding about the telegram bot.Picard
M
1

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)
Mezereum answered 26/7, 2020 at 16:56 Comment(1)
Start all code lines with at 4 spaces to preserve formatting.Visage
C
1

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}")

Clever answered 13/10, 2021 at 13:25 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.