main.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "os"
  7. "os/signal"
  8. "strings"
  9. "time"
  10. "github.com/bwmarrin/discordgo"
  11. )
  12. // Bot parameters
  13. var (
  14. GuildID = flag.String("guild", "", "Test guild ID. If not passed - bot registers commands globally")
  15. BotToken = flag.String("token", "", "Bot access token")
  16. RemoveCommands = flag.Bool("rmcmd", true, "Remove all commands after shutdowning or not")
  17. )
  18. var s *discordgo.Session
  19. func init() { flag.Parse() }
  20. func init() {
  21. var err error
  22. s, err = discordgo.New("Bot " + *BotToken)
  23. if err != nil {
  24. log.Fatalf("Invalid bot parameters: %v", err)
  25. }
  26. }
  27. var (
  28. integerOptionMinValue = 1.0
  29. commands = []*discordgo.ApplicationCommand{
  30. {
  31. Name: "basic-command",
  32. // All commands and options must have a description
  33. // Commands/options without description will fail the registration
  34. // of the command.
  35. Description: "Basic command",
  36. },
  37. {
  38. Name: "basic-command-with-files",
  39. Description: "Basic command with files",
  40. },
  41. {
  42. Name: "options",
  43. Description: "Command for demonstrating options",
  44. Options: []*discordgo.ApplicationCommandOption{
  45. {
  46. Type: discordgo.ApplicationCommandOptionString,
  47. Name: "string-option",
  48. Description: "String option",
  49. Required: true,
  50. },
  51. {
  52. Type: discordgo.ApplicationCommandOptionInteger,
  53. Name: "integer-option",
  54. Description: "Integer option",
  55. MinValue: &integerOptionMinValue,
  56. MaxValue: 10,
  57. Required: true,
  58. },
  59. {
  60. Type: discordgo.ApplicationCommandOptionBoolean,
  61. Name: "bool-option",
  62. Description: "Boolean option",
  63. Required: true,
  64. },
  65. // Required options must be listed first since optional parameters
  66. // always come after when they're used.
  67. // The same concept applies to Discord's Slash-commands API
  68. {
  69. Type: discordgo.ApplicationCommandOptionChannel,
  70. Name: "channel-option",
  71. Description: "Channel option",
  72. // Channel type mask
  73. ChannelTypes: []discordgo.ChannelType{
  74. discordgo.ChannelTypeGuildText,
  75. discordgo.ChannelTypeGuildVoice,
  76. },
  77. Required: false,
  78. },
  79. {
  80. Type: discordgo.ApplicationCommandOptionUser,
  81. Name: "user-option",
  82. Description: "User option",
  83. Required: false,
  84. },
  85. {
  86. Type: discordgo.ApplicationCommandOptionRole,
  87. Name: "role-option",
  88. Description: "Role option",
  89. Required: false,
  90. },
  91. },
  92. },
  93. {
  94. Name: "subcommands",
  95. Description: "Subcommands and command groups example",
  96. Options: []*discordgo.ApplicationCommandOption{
  97. // When a command has subcommands/subcommand groups
  98. // It must not have top-level options, they aren't accesible in the UI
  99. // in this case (at least not yet), so if a command has
  100. // subcommands/subcommand any groups registering top-level options
  101. // will cause the registration of the command to fail
  102. {
  103. Name: "scmd-grp",
  104. Description: "Subcommands group",
  105. Options: []*discordgo.ApplicationCommandOption{
  106. // Also, subcommand groups aren't capable of
  107. // containing options, by the name of them, you can see
  108. // they can only contain subcommands
  109. {
  110. Name: "nst-subcmd",
  111. Description: "Nested subcommand",
  112. Type: discordgo.ApplicationCommandOptionSubCommand,
  113. },
  114. },
  115. Type: discordgo.ApplicationCommandOptionSubCommandGroup,
  116. },
  117. // Also, you can create both subcommand groups and subcommands
  118. // in the command at the same time. But, there's some limits to
  119. // nesting, count of subcommands (top level and nested) and options.
  120. // Read the intro of slash-commands docs on Discord dev portal
  121. // to get more information
  122. {
  123. Name: "subcmd",
  124. Description: "Top-level subcommand",
  125. Type: discordgo.ApplicationCommandOptionSubCommand,
  126. },
  127. },
  128. },
  129. {
  130. Name: "responses",
  131. Description: "Interaction responses testing initiative",
  132. Options: []*discordgo.ApplicationCommandOption{
  133. {
  134. Name: "resp-type",
  135. Description: "Response type",
  136. Type: discordgo.ApplicationCommandOptionInteger,
  137. Choices: []*discordgo.ApplicationCommandOptionChoice{
  138. {
  139. Name: "Channel message with source",
  140. Value: 4,
  141. },
  142. {
  143. Name: "Deferred response With Source",
  144. Value: 5,
  145. },
  146. },
  147. Required: true,
  148. },
  149. },
  150. },
  151. {
  152. Name: "followups",
  153. Description: "Followup messages",
  154. },
  155. }
  156. commandHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
  157. "basic-command": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  158. s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  159. Type: discordgo.InteractionResponseChannelMessageWithSource,
  160. Data: &discordgo.InteractionResponseData{
  161. Content: "Hey there! Congratulations, you just executed your first slash command",
  162. },
  163. })
  164. },
  165. "basic-command-with-files": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  166. s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  167. Type: discordgo.InteractionResponseChannelMessageWithSource,
  168. Data: &discordgo.InteractionResponseData{
  169. Content: "Hey there! Congratulations, you just executed your first slash command with a file in the response",
  170. Files: []*discordgo.File{
  171. {
  172. ContentType: "text/plain",
  173. Name: "test.txt",
  174. Reader: strings.NewReader("Hello Discord!!"),
  175. },
  176. },
  177. },
  178. })
  179. },
  180. "options": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  181. margs := []interface{}{
  182. // Here we need to convert raw interface{} value to wanted type.
  183. // Also, as you can see, here is used utility functions to convert the value
  184. // to particular type. Yeah, you can use just switch type,
  185. // but this is much simpler
  186. i.ApplicationCommandData().Options[0].StringValue(),
  187. i.ApplicationCommandData().Options[1].IntValue(),
  188. i.ApplicationCommandData().Options[2].BoolValue(),
  189. }
  190. msgformat :=
  191. ` Now you just learned how to use command options. Take a look to the value of which you've just entered:
  192. > string_option: %s
  193. > integer_option: %d
  194. > bool_option: %v
  195. `
  196. if len(i.ApplicationCommandData().Options) >= 4 {
  197. margs = append(margs, i.ApplicationCommandData().Options[3].ChannelValue(nil).ID)
  198. msgformat += "> channel-option: <#%s>\n"
  199. }
  200. if len(i.ApplicationCommandData().Options) >= 5 {
  201. margs = append(margs, i.ApplicationCommandData().Options[4].UserValue(nil).ID)
  202. msgformat += "> user-option: <@%s>\n"
  203. }
  204. if len(i.ApplicationCommandData().Options) >= 6 {
  205. margs = append(margs, i.ApplicationCommandData().Options[5].RoleValue(nil, "").ID)
  206. msgformat += "> role-option: <@&%s>\n"
  207. }
  208. s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  209. // Ignore type for now, we'll discuss them in "responses" part
  210. Type: discordgo.InteractionResponseChannelMessageWithSource,
  211. Data: &discordgo.InteractionResponseData{
  212. Content: fmt.Sprintf(
  213. msgformat,
  214. margs...,
  215. ),
  216. },
  217. })
  218. },
  219. "subcommands": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  220. content := ""
  221. // As you can see, the name of subcommand (nested, top-level) or subcommand group
  222. // is provided through arguments.
  223. switch i.ApplicationCommandData().Options[0].Name {
  224. case "subcmd":
  225. content =
  226. "The top-level subcommand is executed. Now try to execute the nested one."
  227. default:
  228. if i.ApplicationCommandData().Options[0].Name != "scmd-grp" {
  229. return
  230. }
  231. switch i.ApplicationCommandData().Options[0].Options[0].Name {
  232. case "nst-subcmd":
  233. content = "Nice, now you know how to execute nested commands too"
  234. default:
  235. // I added this in the case something might go wrong
  236. content = "Oops, something gone wrong.\n" +
  237. "Hol' up, you aren't supposed to see this message."
  238. }
  239. }
  240. s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  241. Type: discordgo.InteractionResponseChannelMessageWithSource,
  242. Data: &discordgo.InteractionResponseData{
  243. Content: content,
  244. },
  245. })
  246. },
  247. "responses": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  248. // Responses to a command are very important.
  249. // First of all, because you need to react to the interaction
  250. // by sending the response in 3 seconds after receiving, otherwise
  251. // interaction will be considered invalid and you can no longer
  252. // use the interaction token and ID for responding to the user's request
  253. content := ""
  254. // As you can see, the response type names used here are pretty self-explanatory,
  255. // but for those who want more information see the official documentation
  256. switch i.ApplicationCommandData().Options[0].IntValue() {
  257. case int64(discordgo.InteractionResponseChannelMessageWithSource):
  258. content =
  259. "You just responded to an interaction, sent a message and showed the original one. " +
  260. "Congratulations!"
  261. content +=
  262. "\nAlso... you can edit your response, wait 5 seconds and this message will be changed"
  263. default:
  264. err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  265. Type: discordgo.InteractionResponseType(i.ApplicationCommandData().Options[0].IntValue()),
  266. })
  267. if err != nil {
  268. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  269. Content: "Something went wrong",
  270. })
  271. }
  272. return
  273. }
  274. err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  275. Type: discordgo.InteractionResponseType(i.ApplicationCommandData().Options[0].IntValue()),
  276. Data: &discordgo.InteractionResponseData{
  277. Content: content,
  278. },
  279. })
  280. if err != nil {
  281. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  282. Content: "Something went wrong",
  283. })
  284. return
  285. }
  286. time.AfterFunc(time.Second*5, func() {
  287. _, err = s.InteractionResponseEdit(s.State.User.ID, i.Interaction, &discordgo.WebhookEdit{
  288. Content: content + "\n\nWell, now you know how to create and edit responses. " +
  289. "But you still don't know how to delete them... so... wait 10 seconds and this " +
  290. "message will be deleted.",
  291. })
  292. if err != nil {
  293. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  294. Content: "Something went wrong",
  295. })
  296. return
  297. }
  298. time.Sleep(time.Second * 10)
  299. s.InteractionResponseDelete(s.State.User.ID, i.Interaction)
  300. })
  301. },
  302. "followups": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  303. // Followup messages are basically regular messages (you can create as many of them as you wish)
  304. // but work as they are created by webhooks and their functionality
  305. // is for handling additional messages after sending a response.
  306. s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  307. Type: discordgo.InteractionResponseChannelMessageWithSource,
  308. Data: &discordgo.InteractionResponseData{
  309. // Note: this isn't documented, but you can use that if you want to.
  310. // This flag just allows you to create messages visible only for the caller of the command
  311. // (user who triggered the command)
  312. Flags: 1 << 6,
  313. Content: "Surprise!",
  314. },
  315. })
  316. msg, err := s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  317. Content: "Followup message has been created, after 5 seconds it will be edited",
  318. })
  319. if err != nil {
  320. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  321. Content: "Something went wrong",
  322. })
  323. return
  324. }
  325. time.Sleep(time.Second * 5)
  326. s.FollowupMessageEdit(s.State.User.ID, i.Interaction, msg.ID, &discordgo.WebhookEdit{
  327. Content: "Now the original message is gone and after 10 seconds this message will ~~self-destruct~~ be deleted.",
  328. })
  329. time.Sleep(time.Second * 10)
  330. s.FollowupMessageDelete(s.State.User.ID, i.Interaction, msg.ID)
  331. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  332. Content: "For those, who didn't skip anything and followed tutorial along fairly, " +
  333. "take a unicorn :unicorn: as reward!\n" +
  334. "Also, as bonus... look at the original interaction response :D",
  335. })
  336. },
  337. }
  338. )
  339. func init() {
  340. s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  341. if h, ok := commandHandlers[i.ApplicationCommandData().Name]; ok {
  342. h(s, i)
  343. }
  344. })
  345. }
  346. func main() {
  347. s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
  348. log.Printf("Logged in as: %v#%v", s.State.User.Username, s.State.User.Discriminator)
  349. })
  350. err := s.Open()
  351. if err != nil {
  352. log.Fatalf("Cannot open the session: %v", err)
  353. }
  354. log.Println("Adding commands...")
  355. registeredCommands := make([]*discordgo.ApplicationCommand, len(commands))
  356. for i, v := range commands {
  357. cmd, err := s.ApplicationCommandCreate(s.State.User.ID, *GuildID, v)
  358. if err != nil {
  359. log.Panicf("Cannot create '%v' command: %v", v.Name, err)
  360. }
  361. registeredCommands[i] = cmd
  362. }
  363. defer s.Close()
  364. stop := make(chan os.Signal, 1)
  365. signal.Notify(stop, os.Interrupt)
  366. log.Println("Press Ctrl+C to exit")
  367. <-stop
  368. if *RemoveCommands {
  369. log.Println("Removing commands...")
  370. // // We need to fetch the commands, since deleting requires the command ID.
  371. // // We are doing this from the returned commands on line 375, because using
  372. // // this will delete all the commands, which might not be desirable, so we
  373. // // are deleting only the commands that we added.
  374. // registeredCommands, err := s.ApplicationCommands(s.State.User.ID, *GuildID)
  375. // if err != nil {
  376. // log.Fatalf("Could not fetch registered commands: %v", err)
  377. // }
  378. for _, v := range registeredCommands {
  379. err := s.ApplicationCommandDelete(s.State.User.ID, *GuildID, v.ID)
  380. if err != nil {
  381. log.Panicf("Cannot delete '%v' command: %v", v.Name, err)
  382. }
  383. }
  384. }
  385. log.Println("Gracefully shutdowning")
  386. }