如何设置Enter in来按摩通过请求发送到Telegram Channel的消息

时间:2019-05-07 23:17:07

标签: python request telegram telegram-bot python-telegram-bot

我通过Requests lib将帖子发送到teleram Channel,我需要添加Enter以获得更好的频道,并且我在行尾使用\n,但这没有用

这是我的代码

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)

结果是:

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

但是应该是这样

>>>> length of Tv packs banned in Database 

>>>> Torrent Link DB value

2 个答案:

答案 0 :(得分:1)

您实际上是在创建tuple而不是str(应该是text JSON参数):

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)

输出:

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

请求库不能正确地处理它以构造HTTP请求,因此您会丢失换行符。


为什么不使用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)

聊天输出:

>>>> length of Tv packs banned in Database:  
>>>> Torrent Link DB value https://example.com

答案 1 :(得分:0)

尝试以下方法:

基本上是您需要在此API中以查询参数形式发送的参数,而实际上您是在正文中发送它们,因此请发送查询字符串并享受编码。

URL: https://api.telegram.org/bot[BOT_API_KEY]/sendMessage?chat_id=[MY_CHANNEL_NAME]&text=[MY_MESSAGE_TEXT]

方法:获取 其中:

  • BOT_API_KEY 是BotFather在创建时生成的API密钥 您的机器人
  • MY_CHANNEL_NAME 是您频道的句柄(例如 @my_channel_name)
  • MY_MESSAGE_TEXT 是您要发送的邮件 (URL编码)
相关问题