Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
294 views
in Technique[技术] by (71.8m points)

python - How to format HTTP request to discord API?

While this code works, it sends "Bad Request".

import socket, ssl
token = 'NzMyMzQ1MTcwNjK2MTR5OEU3.XrzQug.BQzbrckR-THB9eRwZi3Dn08BWrM'
HOST = "discord.com"
PORT = 443
t = 'POST / HTTP/1.0
Authentication: Bot {token}
Host: discord.com/api/guilds/{702627382091186318}/channels

'
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s_sock = context.wrap_socket(s, server_hostname=HOST)
s_sock.connect((HOST, 443))
s_sock.sendall(t.encode())

f = s_sock.recv(7000).decode()
print(f)

s_sock.close()

Note: this is not a real token.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
t = 'POST / HTTP/1.0
Authentication: Bot {token}
Host: discord.com/api/guilds/{702627382091186318}/channels

'

This is not a valid HTTP request. You essentially send (line breaks added for clarity):

 POST / HTTP/1.0

 Authentication: Bot {token}

 Host: discord.com/api/guilds/{702627382091186318}/channels

 

But a correct POST request would look like this instead:

 POST /api/guilds/{702627382091186318}/channels HTTP/1.0

 Authentication: Bot {token}

 Host: discord.com

 Content-length: ...
 

 <body, where size matches Content-length header>

I.e. you have the wrong path, wrong Host header, missing body and missing Content-length header. If you really want to write your own HTTP stack instead of using existing libraries please study the standards instead of just guessing how it might look - that what standards are for.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...