4

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

Rushikant Pawar
  • 428
  • 1
  • 5
  • 14

3 Answers3

6

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.

GriffoGoes
  • 715
  • 7
  • 17
Amit kumar
  • 2,169
  • 10
  • 25
  • 36
  • Kindly have a look over the edited question again and if possible please help – Rushikant Pawar Jul 26 '20 at 17:25
  • 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')` – Amit kumar Jul 26 '20 at 17:29
  • 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 based – Rushikant Pawar Jul 26 '20 at 17:35
  • Refer to this : https://core.telegram.org/bots/api#sendphoto . This should help you out. – Amit kumar Jul 26 '20 at 17:37
  • I seen that official sendPhoto parameters description .. I am not getting the basic implementation of that via python – Rushikant Pawar Jul 26 '20 at 17:39
  • `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. – Amit kumar Jul 26 '20 at 17:40
  • What is bot variable, How to initialise it, Which library to import? – Rushikant Pawar Jul 26 '20 at 17:43
  • 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. – Amit kumar Jul 26 '20 at 17:52
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)
The Thonnu
  • 3,578
  • 2
  • 8
  • 30
Arjun Sreepad
  • 155
  • 2
  • 9
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}")

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435