main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  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 an 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, because
  58. // like everyone knows - optional parameters is on the back.
  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 command have subcommands/subcommand groups
  85. // It must not have top-level options, they aren't accesible in the UI
  86. // in this case (at least, yet), so if command is with
  87. // subcommands/subcommand groups registering top-level options
  88. // will fail the registration of the command
  89. {
  90. Name: "scmd-grp",
  91. Description: "Subcommands group",
  92. Options: []*discordgo.ApplicationCommandOption{
  93. // Also, subcommand groups isn't capable of
  94. // containg options, by the name of them, you can see
  95. // they can contain only 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: "Acknowledge",
  127. Value: 2,
  128. },
  129. {
  130. Name: "Channel message",
  131. Value: 3,
  132. },
  133. {
  134. Name: "Channel message with source",
  135. Value: 4,
  136. },
  137. {
  138. Name: "Acknowledge with source",
  139. Value: 5,
  140. },
  141. },
  142. },
  143. },
  144. },
  145. {
  146. Name: "followups",
  147. Description: "Followup messages",
  148. },
  149. }
  150. commandHandlers = map[string]func(s *discordgo.Session, i *discordgo.InteractionCreate){
  151. "basic-command": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  152. s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  153. Type: discordgo.InteractionResponseChannelMessageWithSource,
  154. Data: &discordgo.InteractionApplicationCommandResponseData{
  155. Content: "Hey there! Congratulations, you just executed your first slash command",
  156. },
  157. })
  158. },
  159. "options": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  160. margs := []interface{}{
  161. // Here we need to convert raw interface{} value to wanted type.
  162. // Also, as you can see, here is used utility functions to convert the value
  163. // to particular type. Yeah, you can use just switch type,
  164. // but this is much simpler
  165. i.Data.Options[0].StringValue(),
  166. i.Data.Options[1].IntValue(),
  167. i.Data.Options[2].BoolValue(),
  168. }
  169. msgformat :=
  170. ` Now you just leared how to use command options. Take a look to the value of which you've just entered:
  171. > string_option: %s
  172. > integer_option: %d
  173. > bool_option: %v
  174. `
  175. if len(i.Data.Options) >= 4 {
  176. margs = append(margs, i.Data.Options[3].ChannelValue(nil).ID)
  177. msgformat += "> channel-option: <#%s>\n"
  178. }
  179. if len(i.Data.Options) >= 5 {
  180. margs = append(margs, i.Data.Options[4].UserValue(nil).ID)
  181. msgformat += "> user-option: <@%s>\n"
  182. }
  183. if len(i.Data.Options) >= 6 {
  184. margs = append(margs, i.Data.Options[5].RoleValue(nil, "").ID)
  185. msgformat += "> role-option: <@&%s>\n"
  186. }
  187. s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  188. // Ignore type for now, we'll discuss them in "responses" part
  189. Type: discordgo.InteractionResponseChannelMessageWithSource,
  190. Data: &discordgo.InteractionApplicationCommandResponseData{
  191. Content: fmt.Sprintf(
  192. msgformat,
  193. margs...,
  194. ),
  195. },
  196. })
  197. },
  198. "subcommands": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  199. content := ""
  200. // As you can see, the name of subcommand (nested, top-level) or subcommand group
  201. // is provided through arguments.
  202. switch i.Data.Options[0].Name {
  203. case "subcmd":
  204. content =
  205. "The top-level subcommand is executed. Now try to execute nested one."
  206. default:
  207. if i.Data.Options[0].Name != "scmd-grp" {
  208. return
  209. }
  210. switch i.Data.Options[0].Options[0].Name {
  211. case "nst-subcmd":
  212. content = "Nice, now you know how to execute nested commands too"
  213. default:
  214. // I added this in the case something might go wrong
  215. content = "Oops, something gone wrong.\n" +
  216. "Hol' up, you aren't supposed to see this message."
  217. }
  218. }
  219. s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  220. Type: discordgo.InteractionResponseChannelMessageWithSource,
  221. Data: &discordgo.InteractionApplicationCommandResponseData{
  222. Content: content,
  223. },
  224. })
  225. },
  226. "responses": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  227. // Responses to a command is really important thing.
  228. // First of all, because you need to react to the interaction
  229. // by sending the response in 3 seconds after receiving, otherwise
  230. // interaction will be considered invalid and you can no longer
  231. // use interaction token and ID for responding to the user's request
  232. content := ""
  233. // As you can see, response type names saying by themselvs
  234. // how they're used, but for those who want to get
  235. // more information - read the official documentation
  236. switch i.Data.Options[0].IntValue() {
  237. case int64(discordgo.InteractionResponseChannelMessage):
  238. content =
  239. "Well, you just responded to an interaction, and sent a message.\n" +
  240. "That's all what I wanted to say, yeah."
  241. content +=
  242. "\nAlso... you can edit your response, wait 5 seconds and this message will be changed"
  243. case int64(discordgo.InteractionResponseChannelMessageWithSource):
  244. content =
  245. "You just responded to an interaction, sent a message and showed the original one. " +
  246. "Congratulations!"
  247. content +=
  248. "\nAlso... you can edit your response, wait 5 seconds and this message will be changed"
  249. default:
  250. err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  251. Type: discordgo.InteractionResponseType(i.Data.Options[0].IntValue()),
  252. })
  253. if err != nil {
  254. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  255. Content: "Something gone wrong",
  256. })
  257. }
  258. return
  259. }
  260. err := s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  261. Type: discordgo.InteractionResponseType(i.Data.Options[0].IntValue()),
  262. Data: &discordgo.InteractionApplicationCommandResponseData{
  263. Content: content,
  264. },
  265. })
  266. if err != nil {
  267. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  268. Content: "Something gone wrong",
  269. })
  270. return
  271. }
  272. time.AfterFunc(time.Second*5, func() {
  273. err = s.InteractionResponseEdit(s.State.User.ID, i.Interaction, &discordgo.WebhookEdit{
  274. Content: content + "\n\nWell, now you know how to create and edit responses. " +
  275. "But you still don't know how to delete them... so... wait 10 seconds and this " +
  276. "message will be deleted.",
  277. })
  278. if err != nil {
  279. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  280. Content: "Something gone wrong",
  281. })
  282. return
  283. }
  284. time.Sleep(time.Second * 10)
  285. s.InteractionResponseDelete(s.State.User.ID, i.Interaction)
  286. })
  287. },
  288. "followups": func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  289. // Followup messages is basically regular messages (you can create as many of them as you wish),
  290. // but working as they is created by webhooks and their functional
  291. // is for handling additional messages after sending response.
  292. s.InteractionRespond(i.Interaction, &discordgo.InteractionResponse{
  293. Type: discordgo.InteractionResponseChannelMessageWithSource,
  294. Data: &discordgo.InteractionApplicationCommandResponseData{
  295. // Note: this isn't documented, but you can use that if you want to.
  296. // This flag just allows to create messages visible only for the caller (user who triggered the command)
  297. // of the command
  298. Flags: 1 << 6,
  299. Content: "Surprise!",
  300. },
  301. })
  302. msg, err := s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  303. Content: "Followup message has created, after 5 seconds it will be edited",
  304. })
  305. if err != nil {
  306. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  307. Content: "Something gone wrong",
  308. })
  309. return
  310. }
  311. time.Sleep(time.Second * 5)
  312. s.FollowupMessageEdit(s.State.User.ID, i.Interaction, msg.ID, &discordgo.WebhookEdit{
  313. Content: "Now original message is gone and after 10 seconds this message will ~~self-destruct~~ be deleted.",
  314. })
  315. time.Sleep(time.Second * 10)
  316. s.FollowupMessageDelete(s.State.User.ID, i.Interaction, msg.ID)
  317. s.FollowupMessageCreate(s.State.User.ID, i.Interaction, true, &discordgo.WebhookParams{
  318. Content: "For those, who didn't skip anything and followed tutorial along fairly, " +
  319. "take a unicorn :unicorn: as reward!\n" +
  320. "Also, as bonus..., look at the original interaction response :D",
  321. })
  322. },
  323. }
  324. )
  325. func init() {
  326. s.AddHandler(func(s *discordgo.Session, i *discordgo.InteractionCreate) {
  327. if h, ok := commandHandlers[i.Data.Name]; ok {
  328. h(s, i)
  329. }
  330. })
  331. }
  332. func main() {
  333. s.AddHandler(func(s *discordgo.Session, r *discordgo.Ready) {
  334. log.Println("Bot is up!")
  335. })
  336. err := s.Open()
  337. if err != nil {
  338. log.Fatalf("Cannot open the session: %v", err)
  339. }
  340. for _, v := range commands {
  341. _, err := s.ApplicationCommandCreate(s.State.User.ID, *GuildID, v)
  342. if err != nil {
  343. log.Panicf("Cannot create '%v' command: %v", v.Name, err)
  344. }
  345. }
  346. defer s.Close()
  347. stop := make(chan os.Signal)
  348. signal.Notify(stop, os.Interrupt)
  349. <-stop
  350. log.Println("Gracefully shutdowning")
  351. }