skip to Main Content

I sending post to teleram Channel via Requests lib and i need to add Enter for better formate in channel and i use n at the end of lines but it dosen’t work is there any idea for this

This is my code

import requests

def Telegram_channel (x):
    url = "https://api.telegram.org/bot<token>/sendMessage"
    data = {"chat_id":"-USER_id", "text":x}
    r = requests.post(url, json=data)


x = ">>>> length of Tv packs banned in Database : n"

x = x,">>>> Torrent Link DB value ",torrent_link,'n'

Telegram_channel (x)

and the result is :

>>>> length of Tv packs banned in Database  n>>>> Torrent Link DB value n

but it should be like this

>>>> length of Tv packs banned in Database 

>>>> Torrent Link DB value

2

Answers


  1. Try below :

    Basically the parameter you need to send in this api, in query params, and actually you are sending them in body, so please send in query string and enjoy coding.

    URL :
    https://api.telegram.org/bot%5BBOT_API_KEY%5D/sendMessage?chat_id=%5BMY_CHANNEL_NAME%5D&text=%5BMY_MESSAGE_TEXT%5D

    METHOD : GET
    where:

    • BOT_API_KEY is the API Key generated by BotFather when you created
      your bot
    • MY_CHANNEL_NAME is the handle of your channel (e.g.
      @my_channel_name)
    • MY_MESSAGE_TEXT is the message you want to send
      (URL-encoded)
    Login or Signup to reply.
  2. You are actually creating a tuple instead of str (which text JSON parameter should be):

    x = ">>>> length of Tv packs banned in Database : n"
    x = x,">>>> Torrent Link DB value ","torrent_link_text_here",'n'
    print(type(x))
    print(x)
    

    Output:

    <class 'tuple'>
    ('>>>> length of Tv packs banned in Database : n', '>>>> Torrent Link DB value ', 'torrent_link_text_here', 'n')
    

    Requests lib cannot treat it correctly to construct an HTTP request, so you lose line breaks.


    Why not use string formatting?

    import requests
    
    url = "https://api.telegram.org/bot<TOKEN>/sendMessage"
    torrent_link = "https://example.com"
    x = ">>>> length of Tv packs banned in Database: n>>>> Torrent Link DB value {}n".format(torrent_link)
    
    data = {"chat_id": <YOUR_CHAT_ID>, "text": x}
    r = requests.post(url, json=data)
    
    

    Chat output:

    >>>> length of Tv packs banned in Database:  
    >>>> Torrent Link DB value https://example.com
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search