• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Golang discordgo.Session类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/bwmarrin/discordgo.Session的典型用法代码示例。如果您正苦于以下问题:Golang Session类的具体用法?Golang Session怎么用?Golang Session使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



在下文中一共展示了Session类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: Welcome

//Welcome sends an acknowledge to the terminal that it is listening, and prints the current Username
func Welcome(dg *discordgo.Session) {
	d := color.New(color.FgYellow, color.Bold)
	d.Printf("Listening!\n\n")

	user, _ := dg.User("@me")
	d.Printf("Welcome, %s!\n\n", user.Username)
}
开发者ID:iopred,项目名称:discord-cli,代码行数:8,代码来源:init.go


示例2: playSound

// playSound plays the current buffer to the provided channel.
func playSound(s *discordgo.Session, guildID, channelID string) (err error) {
	// Join the provided voice channel.
	vc, err := s.ChannelVoiceJoin(guildID, channelID, false, true)
	if err != nil {
		return err
	}

	// Sleep for a specified amount of time before playing the sound
	time.Sleep(250 * time.Millisecond)

	// Start speaking.
	_ = vc.Speaking(true)

	// Send the buffer data.
	for _, buff := range buffer {
		vc.OpusSend <- buff
	}

	// Stop speaking
	_ = vc.Speaking(false)

	// Sleep for a specificed amount of time before ending.
	time.Sleep(250 * time.Millisecond)

	// Disconnect from the provided voice channel.
	_ = vc.Disconnect()

	return nil
}
开发者ID:42wim,项目名称:matterbridge,代码行数:30,代码来源:main.go


示例3: changeAvatar

// Helper function to change the avatar
func changeAvatar(s *discordgo.Session) {

	resp, err := http.Get(URL)
	if err != nil {
		fmt.Println("Error retrieving the file, ", err)
		return
	}

	defer func() {
		_ = resp.Body.Close()
	}()

	img, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading the response, ", err)
		return
	}

	base64 := base64.StdEncoding.EncodeToString(img)

	avatar := fmt.Sprintf("data:%s;base64,%s", http.DetectContentType(img), base64)

	_, err = s.UserUpdate("", "", BotUsername, avatar, "")
	if err != nil {
		fmt.Println("Error setting the avatar, ", err)
	}

}
开发者ID:42wim,项目名称:matterbridge,代码行数:29,代码来源:main.go


示例4: Message

// Message receives a Message struct and sends it to appropriate channels
func Message(s *discordgo.Session, m *types.Message) error {
	message := strings.Join(m.Payload, "\n")
	var channels []string
	var dchannels []*discordgo.Channel
	var err error
	c := config.Get()

	if m.Prefix != "" {
		message = fmt.Sprintf("%s: %s", m.Prefix, message)
	}

	if m.Channels[0] == "*" {
		dchannels, err = s.GuildChannels(c.Guild)

		if err != nil {
			return err
		}
		//errhandler.Handle(err)

		for _, chann := range dchannels {
			channels = append(channels, chann.ID)
		}

	} else {
		channels = m.Channels
	}
	log.Debugf("%s\n", len(channels))

	for _, channel := range channels {
		s.ChannelMessageSend(channel, message)
	}
	return nil
}
开发者ID:Skullever,项目名称:digo,代码行数:34,代码来源:handler.go


示例5: dgoListen

func dgoListen(s *discordgo.Session) error {
	log.Notice("Digo listening for WS Events")
	// Listen blocks until it returns
	//go acceptInvite(s)
	err := s.Listen()
	return err
}
开发者ID:Skullever,项目名称:digo,代码行数:7,代码来源:conn.go


示例6: messageCreate

func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
	if m.ChannelID != config.Discord.ChannelID {
		return
	}

	ign := ""
	member, err := s.State.Member(config.Discord.ServerID, m.Author.ID)
	if err != nil {
		log.Printf("[Discord] Failed to get member: %s (Make sure you have set the bot permissions to see members)", err.Error())
		return
	}

	roles, err := s.GuildRoles(config.Discord.ServerID)
	if err != nil {
		log.Printf("[Discord] Failed to get roles: %s (Make sure you have set the bot permissions to see roles)", err.Error())
		return
	}
	for _, role := range member.Roles {
		if ign != "" {
			break
		}
		for _, gRole := range roles {
			if ign != "" {
				break
			}
			if strings.TrimSpace(gRole.ID) == strings.TrimSpace(role) {
				if strings.Contains(gRole.Name, "IGN:") {
					splitStr := strings.Split(gRole.Name, "IGN:")
					if len(splitStr) > 1 {
						ign = strings.TrimSpace(splitStr[1])
					}
				}
			}
		}
	}
	if ign == "" {
		return
	}
	msg := m.ContentWithMentionsReplaced()
	//Maximum limit of 4k
	if len(msg) > 4000 {
		msg = msg[0:4000]
	}

	if len(msg) < 1 {
		return
	}

	ign = sanitize(ign)
	msg = sanitize(msg)

	//Send message.
	if err = Sendln(fmt.Sprintf("emote world 260 %s says from discord, '%s'", ign, msg)); err != nil {
		log.Printf("[Discord] Error sending message to telnet (%s:%s): %s\n", ign, msg, err.Error())
		return
	}

	log.Printf("[Discord] %s: %s\n", ign, msg)
}
开发者ID:Xackery,项目名称:discordeq,代码行数:59,代码来源:discord.go


示例7: sendMessage

func sendMessage(sess *discordgo.Session, message string) {
	channelid := fetchPrimaryTextChannelID(sess)
	logInfo("SENDING MESSAGE:", message)
	retryOnBadGateway(func() error {
		_, err := sess.ChannelMessageSend(channelid, message)
		return err
	})
}
开发者ID:dhedegaard,项目名称:notibot,代码行数:8,代码来源:notibot.go


示例8: Ban

//Ban function calls the BanCreate api for discord and sets the warnning
//and banned information appropriatly
func (u *User) Ban(dg *discordgo.Session) (success bool, err error) {
	u.Banned = true
	u.BannedDate = time.Now()
	u.Warnings = 0
	err = dg.GuildBanCreate(u.Member.GuildID, u.Member.User.ID, 0)
	if err == nil {
		return true, nil
	}
	return false, nil
}
开发者ID:dayln,项目名称:gopherbot,代码行数:12,代码来源:user.go


示例9: ChangeBotName

func ChangeBotName(s *discordgo.Session, name string, avatarfile string) {
	binary, _ := ioutil.ReadFile(avatarfile)
	avatar := base64.StdEncoding.EncodeToString(binary)

	_, err := s.UserUpdate("", "", name, "data:image/jpeg;base64,"+avatar, "")
	if err != nil {
		fmt.Println(err.Error())
	} else {
		fmt.Println("Changed username successfully")
	}
}
开发者ID:blackhole12,项目名称:sweetiebot,代码行数:11,代码来源:sweetiebot.go


示例10: bdLinks

func bdLinks(s *discordgo.Session, id string) {
	resp, err := http.Get("https://betterdiscord.net/home/")
	checkErr(err)
	bytes, err := ioutil.ReadAll(resp.Body)
	checkErr(err)
	rx := regexp.MustCompile(`<a href="(.*.zip)`)
	mm := rx.FindAllStringSubmatch(string(bytes), 2)
	s.ChannelMessageSend(id,
		fmt.Sprintf("\n`OSX:` %s\n`Windows:` %s", mm[1][1], mm[0][1]))

}
开发者ID:Muckfoot,项目名称:Go,代码行数:11,代码来源:basic_bot.go


示例11: onGuildCreate

func onGuildCreate(s *discordgo.Session, event *discordgo.GuildCreate) {
	if event.Guild.Unavailable != nil {
		return
	}

	for _, channel := range event.Guild.Channels {
		if channel.ID == event.Guild.ID {
			s.ChannelMessageSend(channel.ID, "**AIRHORN BOT READY FOR HORNING. TYPE `!AIRHORN` WHILE IN A VOICE CHANNEL TO ACTIVATE**")
			return
		}
	}
}
开发者ID:RaymondSchnyder,项目名称:airhornbot,代码行数:12,代码来源:bot.go


示例12: guildCreate

// This function will be called (due to AddHandler above) every time a new
// guild is joined.
func guildCreate(s *discordgo.Session, event *discordgo.GuildCreate) {
	if event.Guild.Unavailable != nil {
		return
	}

	for _, channel := range event.Guild.Channels {
		if channel.ID == event.Guild.ID {
			_, _ = s.ChannelMessageSend(channel.ID, "Airhorn is ready! Type !airhorn while in a voice channel to play a sound.")
			return
		}
	}
}
开发者ID:42wim,项目名称:matterbridge,代码行数:14,代码来源:main.go


示例13: acceptInvite

func acceptInvite(s *discordgo.Session) error {
	var err error
	c := config.Get()
	//time.Sleep(1 * time.Second)
	if c.InviteID != "" {
		log.Debugf("Attempting to accept invite: %s", c.InviteID)
		_, err = s.InviteAccept(c.InviteID)
	} else {
		log.Debug("No DIGO_INVITE_ID specified, no invite to accept.")
	}
	return err
}
开发者ID:Skullever,项目名称:digo,代码行数:12,代码来源:conn.go


示例14: fetchUser

func fetchUser(sess *discordgo.Session, userid string) *discordgo.User {
	var result *discordgo.User
	retryOnBadGateway(func() error {
		var err error
		result, err = sess.User(userid)
		if err != nil {
			return err
		}
		return nil
	})
	return result
}
开发者ID:dhedegaard,项目名称:notibot,代码行数:12,代码来源:notibot.go


示例15: checkForPermissions

func checkForPermissions(s *discordgo.Session,
	channelID string, roleID []string) bool {
	var ok bool
	if len(roleID) > 0 {
		_, ok = adminIds[roleID[0]]
		if ok == true {
			return ok
		}
	}
	s.ChannelMessageSend(channelID, fmt.Sprintf("Insuficient permissions"))
	return ok

}
开发者ID:Muckfoot,项目名称:Go,代码行数:13,代码来源:basic_bot.go


示例16: fetchPrimaryTextChannelID

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
}
开发者ID:dhedegaard,项目名称:notibot,代码行数:29,代码来源:notibot.go


示例17: updateRolesToDB

func updateRolesToDB(s *discordgo.Session, guild string) {
	roles, _ := s.GuildRoles(guild)
	pgDb := dbConn()
	tx, err := pgDb.Begin()
	checkErr(err)

	for i := 0; i < len(roles); i++ {
		_, err = tx.Exec("INSERT INTO roles(role, role_id) VALUES($1, $2)",
			roles[i].Name, roles[i].ID)
		checkErr(err)
	}
	tx.Commit()
	pgDb.Close()
}
开发者ID:Muckfoot,项目名称:Go,代码行数:14,代码来源:basic_bot.go


示例18: onGuildCreate

// the below method is invoked when the Discord Websocket API transmits
// a 'guildCreate' event to the bot
func onGuildCreate(s *discordgo.Session, event *discordgo.GuildCreate) {
	logrus.WithFields(logrus.Fields{
		"guildId":   event.ID,
		"guildName": event.Name,
		"joinedAt":  event.JoinedAt,
	}).Debug("Received guild create event from Discord Websocket API.")

	// send greet message to the appropriate general/lobby channel
	for _, channel := range event.Guild.Channels {
		if channel.ID == event.Guild.ID {
			s.ChannelMessageSend(channel.ID, "Pokemon Discord is ready for use! Type `!setTeam [name]` to set your Pokemon GO team.")
		}
	}
}
开发者ID:RyanMorrison04,项目名称:pokemon-discord,代码行数:16,代码来源:pokemon.go


示例19: PlaySound

// Play a sound
func PlaySound(s *discordgo.Session, play *Play, vc *discordgo.VoiceConnection) (err error) {
	log.WithFields(log.Fields{
		"play": play,
	}).Info("Playing sound")

	if vc == nil {
		vc, err = s.ChannelVoiceJoin(play.GuildID, play.ChannelID, false, false)
		// vc.Receive = false
		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Error("Failed to play sound")
			delete(queues, play.GuildID)
			return err
		}
	}

	// If we need to change channels, do that now
	if vc.ChannelID != play.ChannelID {
		vc.ChangeChannel(play.ChannelID, false, false)
		time.Sleep(time.Millisecond * 125)
	}

	// // Track stats for this play in redis
	// go rdTrackSoundStats(play)

	// Sleep for a specified amount of time before playing the sound
	time.Sleep(time.Millisecond * 32)

	// Play the sound
	play.Sound.Play(vc)

	// If this is chained, play the chained sound
	if play.Next != nil {
		PlaySound(s, play.Next, vc)
	}

	// If there is another song in the queue, recurse and play that
	if len(queues[play.GuildID]) > 0 {
		play := <-queues[play.GuildID]
		PlaySound(s, play, vc)
		return nil
	}

	// If the queue is empty, delete it
	time.Sleep(time.Millisecond * time.Duration(play.Sound.PartDelay))
	delete(queues, play.GuildID)
	vc.Disconnect()
	return nil
}
开发者ID:t11230,项目名称:airhornbot,代码行数:51,代码来源:sound_utils.go


示例20: ListenToDiscord

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
}
开发者ID:Xackery,项目名称:discordeq,代码行数:30,代码来源:discord.go



注:本文中的github.com/bwmarrin/discordgo.Session类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang discordgo.VoiceConnection类代码示例发布时间:2022-05-24
下一篇:
Golang discordgo.MessageCreate类代码示例发布时间:2022-05-24
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap