func fetchPrimaryTextChannelID(sess *discordgo.Session) string { var channelid string retryOnBadGateway(func() error { guilds, err := sess.UserGuilds() if err != nil { return err } guild, err := sess.Guild(guilds[0].ID) if err != nil { return err } channels, err := sess.GuildChannels(guild.ID) if err != nil { return err } for _, channel := range channels { channel, err = sess.Channel(channel.ID) if err != nil { return err } if channel.Type == "text" { channelid = channel.ID return nil } } return errors.New("No primary channel found") }) return channelid }
func ListenToDiscord(config *eqemuconfig.Config, disco *discord.Discord) (err error) { var session *discordgo.Session var guild *discordgo.Guild //log.Println("Listen to discord..") if session, err = disco.GetSession(); err != nil { log.Printf("[Discord] Failed to get instance %s: %s (Make sure bot is part of server)", config.Discord.ServerID, err.Error()) return } if guild, err = session.Guild(config.Discord.ServerID); err != nil { log.Printf("[Discord] Failed to get server %s: %s (Make sure bot is part of server)", config.Discord.ServerID, err.Error()) return } isNotAvail := true if guild.Unavailable == &isNotAvail { log.Printf("[Discord] Failed to get server %s: Server unavailable (Make sure bot is part of server, and has permission)", config.Discord.ServerID, err.Error()) return } session.StateEnabled = true session.AddHandler(messageCreate) log.Printf("[Discord] Connected\n") if err = session.Open(); err != nil { log.Printf("[Discord] Session closed: %s", err.Error()) return } select {} return }
func findPrimaryChannelInGuild(s *discordgo.Session, guildID *string) (*discordgo.Channel, error) { guild, err := s.Guild(*guildID) if err != nil { return nil, err } for _, guildChannel := range guild.Channels { if guildChannel.ID == guild.ID { return guildChannel, nil } } // this should never happen as every Discord server should have a // 'primary' channel return nil, nil }
//SetGuildState sets the Guild inside the State func SetGuildState(dg *discordgo.Session) { State.InsertMode = false Guilds, _ := dg.UserGuilds() d := color.New(color.FgYellow, color.Bold) d.Printf("Select a Guild:\n") for key, guild := range Guilds { fmt.Printf("%d:%s\n", key, guild.Name) } var response int fmt.Scanf("%d\n", &response) State.Guild, _ = dg.Guild(Guilds[response].ID) Clear() State.InsertMode = true }
// the below method is invoked when the Discord Websocket API transmits // a 'guildMemberAdd' event to the bot func onGuildMemberAdd(s *discordgo.Session, event *discordgo.GuildMemberAdd) { logrus.WithFields(logrus.Fields{ "guildId": event.GuildID, "joinedAt": event.JoinedAt, "userId": event.User.ID, "username": event.User.Username, }).Debug("Received guild member add event from Discord Websocket API.") guild, err := s.Guild(event.GuildID) if err != nil { logrus.WithFields(logrus.Fields{ "guildId": event.GuildID, "capturedError": err, }).Error("Could not retrieve guild object from identifier.") return } primaryChan, err := findPrimaryChannelInGuild(s, &event.GuildID) if err != nil { logrus.WithFields(logrus.Fields{ "userId": event.User.ID, "guildId": event.GuildID, "capturedError": err, }).Error("Could not determine primary channel for guild.") return } // create a private messaging channel between the bot and the new guild member privChan, err := s.UserChannelCreate(event.User.ID) if err != nil { logrus.WithFields(logrus.Fields{ "userId": event.User.ID, "capturedError": err, }).Error("Could not create channel between bot and user.") return } // send greet message to new guild member s.ChannelMessageSend(privChan.ID, "Welcome to "+guild.Name+"! We recommend setting your Pokemon GO team to grant access to team-only channels. To do so, type `!setTeam [name]` into the #"+primaryChan.Name+" text channel to set your Pokemon GO team. Available team names are: 'valor' (red), 'mystic' (blue) and 'instinct' (yellow).") }
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) { if m.Author.Bot { return } chanl, err := s.Channel(m.ChannelID) if err != nil { return } guild, _ := s.Guild(chanl.GuildID) var author *discordgo.Member if guild != nil { author, _ = s.GuildMember(guild.ID, m.Author.ID) } checkLink(s, m.Content, chanl.ID, chanl.LastMessageID) messageContents <- m if len(m.Content) > 21 && len(m.Mentions) > 0 && m.Mentions[len(m.Mentions)-1].Username == "MrDestructoid" { arr := strings.Fields(m.Content) switch arr[1] { case "BD": bdLinks(s, m.ChannelID) // case "state": // for _, i := range guild.VoiceStates { // fmt.Println(i.UserID) // } // case "bot": // var mem runtime.MemStats // runtime.ReadMemStats(&mem) // fmt.Println(mem.HeapAlloc) case "myid": s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("```\n%v\n```", m.Author.ID)) // //---------------- NO WAY TO UTILIZE ----------- // case "joinchannel": // ch := make(chan string) // fmt.Println(strings.Join(arr[2:], " ")) // if findNjoinChannel(s, guild.ID, guild.Channels, // strings.Join(arr[2:], " "), ch) { // echo(dgv, ch) // fmt.Println("opened") // } // //---------------- NO WAY TO UTILIZE ---------- case "channels": var str string = fmt.Sprintf("\n%-20s\t%-5s\tID", "Name", "Type") for _, c := range guild.Channels { str += fmt.Sprintf("\n%-20s\t%-5s\t%s", c.Name, c.Type, c.ID) } s.ChannelMessageSend(m.ChannelID, fmt.Sprintf("```%s```", str)) case "updateroles": updateRolesToDB(s, guild.ID) case "guild": var owner string for _, i := range guild.Members { if i.User.ID == guild.OwnerID { owner = i.User.Username } } s.ChannelMessageSend(m.ChannelID, fmt.Sprintf( "```**Guild information** \nName: %s\nOwner: %s\nID: %s\nRegion: %s\nHas members: %d```", guild.Name, owner, guild.ID, guild.Region, len(guild.Members))) case "quit": if checkForPermissions(s, chanl.ID, author.Roles) { quit = true } case "ban": banUser(s, guild, author, m.ChannelID, arr) case "unban": manualUnban(s, chanl.ID, author.Roles, arr) case "bannedusers": bannedUsers(s, m) default: s.ChannelMessageSend(chanl.ID, fmt.Sprintf("No such command")) } } }
func handleTeamSet(s *discordgo.Session, givenTeamName *string, authorID *string, channelID *string) { // validate a team option was provided to the command if *givenTeamName == "" { s.ChannelMessageSend(*channelID, "A team must be provided to this command.") return } // validate the team provided matches a valid option hasTeam := false for _, team := range teams { if *givenTeamName == team { hasTeam = true } } if !hasTeam { s.ChannelMessageSend(*channelID, "The team selected ("+*givenTeamName+") does not exist. Valid options are: "+strings.Join(teams, ", ")+".") return } currChannel, err := s.Channel(*channelID) if err != nil { logrus.WithFields(logrus.Fields{ "channelId": *channelID, "capturedError": err, }).Error("Could not parse channel identifier into channel object.") s.ChannelMessageSend(*channelID, "An error occurred while setting your team. Please wait a moment and try again.") return } currGuild, err := s.Guild(currChannel.GuildID) if err != nil { logrus.WithFields(logrus.Fields{ "guildId": currChannel.GuildID, "capturedError": err, }).Error("Could not parse guild identifier into guild object.") s.ChannelMessageSend(*channelID, "An error occurred while setting your team. Please wait a moment and try again.") return } currMember, err := s.GuildMember(currGuild.ID, *authorID) if err != nil { logrus.WithFields(logrus.Fields{ "guildId": currGuild.ID, "userId": *authorID, "capturedError": err, }).Error("Could not parse guild identifier and user identifier into guild member object.") s.ChannelMessageSend(*channelID, "An error occurred while setting your team. Please wait a moment and try again.") return } // ensure they are not an existing member of a team for _, roleID := range currMember.Roles { var role *discordgo.Role for _, guildRole := range currGuild.Roles { if guildRole.ID == roleID { role = guildRole } } if role == nil { logrus.WithFields(logrus.Fields{ "roleId": roleID, }).Error("Could not retrieve role object from identifier.") s.ChannelMessageSend(*channelID, "An error occurred while setting your team. Please wait a moment and try again.") return } for _, teamName := range teams { if role.Name == "Team "+strings.Title(teamName) { logrus.WithFields(logrus.Fields{ "roleName": role.Name, "roleId": role.ID, "userId": currMember.User.ID, "userName": currMember.User.Username, "guildId": currGuild.ID, }).Warn("Attempted team switch detected.") s.ChannelMessageSend(*channelID, "You are already a member of a team and cannot switch now. Ask an administrator if you have made a mistake selecting teams.") return } } } // add the role to the user teamTitle := strings.Title(*givenTeamName) for _, role := range currGuild.Roles { if role.Name == "Team "+teamTitle { err := s.GuildMemberEdit(currGuild.ID, *authorID, append(currMember.Roles, role.ID)) if err != nil { logrus.WithFields(logrus.Fields{ "guildId": currGuild.ID, "userId": *authorID, "roleId": role.ID, "capturedError": err, }).Error("Could not add team role to user.") s.ChannelMessageSend(*channelID, "An error occurred while setting your team. Please wait a moment and try again.") return } s.ChannelMessageSend(*channelID, "You have been set to Team "+teamTitle+".") } } }