python - 如何通过 HTTP 向 Telegram 机器人发送文件?

标签 python python-3.x python-requests telegram

我想通过 http Telegram API 发送文件并尝试以下代码:

def send_media(self, chat_id, doc):
    method = 'sendDocument'
    params = {'chat_id': chat_id, 'document': doc}
    resp = requests.post(self.api_url + method, params)
    return resp
 document = open('table.csv', 'rb')
 doc = InputFile(document)
 bot.send_media(last_chat_id, doc).json()
 document.close()

并根据要求出现这样的错误:

 {'ok': False, 'error_code': 400, 'description': 'Bad Request: wrong URL host'}

我应该怎么做才能发送文件?

最佳答案

这里的问题是requests库的错误使用,如果您发送multipart/form-data和文件,您应该使用参数files.

例如

requests.post(self.api_url + method, data={'chat_id': chat_id}, files={'document': document})

文档链接 - http://docs.python-requests.org/en/master/user/quickstart/#post-a-multipart-encoded-file

关于python - 如何通过 HTTP 向 Telegram 机器人发送文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54809400/

相关文章:

python - 套接字错误 : [Errno 54] Connection reset by peer Selenium-python

python - 是否有更短的方法或 pythonic 方法来生成遵循使用 BeautifulSoup 模式的自定义 html?

python - 使用 python requests-HTML 获取标签的父元素

python - 将请求response.content放入队列后multiprocessing.Process不会终止

Python请求图片上传HTTP POST

python - 从跨度类 XPath 检索值

python - 如何在 Python 中通过 Tor 发出 urllib2 请求?

python-3.x - 将字典键和值添加到 Redis 列表

python - 将 POST 从请求转换为 GAE urlfetch

python - 被 GradientBoostingClassifier 的 apply 函数搞糊涂了