Python3 urllib不协调与Slack机器人

Python3 urllib不协调与Slack机器人,python,discord,webhooks,slack-api,Python,Discord,Webhooks,Slack Api,我有一个简单的python脚本,它应该在Slack上向我发送一条消息,它工作得很好 #/usr/bin/python 从urllib.request导入请求,urlopen 导入json #提供生成的webhook URL slack\u webhook\u url=https://hooks.slack.com/services/josadfs/nfonwnfoawf/abcdsads' #将消息发布到slack webhook 消息={ “文本”:“你好,世界” } req=请求(slack

我有一个简单的python脚本,它应该在Slack上向我发送一条消息,它工作得很好

#/usr/bin/python
从urllib.request导入请求,urlopen
导入json
#提供生成的webhook URL
slack\u webhook\u url=https://hooks.slack.com/services/josadfs/nfonwnfoawf/abcdsads'
#将消息发布到slack webhook
消息={
“文本”:“你好,世界”
}
req=请求(slack\u webhook\u url,json.dumps(message.encode('utf-8'))
响应=urlopen(请求)
回复:read()
我有另一个脚本,它做同样的事情,只是为了不和谐

#/usr/bin/python
从urllib.request导入请求,urlopen
导入json
#提供生成的webhook URL
slack\u webhook\u url=https://discordapp.com/api/webhooks/252534154132/knskdnvoangoe0940507230'
#将消息发布到slack webhook
消息={
“内容”:“你好,世界”
}
req=请求(slack\u webhook\u url,json.dumps(message.encode('utf-8'))
响应=urlopen(请求)
回复:read()
出于某种原因,这给了我一个
httperror403:probled
错误

curl
命令都可以工作,因此这不是API关键问题。不过,discord脚本在使用requests模块时可以工作

#/usr/bin/python
导入json
导入请求
#提供Discord生成的webhook URL
不和谐的网络钩子https://discordapp.com/api/webhooks/252534154132/knskdnvoangoe0940507230'
#将消息发布到Discord webhook
数据={
“内容”:“你好,世界”
}
requests.post(discord\u webhook\u url,data=data)

我的urllib实现是否有问题?是否可以使用urllib发送discord请求?

discord似乎会阻止来自Python urllib的默认用户代理的请求。通过使用Request.add_header()指定用户代理和内容类型,我成功地执行了代码。我测试了下面的代码,它对我有效

#!/usr/bin/python

from urllib.request import Request, urlopen
import json

# Provide the webhook URL that slack generated
slack_webhook_url = '<redacted>'

# Post the message to the slack webhook
message = {
    "content": "Hello world"
}

req = Request(slack_webhook_url, json.dumps(message).encode('utf-8'))

#specifying headers for the request, discord appears to block the  default urllib user-agent
req.add_header('Content-Type', 'application/json')
req.add_header('User-Agent', 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11')

response = urlopen(req)
response.read()
#/usr/bin/python
从urllib.request导入请求,urlopen
导入json
#提供生成的webhook URL
slack_webhook_url=“”
#将消息发布到slack webhook
消息={
“内容”:“你好,世界”
}
req=请求(slack\u webhook\u url,json.dumps(message.encode('utf-8'))
#指定请求的标题时,discord会阻止默认的urllib用户代理
请求添加标题('Content-Type','application/json')
请求添加标题(“用户代理”、“Mozilla/5.0(X11;U;Linux i686)Gecko/20071127 Firefox/2.0.0.11”)
响应=urlopen(请求)
回复:read()

问题中没有提到电报,为什么标题上写着电报?对不起!那是个打字错误。我也试过用电报,但它也有类似的问题,不和谐。永远的答案!非常感谢。