如何使用 io.read 从 Lua 向 Webhook 发送消息
How to send messages to Webhook from Lua using io.read
Webhook 需要它,这样我就不会因为编辑而感到厌烦
local message = [[ {"username":"example","avatar_url": "example.com","content": (where io.read will be content)
通过使用 ]] 和 [[ 和 concat (..) 就像...
Lua 5.3.5 Copyright (C) 1994-2018 Lua.org, PUC-Rio
> message = [[ {"username":"example","avatar_url": "example.com","content":"]] .. io.read() .. [["}]]
content
> print(message)
{"username":"example","avatar_url": "example.com","content":"content"}
在 io.read()...
之前输出一些东西(提示)时看起来也更好
io.write('Content: ')
local message = [[ {"username":"example","avatar_url": "example.com","content":"]] .. io.read() .. [["}]]
print(message)
Discord webhooks 使用 JSON。您可以使用 JSON 库,例如 lunajson 来正确转义您的输入。它是用纯 Lua 编写的,因此在 Lua 可用时始终可以使用(不需要任何 C 库/编译/复杂安装)。
local lunajson = require"lunajson"
local content = io.read()
local json_message = lunajson.encode{
username = "example",
avatar_url = "example.com",
content = content
}
如您所见,这也使您的代码更具可读性(您使用 JSON 编码的 table 得到语法高亮显示)。
不要使用简单的字符串插值:当使用引号时它会中断(这在英语消息中很常见)并且可能被滥用来发送与您预期不同的请求.
如果出于某种原因你不想使用 lunajson,坚持使用错误的字符串操作,至少转义你的输入以删除双引号;您也不需要长字符串 [[...]]
,单引号就足够了,string.format
进一步有助于提高可读性:
-- HACK don't do this
local content = io.read()
local json_message = ('{"username":"example","avatar_url":"example.com","content": "%s"}'):format(content:gsub('"', '\"'))
另请注意,"example.com"
指向网页而不是图像文件。
Webhook 需要它,这样我就不会因为编辑而感到厌烦
local message = [[ {"username":"example","avatar_url": "example.com","content": (where io.read will be content)
通过使用 ]] 和 [[ 和 concat (..) 就像...
Lua 5.3.5 Copyright (C) 1994-2018 Lua.org, PUC-Rio
> message = [[ {"username":"example","avatar_url": "example.com","content":"]] .. io.read() .. [["}]]
content
> print(message)
{"username":"example","avatar_url": "example.com","content":"content"}
在 io.read()...
之前输出一些东西(提示)时看起来也更好io.write('Content: ')
local message = [[ {"username":"example","avatar_url": "example.com","content":"]] .. io.read() .. [["}]]
print(message)
Discord webhooks 使用 JSON。您可以使用 JSON 库,例如 lunajson 来正确转义您的输入。它是用纯 Lua 编写的,因此在 Lua 可用时始终可以使用(不需要任何 C 库/编译/复杂安装)。
local lunajson = require"lunajson"
local content = io.read()
local json_message = lunajson.encode{
username = "example",
avatar_url = "example.com",
content = content
}
如您所见,这也使您的代码更具可读性(您使用 JSON 编码的 table 得到语法高亮显示)。
不要使用简单的字符串插值:当使用引号时它会中断(这在英语消息中很常见)并且可能被滥用来发送与您预期不同的请求.
如果出于某种原因你不想使用 lunajson,坚持使用错误的字符串操作,至少转义你的输入以删除双引号;您也不需要长字符串 [[...]]
,单引号就足够了,string.format
进一步有助于提高可读性:
-- HACK don't do this
local content = io.read()
local json_message = ('{"username":"example","avatar_url":"example.com","content": "%s"}'):format(content:gsub('"', '\"'))
另请注意,"example.com"
指向网页而不是图像文件。