· 4 years ago · Jul 23, 2021, 07:56 PM
1--- Provides a pastebin api to interact with pastebin without using the pastebin shell command.
2-- @module[kind=misc] pastebin
3
4local function extractId(paste)
5 local patterns = {
6 "^([%a%d]+)$",
7 "^https?://pastebin.com/([%a%d]+)$",
8 "^pastebin.com/([%a%d]+)$",
9 "^https?://pastebin.com/raw/([%a%d]+)$",
10 "^pastebin.com/raw/([%a%d]+)$",
11 }
12
13 for i = 1, #patterns do
14 local code = paste:match(patterns[i])
15 if code then return code end
16 end
17
18 return nil
19end
20
21--- Get a string from pastebin.
22-- @tparam string id The paste id that you want to download.
23-- @treturn string|nil The string containing the paste, or nil.
24-- @treturn nil|string The reason why it couldn't be retrieved.
25local function get(url)
26 local paste = extractId(url)
27 if not paste then
28 return nil, "invalid"
29 end
30 -- Add a cache buster so that spam protection is re-checked
31 local cacheBuster = ("%x"):format(math.random(0, 2 ^ 30))
32 local response, err = http.get(
33 "https://pastebin.com/raw/" .. textutils.urlEncode(paste) .. "?cb=" .. cacheBuster
34 )
35
36 if response then
37 -- If spam protection is activated, we get redirected to /paste with Content-Type: text/html
38 local headers = response.getResponseHeaders()
39 if not headers["Content-Type"] or not headers["Content-Type"]:find("^text/plain") then
40 return nil, "captcha"
41 end
42
43 local sResponse = response.readAll()
44 response.close()
45 return sResponse
46 else
47 return nil, err
48 end
49end
50
51--- Put a string on pastebin.
52-- @tparam string string The string that you want to put on pastebin.
53-- @tparam[opt] string name The name of the paste, defaults to "CC:T Paste".
54-- @treturn string|nil A string containing the id of the paste.
55local function put(sText, sName)
56 sName = sName or "CC:T Paste"
57 -- Upload a file to pastebin.com
58
59 -- POST the contents to pastebin
60 local key = "0ec2eb25b6166c0c27a394ae118ad829"
61 local response = http.post(
62 "https://pastebin.com/api/api_post.php",
63 "api_option=paste&" ..
64 "api_dev_key=" .. key .. "&" ..
65 "api_paste_format=lua&" ..
66 "api_paste_name=" .. textutils.urlEncode(sName) .. "&" ..
67 "api_paste_code=" .. textutils.urlEncode(sText)
68 )
69
70 if response then
71
72 local sResponse = response.readAll()
73 response.close()
74
75 local sCode = string.match(sResponse, "[^/]+$")
76 return sCode
77 else
78 return nil
79 end
80end
81
82return {
83 get = get,
84 put = put,
85}