commands_botinteraction.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. // mautrix-discord - A Matrix-Discord puppeting bridge.
  2. // Copyright (C) 2023 Tulir Asokan
  3. //
  4. // This program is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. package main
  17. import (
  18. "fmt"
  19. "strconv"
  20. "strings"
  21. "time"
  22. "github.com/bwmarrin/discordgo"
  23. "github.com/google/shlex"
  24. "maunium.net/go/mautrix/bridge/commands"
  25. )
  26. var cmdCommands = &commands.FullHandler{
  27. Func: wrapCommand(fnCommands),
  28. Name: "commands",
  29. Aliases: []string{"cmds", "cs"},
  30. Help: commands.HelpMeta{
  31. Section: commands.HelpSectionUnclassified,
  32. Description: "View parameters of bot interaction commands on Discord",
  33. Args: "search <_query_> OR help <_command_>",
  34. },
  35. RequiresPortal: true,
  36. RequiresLogin: true,
  37. }
  38. var cmdExec = &commands.FullHandler{
  39. Func: wrapCommand(fnExec),
  40. Name: "exec",
  41. Aliases: []string{"command", "cmd", "c", "exec", "e"},
  42. Help: commands.HelpMeta{
  43. Section: commands.HelpSectionUnclassified,
  44. Description: "Run bot interaction commands on Discord",
  45. Args: "<_command_> [_arg=value ..._]",
  46. },
  47. RequiresLogin: true,
  48. RequiresPortal: true,
  49. }
  50. func (portal *Portal) getCommand(user *User, command string) (*discordgo.ApplicationCommand, error) {
  51. portal.commandsLock.Lock()
  52. defer portal.commandsLock.Unlock()
  53. cmd, ok := portal.commands[command]
  54. if !ok {
  55. results, err := user.Session.ApplicationCommandsSearch(portal.Key.ChannelID, command)
  56. if err != nil {
  57. return nil, err
  58. }
  59. for _, result := range results {
  60. if result.Name == command {
  61. portal.commands[result.Name] = result
  62. cmd = result
  63. break
  64. }
  65. }
  66. if cmd == nil {
  67. return nil, nil
  68. }
  69. }
  70. return cmd, nil
  71. }
  72. func getCommandOptionTypeName(optType discordgo.ApplicationCommandOptionType) string {
  73. switch optType {
  74. case discordgo.ApplicationCommandOptionSubCommand:
  75. return "subcommand"
  76. case discordgo.ApplicationCommandOptionSubCommandGroup:
  77. return "subcommand group (unsupported)"
  78. case discordgo.ApplicationCommandOptionString:
  79. return "string"
  80. case discordgo.ApplicationCommandOptionInteger:
  81. return "integer"
  82. case discordgo.ApplicationCommandOptionBoolean:
  83. return "boolean"
  84. case discordgo.ApplicationCommandOptionUser:
  85. return "user (unsupported)"
  86. case discordgo.ApplicationCommandOptionChannel:
  87. return "channel (unsupported)"
  88. case discordgo.ApplicationCommandOptionRole:
  89. return "role (unsupported)"
  90. case discordgo.ApplicationCommandOptionMentionable:
  91. return "mentionable (unsupported)"
  92. case discordgo.ApplicationCommandOptionNumber:
  93. return "number"
  94. case discordgo.ApplicationCommandOptionAttachment:
  95. return "attachment (unsupported)"
  96. default:
  97. return fmt.Sprintf("unknown type %d", optType)
  98. }
  99. }
  100. func parseCommandOptionValue(optType discordgo.ApplicationCommandOptionType, value string) (any, error) {
  101. switch optType {
  102. case discordgo.ApplicationCommandOptionSubCommandGroup:
  103. return nil, fmt.Errorf("subcommand groups aren't supported")
  104. case discordgo.ApplicationCommandOptionString:
  105. return value, nil
  106. case discordgo.ApplicationCommandOptionInteger:
  107. return strconv.ParseInt(value, 10, 64)
  108. case discordgo.ApplicationCommandOptionBoolean:
  109. return strconv.ParseBool(value)
  110. case discordgo.ApplicationCommandOptionUser:
  111. return nil, fmt.Errorf("user options aren't supported")
  112. case discordgo.ApplicationCommandOptionChannel:
  113. return nil, fmt.Errorf("channel options aren't supported")
  114. case discordgo.ApplicationCommandOptionRole:
  115. return nil, fmt.Errorf("role options aren't supported")
  116. case discordgo.ApplicationCommandOptionMentionable:
  117. return nil, fmt.Errorf("mentionable options aren't supported")
  118. case discordgo.ApplicationCommandOptionNumber:
  119. return strconv.ParseFloat(value, 64)
  120. case discordgo.ApplicationCommandOptionAttachment:
  121. return nil, fmt.Errorf("attachment options aren't supported")
  122. default:
  123. return nil, fmt.Errorf("unknown option type %d", optType)
  124. }
  125. }
  126. func indent(text, with string) string {
  127. split := strings.Split(text, "\n")
  128. for i, part := range split {
  129. split[i] = with + part
  130. }
  131. return strings.Join(split, "\n")
  132. }
  133. func formatOption(opt *discordgo.ApplicationCommandOption) string {
  134. argText := fmt.Sprintf("* `%s`: %s", opt.Name, getCommandOptionTypeName(opt.Type))
  135. if strings.ToLower(opt.Description) != opt.Name {
  136. argText += fmt.Sprintf(" - %s", opt.Description)
  137. }
  138. if opt.Required {
  139. argText += " (required)"
  140. }
  141. if len(opt.Options) > 0 {
  142. subopts := make([]string, len(opt.Options))
  143. for i, subopt := range opt.Options {
  144. subopts[i] = indent(formatOption(subopt), " ")
  145. }
  146. argText += "\n" + strings.Join(subopts, "\n")
  147. }
  148. return argText
  149. }
  150. func formatCommand(cmd *discordgo.ApplicationCommand) string {
  151. baseText := fmt.Sprintf("$cmdprefix exec %s", cmd.Name)
  152. if len(cmd.Options) > 0 {
  153. args := make([]string, len(cmd.Options))
  154. argPlaceholder := "[arg=value ...]"
  155. for i, opt := range cmd.Options {
  156. args[i] = formatOption(opt)
  157. if opt.Required {
  158. argPlaceholder = "<arg=value ...>"
  159. }
  160. }
  161. baseText = fmt.Sprintf("`%s %s` - %s\n%s", baseText, argPlaceholder, cmd.Description, strings.Join(args, "\n"))
  162. } else {
  163. baseText = fmt.Sprintf("`%s` - %s", baseText, cmd.Description)
  164. }
  165. return baseText
  166. }
  167. func parseCommandOptions(opts []*discordgo.ApplicationCommandOption, subcommands []string, namedArgs map[string]string) (res []*discordgo.ApplicationCommandOptionInput, err error) {
  168. subcommandDone := false
  169. for _, opt := range opts {
  170. optRes := &discordgo.ApplicationCommandOptionInput{
  171. Type: opt.Type,
  172. Name: opt.Name,
  173. }
  174. if opt.Type == discordgo.ApplicationCommandOptionSubCommand {
  175. if !subcommandDone && len(subcommands) > 0 && subcommands[0] == opt.Name {
  176. subcommandDone = true
  177. optRes.Options, err = parseCommandOptions(opt.Options, subcommands[1:], namedArgs)
  178. if err != nil {
  179. err = fmt.Errorf("error parsing subcommand %s: %v", opt.Name, err)
  180. break
  181. }
  182. subcommands = subcommands[1:]
  183. } else {
  184. continue
  185. }
  186. } else if argVal, ok := namedArgs[opt.Name]; ok {
  187. optRes.Value, err = parseCommandOptionValue(opt.Type, argVal)
  188. if err != nil {
  189. err = fmt.Errorf("error parsing parameter %s: %v", opt.Name, err)
  190. break
  191. }
  192. } else if opt.Required {
  193. switch opt.Type {
  194. case discordgo.ApplicationCommandOptionSubCommandGroup, discordgo.ApplicationCommandOptionUser,
  195. discordgo.ApplicationCommandOptionChannel, discordgo.ApplicationCommandOptionRole,
  196. discordgo.ApplicationCommandOptionMentionable, discordgo.ApplicationCommandOptionAttachment:
  197. err = fmt.Errorf("missing required parameter %s (which is not supported by the bridge)", opt.Name)
  198. default:
  199. err = fmt.Errorf("missing required parameter %s", opt.Name)
  200. }
  201. break
  202. } else {
  203. continue
  204. }
  205. res = append(res, optRes)
  206. }
  207. if len(subcommands) > 0 {
  208. err = fmt.Errorf("unparsed subcommands left over (did you forget quoting for parameters with spaces?)")
  209. }
  210. return
  211. }
  212. func executeCommand(cmd *discordgo.ApplicationCommand, args []string) (res []*discordgo.ApplicationCommandOptionInput, err error) {
  213. namedArgs := map[string]string{}
  214. n := 0
  215. for _, arg := range args {
  216. name, value, isNamed := strings.Cut(arg, "=")
  217. if isNamed {
  218. namedArgs[name] = value
  219. } else {
  220. args[n] = arg
  221. n++
  222. }
  223. }
  224. return parseCommandOptions(cmd.Options, args[:n], namedArgs)
  225. }
  226. func fnCommands(ce *WrappedCommandEvent) {
  227. if len(ce.Args) < 2 {
  228. ce.Reply("**Usage**: `$cmdprefix commands search <_query_>` OR `$cmdprefix commands help <_command_>`")
  229. return
  230. }
  231. subcmd := strings.ToLower(ce.Args[0])
  232. if subcmd == "search" {
  233. results, err := ce.User.Session.ApplicationCommandsSearch(ce.Portal.Key.ChannelID, ce.Args[1])
  234. if err != nil {
  235. ce.Reply("Error searching for commands: %v", err)
  236. return
  237. }
  238. formatted := make([]string, len(results))
  239. ce.Portal.commandsLock.Lock()
  240. for i, result := range results {
  241. ce.Portal.commands[result.Name] = result
  242. formatted[i] = indent(formatCommand(result), " ")
  243. formatted[i] = "*" + formatted[i][1:]
  244. }
  245. ce.Portal.commandsLock.Unlock()
  246. ce.Reply("Found results:\n" + strings.Join(formatted, "\n"))
  247. } else if subcmd == "help" {
  248. command := strings.ToLower(ce.Args[1])
  249. cmd, err := ce.Portal.getCommand(ce.User, command)
  250. if err != nil {
  251. ce.Reply("Error searching for commands: %v", err)
  252. } else if cmd == nil {
  253. ce.Reply("Command %q not found", command)
  254. } else {
  255. ce.Reply(formatCommand(cmd))
  256. }
  257. }
  258. }
  259. func fnExec(ce *WrappedCommandEvent) {
  260. if len(ce.Args) == 0 {
  261. ce.Reply("**Usage**: `$cmdprefix exec <command> [arg=value ...]`")
  262. return
  263. }
  264. args, err := shlex.Split(ce.RawArgs)
  265. if err != nil {
  266. ce.Reply("Error parsing args with shlex: %v", err)
  267. return
  268. }
  269. command := strings.ToLower(args[0])
  270. cmd, err := ce.Portal.getCommand(ce.User, command)
  271. if err != nil {
  272. ce.Reply("Error searching for commands: %v", err)
  273. } else if cmd == nil {
  274. ce.Reply("Command %q not found", command)
  275. } else if options, err := executeCommand(cmd, args[1:]); err != nil {
  276. ce.Reply("Error parsing arguments: %v\n\n**Usage:** "+formatCommand(cmd), err)
  277. } else {
  278. nonce := generateNonce()
  279. ce.User.pendingInteractionsLock.Lock()
  280. ce.User.pendingInteractions[nonce] = ce
  281. ce.User.pendingInteractionsLock.Unlock()
  282. err = ce.User.Session.SendInteractions(ce.Portal.GuildID, ce.Portal.Key.ChannelID, cmd, options, nonce)
  283. if err != nil {
  284. ce.Reply("Error sending interaction: %v", err)
  285. ce.User.pendingInteractionsLock.Lock()
  286. delete(ce.User.pendingInteractions, nonce)
  287. ce.User.pendingInteractionsLock.Unlock()
  288. } else {
  289. go func() {
  290. time.Sleep(10 * time.Second)
  291. ce.User.pendingInteractionsLock.Lock()
  292. if _, stillWaiting := ce.User.pendingInteractions[nonce]; stillWaiting {
  293. delete(ce.User.pendingInteractions, nonce)
  294. ce.Reply("Timed out waiting for interaction success")
  295. }
  296. ce.User.pendingInteractionsLock.Unlock()
  297. }()
  298. }
  299. }
  300. }