commands_botinteraction.go 10 KB

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