main.go 12 KB

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