main.go 13 KB

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