예제 #1
0
파일: main.go 프로젝트: Xe/betterbot
func main() {
	conn, err := common.Connect()
	if err != nil {
		panic(err)
	}
	uplink = conn

	discord, err := discordgo.New(*discordUser, *discordPass)
	if err != nil {
		panic(err)
	}

	uplink.Println("Connected to discord")

	discord.Open()
	discord.AddHandler(messageCreate)
	discord.UpdateStatus(0, "Golang message input queue")

	conn.Subscribe(uplink.ID+":input", func(subj, reply string, msg *common.Message) {
		switch msg.Kind {
		case "TextMessage":
			discord.ChannelMessageSend(msg.Destination, msg.Body)
		}
	})

	runtime.Goexit()
}
예제 #2
0
파일: main.go 프로젝트: 42wim/matterbridge
func main() {

	// Create a new Discord session using the provided login information.
	// Use discordgo.New(Token) to just use a token for login.
	dg, err := discordgo.New(Email, Password, Token)
	if err != nil {
		fmt.Println("error creating Discord session,", err)
		return
	}

	// Register messageCreate as a callback for the messageCreate events.
	dg.AddHandler(messageCreate)

	// Open the websocket and begin listening.
	err = dg.Open()
	if err != nil {
		fmt.Println("error opening connection,", err)
		return
	}

	fmt.Println("Bot is now running.  Press CTRL-C to exit.")
	// Simple way to keep program running until CTRL-C is pressed.
	<-make(chan struct{})
	return
}
예제 #3
0
파일: main.go 프로젝트: Xwth/h-bot
func connectToDiscord() {
	log.Println("Connecting to discord")

	//var err error
	c := config.Get()
	dg, err := discordgo.New(c.Email, c.Password, c.Token)

	if err != nil {
		log.Println(err.Error())
		return
	}

	// Register messageCreate as a callback for the OnMessageCreate event.
	dg.AddHandler(messageCreate)

	// Retry after broken websocket
	dg.ShouldReconnectOnError = true

	// Open websocket connection
	err = dg.Open()
	if err != nil {
		log.Println(err)
		return
	}

	log.Println("Connected")
}
예제 #4
0
파일: main.go 프로젝트: bwmarrin/discordgo
func main() {

	// Create a new Discord session using the provided bot token.
	dg, err := discordgo.New("Bot " + Token)
	if err != nil {
		fmt.Println("error creating Discord session,", err)
		return
	}

	// Get the account information.
	u, err := dg.User("@me")
	if err != nil {
		fmt.Println("error obtaining account details,", err)
	}

	// Store the account ID for later use.
	BotID = u.ID

	// Register messageCreate as a callback for the messageCreate events.
	dg.AddHandler(messageCreate)

	// Open the websocket and begin listening.
	err = dg.Open()
	if err != nil {
		fmt.Println("error opening connection,", err)
		return
	}

	fmt.Println("Bot is now running.  Press CTRL-C to exit.")
	// Simple way to keep program running until CTRL-C is pressed.
	<-make(chan struct{})
	return
}
예제 #5
0
파일: main.go 프로젝트: 42wim/matterbridge
func main() {

	// Create a new Discord session using the provided login information.
	// Use discordgo.New(Token) to just use a token for login.
	dg, err := discordgo.New(Email, Password, Token)
	if err != nil {
		fmt.Println("error creating Discord session,", err)
		return
	}

	bot, err := dg.User("@me")
	if err != nil {
		fmt.Println("error fetching the bot details,", err)
		return
	}

	BotID = bot.ID
	BotUsername = bot.Username
	changeAvatar(dg)

	fmt.Println("Bot is now running.  Press CTRL-C to exit.")
	// Simple way to keep program running until CTRL-C is pressed.
	<-make(chan struct{})
	return
}
예제 #6
0
func connectToDiscord() {
	log.Println("Connecting to discord")

	var err error

	c := config.Get()

	dg, err := discordgo.New(c.Email, c.Password, "Bot "+c.Token)
	if err != nil {
		log.Println(err.Error())
		return
	}

	// Register messageCreate as a callback for the OnMessageCreate event.
	dg.AddHandler(messageCreate)

	// Retry after broken websocket
	dg.ShouldReconnectOnError = true

	// Verify the Token is valid and grab user information
	dg.State.User, err = dg.User("@me")
	if err != nil {
		log.Printf("error fetching user information, %s\n", err)
	}

	// Open websocket connection
	err = dg.Open()
	if err != nil {
		log.Printf("error opening connection to Discord, %s\n", err)
		return
	}

	log.Println("Connected")
}
예제 #7
0
파일: new_basic.go 프로젝트: Skullever/digo
func main() {

	// Check for Username and Password CLI arguments.
	if len(os.Args) != 3 {
		fmt.Println("You must provide username and password as arguments. See below example.")
		fmt.Println(os.Args[0], " [username] [password]")
		return
	}

	// Call the helper function New() passing username and password command
	// line arguments. This returns a new Discord session, authenticates,
	// connects to the Discord data websocket, and listens for events.
	dg, err := discordgo.New(os.Args[1], os.Args[2])
	if err != nil {
		fmt.Println(err)
		return
	}

	// Register messageCreate as a callback for the OnMessageCreate event.
	dg.OnMessageCreate = messageCreate

	// Simple way to keep program running until any key press.
	var input string
	fmt.Scanln(&input)
	return
}
예제 #8
0
파일: main.go 프로젝트: iopred/discord-cli
func main() {
	//Initialize Config
	GetConfig()
	CheckState()
	State.InsertMode = false
	Clear()
	Header("V0.1")

	// Connect to Discord
	dg, err := discordgo.New(State.Username, State.Password)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Register messageCreate as a callback for the OnMessageCreate event.
	dg.OnMessageCreate = messageCreate

	// Open the websocket and begin listening.
	dg.Open()

	//Print Welcome as a sign that the user has logged in.
	Welcome(dg)

	//SetChannelState
	SetGuildState(dg)
	SetChannelState(dg)

	//Setup stdout logging
	rl, err := readline.NewEx(&readline.Config{
		Prompt:         "> ",
		UniqueEditLine: true,
	})
	if err != nil {
		panic(err)
	}

	defer rl.Close()
	log.SetOutput(rl.Stderr()) // let "log" write to l.Stderr instead of os.Stderr

	//Start Listening
	for {
		line, _ := rl.Readline()

		//QUIT
		if line == ":q" {
			break
		}

		line = ParseForCommands(line, dg)

		if line != "" {
			dg.ChannelMessageSend(State.Channel.ID, line)
		}
	}

	return
}
예제 #9
0
파일: main.go 프로젝트: bwmarrin/dca
func main() {

	// NOTE: All of the below fields are required for this example to work correctly.
	var (
		Email     = flag.String("e", "", "Discord account email.")
		Password  = flag.String("p", "", "Discord account password.")
		GuildID   = flag.String("g", "", "Guild ID")
		ChannelID = flag.String("c", "", "Channel ID")
		Folder    = flag.String("f", "", "Folder of files to play.")
		err       error
	)
	flag.Parse()

	// Connect to Discord
	discord, err := discordgo.New(*Email, *Password)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Open Websocket
	err = discord.Open()
	if err != nil {
		fmt.Println(err)
		return
	}

	// Connect to voice channel.
	// NOTE: Setting mute to false, deaf to true.
	err = discord.ChannelVoiceJoin(*GuildID, *ChannelID, false, true)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Hacky loop to prevent sending on a nil channel.
	// TODO: Find a better way.
	for discord.Voice.Ready == false {
		runtime.Gosched()
	}

	// Start loop and attempt to play all files in the given folder
	fmt.Println("Reading Folder: ", *Folder)
	files, _ := ioutil.ReadDir(*Folder)
	for _, f := range files {
		fmt.Println("PlayAudioFile:", f.Name())
		discord.UpdateStatus(0, f.Name())
		PlayAudioFile(discord.Voice, fmt.Sprintf("%s/%s", *Folder, f.Name()))
	}

	// Close connections
	discord.Voice.Close()
	discord.Close()

	return
}
예제 #10
0
func main() {
	logInfo("Logging in...")
	var err error
	var session *discordgo.Session
	if accountToken == "" {
		logInfo("Logging in with username and password...")
		session, err = discordgo.New(username, password)
	} else {
		logInfo("Logging in with bot account token...")
		session, err = discordgo.New(accountToken)
	}
	setupHandlers(session)
	panicOnErr(err)
	logInfo("Opening session...")
	err = session.Open()
	panicOnErr(err)
	logInfo("Sleeping...")
	<-make(chan struct{})
}
예제 #11
0
파일: main.go 프로젝트: 42wim/matterbridge
func main() {

	// Create a new Discord session using the provided login information.
	dg, err := discordgo.New(Email, Password)
	if err != nil {
		fmt.Println("error creating Discord session,", err)
		return
	}

	fmt.Printf("Your Authentication Token is:\n\n%s\n", dg.Token)
}
예제 #12
0
func main() {
	logrus.Info("pokemon-discord is starting up.")

	// parse the command-line arguments for the Discord bot token
	var (
		dToken      = flag.String("t", "", "Discord API token for bot usage")
		enableDebug = flag.Bool("d", false, "Enables or disables debug logging (default disabled)")
		err         error
	)
	flag.Parse()

	// validate command-line arguments
	if *dToken == "" {
		logrus.Fatal("Discord API authorization token was expected but never provided!")
		return
	}
	if *enableDebug {
		logrus.Info("Enabling debug logging as set by the command-line parameter.")
		logrus.SetLevel(logrus.DebugLevel)
	}

	// build Discord session
	discord, err = discordgo.New(*dToken)
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"capturedError": err,
		}).Fatal("An error occurred while creating a Discord session.")
		return
	}

	// add event handler functions
	logrus.Info("Adding Discord event handlers to bot.")
	discord.AddHandler(onReady)
	discord.AddHandler(onMessageCreate)
	discord.AddHandler(onGuildCreate)
	discord.AddHandler(onGuildMemberAdd)

	logrus.Info("Establishing Websocket connection with the Discord API.")
	err = discord.Open()
	if err != nil {
		logrus.WithFields(logrus.Fields{
			"capturedError": err,
		}).Fatal("An error occurred while connecting to the Discord Websocket API.")
		return
	}

	logrus.Info("pokemon-discord is ready.")

	// wait for OS signal to shutdown
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)
	<-c
}
예제 #13
0
func main() {

	// NOTE: All of the below fields are required for this example to work correctly.
	var (
		Email     = flag.String("e", "", "Discord account email.")
		Password  = flag.String("p", "", "Discord account password.")
		GuildID   = flag.String("g", "", "Guild ID")
		ChannelID = flag.String("c", "", "Channel ID")
		Filename  = flag.String("f", "", "Filename of file to play.")
		err       error
	)
	flag.Parse()

	// Connect to Discord
	discord, err := discordgo.New(*Email, *Password)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Connect to voice channel.
	// NOTE: Setting mute to false, deaf to true.
	err = discord.ChannelVoiceJoin(*GuildID, *ChannelID, false, true)
	if err != nil {
		fmt.Println(err)
		return
	}

	// This will block until Voice is ready.  This is not the most ideal
	// way to check and shouldn't be used outside of this example.
	for {
		if discord.Voice.Ready {
			break
		}
		fmt.Print(".")
		time.Sleep(1 * time.Second)
	}

	// streams file from ffmpeg then encodes with opus and sends via UDP
	// to Discord.
	dgvoice.PlayAudioFile(discord, *Filename)

	// Close connections
	discord.Voice.Close()
	discord.Close()

	return
}
예제 #14
0
func ExampleApplication() {

	// Authentication Token pulled from environment variable DG_TOKEN
	Token := os.Getenv("DG_TOKEN")
	if Token == "" {
		return
	}

	// Create a new Discordgo session
	dg, err := discordgo.New(Token)
	if err != nil {
		log.Println(err)
		return
	}

	// Create an new Application
	ap := &discordgo.Application{}
	ap.Name = "TestApp"
	ap.Description = "TestDesc"
	ap, err = dg.ApplicationCreate(ap)
	log.Printf("ApplicationCreate: err: %+v, app: %+v\n", err, ap)

	// Get a specific Application by it's ID
	ap, err = dg.Application(ap.ID)
	log.Printf("Application: err: %+v, app: %+v\n", err, ap)

	// Update an existing Application with new values
	ap.Description = "Whooooa"
	ap, err = dg.ApplicationUpdate(ap.ID, ap)
	log.Printf("ApplicationUpdate: err: %+v, app: %+v\n", err, ap)

	// create a new bot account for this application
	bot, err := dg.ApplicationBotCreate(ap.ID)
	log.Printf("BotCreate: err: %+v, bot: %+v\n", err, bot)

	// Get a list of all applications for the authenticated user
	apps, err := dg.Applications()
	log.Printf("Applications: err: %+v, apps : %+v\n", err, apps)
	for k, v := range apps {
		log.Printf("Applications: %d : %+v\n", k, v)
	}

	// Delete the application we created.
	err = dg.ApplicationDelete(ap.ID)
	log.Printf("Delete: err: %+v\n", err)

	return
}
예제 #15
0
파일: patbot.go 프로젝트: Luukdegram/patbot
func main() {

	// Check for Username and Password CLI arguments.
	if len(os.Args) != 3 {
		fmt.Println("You must provide username and password as arguments. See below example.")
		fmt.Println(os.Args[0], " [username] [password]")
		return
	}

	// Call the helper function New() passing username and password command
	// line arguments. This returns a new Discord session, authenticates,
	// connects to the Discord data websocket, and listens for events.
	dg, err := discordgo.New(os.Args[1], os.Args[2])
	if err != nil {
		fmt.Println(err)
		return
	}

	raffles = map[string]*Raffle{}
	commandHandler = NewCommandHandler(dg)
	RegisterCommands()
	commandHandler.Start()

	// Register messageCreate as a callback for the OnMessageCreate event.
	dg.AddHandler(messageCreate)

	// Open the websocket and begin listening.
	dg.Open()

	fmt.Println("Successfully started the bot, type \"quit\" to stop the bot.")

	running := true
	for running {
		var input string
		fmt.Scanln(&input)

		if input == "quit" {
			running = false
		}
	}

	return
}
예제 #16
0
파일: main.go 프로젝트: Rassilon216/dgvoice
func main() {

	// NOTE: All of the below fields are required for this example to work correctly.
	var (
		Email     = flag.String("e", "", "Discord account email.")
		Password  = flag.String("p", "", "Discord account password.")
		GuildID   = flag.String("g", "", "Guild ID")
		ChannelID = flag.String("c", "", "Channel ID")
		err       error
	)
	flag.Parse()

	// Connect to Discord
	discord, err := discordgo.New(*Email, *Password)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Open Websocket
	err = discord.Open()
	if err != nil {
		fmt.Println(err)
		return
	}

	// Connect to voice channel.
	// NOTE: Setting mute to false, deaf to true.
	dgv, err := discord.ChannelVoiceJoin(*GuildID, *ChannelID, false, true)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Starts echo
	Echo(dgv)

	// Close connections
	dgv.Close()
	discord.Close()

	return
}
예제 #17
0
파일: main.go 프로젝트: dayln/gopherbot
func main() {
	dg, err := discordgo.New(os.Getenv("DIS_TOKEN"))
	if err != nil {
		fmt.Println(err)
		return
	}
	//set a call back func OnMessageCreate
	dg.AddHandler(messageCreate)
	err = dg.Open()
	if err != nil {
		fmt.Println(err)
		return
	}
	st, err := dg.UserGuilds()
	fmt.Printf("%s", st[0].Name)
	// Simple way to keep program running until any key press.
	var input string
	fmt.Scanln(&input)
	return
}
예제 #18
0
파일: main.go 프로젝트: 42wim/matterbridge
func main() {
	if token == "" {
		fmt.Println("No token provided. Please run: airhorn -t <bot token>")
		return
	}

	// Load the sound file.
	err := loadSound()
	if err != nil {
		fmt.Println("Error loading sound: ", err)
		fmt.Println("Please copy $GOPATH/src/github.com/bwmarrin/examples/airhorn/airhorn.dca to this directory.")
		return
	}

	// Create a new Discord session using the provided token.
	dg, err := discordgo.New(token)
	if err != nil {
		fmt.Println("Error creating Discord session: ", err)
		return
	}

	// Register ready as a callback for the ready events.
	dg.AddHandler(ready)

	// Register messageCreate as a callback for the messageCreate events.
	dg.AddHandler(messageCreate)

	// Register guildCreate as a callback for the guildCreate events.
	dg.AddHandler(guildCreate)

	// Open the websocket and begin listening.
	err = dg.Open()
	if err != nil {
		fmt.Println("Error opening Discord session: ", err)
	}

	fmt.Println("Airhorn is now running.  Press CTRL-C to exit.")
	// Simple way to keep program running until CTRL-C is pressed.
	<-make(chan struct{})
	return
}
예제 #19
0
func (b *bdiscord) Connect() error {
	var err error
	flog.Info("Connecting")
	if !strings.HasPrefix(b.Config.Token, "Bot ") {
		b.Config.Token = "Bot " + b.Config.Token
	}
	b.c, err = discordgo.New(b.Config.Token)
	if err != nil {
		flog.Debugf("%#v", err)
		return err
	}
	flog.Info("Connection succeeded")
	b.c.AddHandler(b.messageCreate)
	err = b.c.Open()
	if err != nil {
		flog.Debugf("%#v", err)
		return err
	}
	guilds, err := b.c.UserGuilds()
	if err != nil {
		flog.Debugf("%#v", err)
		return err
	}
	userinfo, err := b.c.User("@me")
	if err != nil {
		flog.Debugf("%#v", err)
		return err
	}
	b.Nick = userinfo.Username
	for _, guild := range guilds {
		if guild.Name == b.Config.Server {
			b.Channels, err = b.c.GuildChannels(guild.ID)
			if err != nil {
				flog.Debugf("%#v", err)
				return err
			}
		}
	}
	return nil
}
예제 #20
0
//Starts discord connection and sets handlers and behavior
func discordStart(c *discordConfig) {
	//Updates discordCfg variable with c parameter data
	//For future use outside this function
	discordCfg = c

	//Connect to discord with token
	var err error
	discord, err = discordgo.New(c.Token)
	if err != nil {
		log.Fatal("Error initializing discord in discordStart() function!\n", err)
	}

	//Set behavior & assign handlers
	discord.Debug = c.Debug
	discord.AddHandler(discordMsgHandler)
	discord.AddHandler(discordReadyHandler)
	discord.AddHandler(discordNewGuildHandler)
	discord.AddHandler(discordLeaveGuildHandler)
	discord.AddHandler(discordNewChannelHandler)
	discord.AddHandler(discordLeaveChannelHandler)
	discord.AddHandler(discordChannelUpdateHandler)
	discord.Open() //Opens discord connection
}
예제 #21
0
파일: discord.go 프로젝트: TF2Stadium/Helen
func init() {
	token := config.Constants.DiscordToken
	guildId := config.Constants.DiscordGuildId
	if token == "" || guildId == "" {
		return
	}

	var err error
	Discord, err = dg.New(token)
	if err != nil {
		logrus.Fatal(err)
		return
	}

	guild, err := Discord.Guild(guildId)
	if err != nil {
		Discord = nil
		logrus.Fatal(err)
		return
	}

	rawChannels, err := Discord.GuildChannels(guildId)
	if err != nil {
		Discord = nil
		logrus.Fatal(err)
		return
	}

	for _, emoji := range guild.Emojis {
		emojis[emoji.Name] = fmt.Sprintf("<:%s:%s>", emoji.Name, emoji.ID)
	}
	for _, channel := range rawChannels {
		channels[channel.Name] = channel
	}
	logrus.Infof("Discord: Loaded %d channels, %d emojis", len(rawChannels), len(guild.Emojis))
}
예제 #22
0
파일: main.go 프로젝트: bwmarrin/disgord
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/bwmarrin/discordgo"
)

// Version is a constant that stores the Disgord version information.
const Version = "v0.0.0-alpha"

// Session is declared in the global space so it can be easily used
// throughout this program.
// In this use case, there is no error that would be returned.
var Session, _ = discordgo.New()

// Read in all configuration options from both environment variables and
// command line arguments.
func init() {

	// Discord Authentication Token
	Session.Token = os.Getenv("DG_TOKEN")
	if Session.Token == "" {
		flag.StringVar(&Session.Token, "t", "", "Discord Authentication Token")
	}
}

func main() {

	// Declare any variables needed later.
예제 #23
0
func main() {
	var (
		Token      = flag.String("t", "", "Discord Authentication Token")
		Redis      = flag.String("r", "", "Redis Connection String")
		Shard      = flag.String("s", "", "Shard ID")
		ShardCount = flag.String("c", "", "Number of shards")
		Owner      = flag.String("o", "", "Owner ID")
		err        error
	)
	flag.Parse()

	if *Owner != "" {
		OWNER = *Owner
	}

	// Preload all the sounds
	log.Info("Preloading sounds...")
	for _, coll := range COLLECTIONS {
		coll.Load()
	}

	// If we got passed a redis server, try to connect
	if *Redis != "" {
		log.Info("Connecting to redis...")
		rcli = redis.NewClient(&redis.Options{Addr: *Redis, DB: 0})
		_, err = rcli.Ping().Result()

		if err != nil {
			log.WithFields(log.Fields{
				"error": err,
			}).Fatal("Failed to connect to redis")
			return
		}
	}

	// Create a discord session
	log.Info("Starting discord session...")
	discord, err = discordgo.New(*Token)
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("Failed to create discord session")
		return
	}

	// Set sharding info
	discord.ShardID, _ = strconv.Atoi(*Shard)
	discord.ShardCount, _ = strconv.Atoi(*ShardCount)

	if discord.ShardCount <= 0 {
		discord.ShardCount = 1
	}

	discord.AddHandler(onReady)
	discord.AddHandler(onGuildCreate)
	discord.AddHandler(onMessageCreate)

	err = discord.Open()
	if err != nil {
		log.WithFields(log.Fields{
			"error": err,
		}).Fatal("Failed to create discord websocket connection")
		return
	}

	// We're running!
	log.Info("AIRHORNBOT is ready to horn it up.")

	// Wait for a signal to quit
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, os.Kill)
	<-c
}
예제 #24
0
파일: basic_bot.go 프로젝트: Muckfoot/Go
func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	var err error

	logf, err := os.OpenFile("bot-erros.log",
		os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		panic(err)
	}

	defer logf.Close()
	log.SetOutput(logf)
	pgDb := dbConn()
	rows, err := pgDb.Query(
		`SELECT role_id, role FROM roles
		WHERE role IN ('Mods', 'Admin', 'Banned') `)
	checkErr(err)

	adminIds = make(map[string]int)
	for rows.Next() {
		var id string
		var role string
		rows.Scan(&id, &role)
		if role == "Banned" {
			roleBannedId = id
		} else {
			adminIds[id] = 1
		}
	}

	rows.Close()
	pgDb.Close()

	token := ""

	dg, err := discordgo.New(token)
	checkErr(err)

	dg.AddHandler(messageCreate)
	// dg.AddHandler(voiceServerUpdate) //USELESS right now.
	dg.Open()

	go func() {
		for {
			for !pullFromReddit(dg) {
			}
			time.Sleep(time.Minute * 3)
		}
	}()

	go checkBans(dg)
	go storeMessageContent()

	for {
		if quit {
			break
		}
		runtime.GC()
		debug.FreeOSMemory()
		time.Sleep(time.Second * 2)
	}

}
예제 #25
0
func Initialize(Token string) {
	dbauth, _ := ioutil.ReadFile("db.auth")
	isdebug, err := ioutil.ReadFile("isdebug")
	rand.Seed(time.Now().UTC().Unix())

	sb = &SweetieBot{
		version:            Version{0, 8, 15, 4},
		Debug:              (err == nil && len(isdebug) > 0),
		Owners:             map[uint64]bool{95585199324143616: true, 98605232707080192: true},
		RestrictedCommands: map[string]bool{"search": true, "lastping": true, "setstatus": true},
		NonServerCommands:  map[string]bool{"roll": true, "episodegen": true, "bestpony": true, "episodequote": true, "help": true, "listguilds": true, "update": true, "announce": true, "dumptables": true, "defaultserver": true},
		MainGuildID:        98609319519453184,
		DBGuilds:           map[uint64]bool{98609319519453184: true, 164188105031680000: true, 105443346608095232: true},
		DebugChannels:      map[string]string{"98609319519453184": "141710126628339712", "105443346608095232": "200112394494541824"},
		GuildChannels:      make(map[string]*GuildInfo),
		quit:               false,
		guilds:             make(map[uint64]*GuildInfo),
		LastMessages:       make(map[string]int64),
		MaxConfigSize:      1000000,
		changelog: map[int]string{
			AssembleVersion(0, 8, 15, 4): "- ReplaceMentions now breaks role pings (but does not resolve them)",
			AssembleVersion(0, 8, 15, 3): "- Use database to resolve users to improve responsiveness",
			AssembleVersion(0, 8, 15, 2): "- Improved !vote error messages",
			AssembleVersion(0, 8, 15, 1): "- Quickconfig actually sets silentrole now",
			AssembleVersion(0, 8, 15, 0): "- Use 64-bit integer conversion",
			AssembleVersion(0, 8, 14, 6): "- Allow adding birthdays on current day\n-Update avatar change function",
			AssembleVersion(0, 8, 14, 5): "- Allow exact string matching on !import",
			AssembleVersion(0, 8, 14, 4): "- Added !import\n- Added Importable option\n- Make !collections more useful",
			AssembleVersion(0, 8, 14, 3): "- Allow pinging multiple groups via group1+group2",
			AssembleVersion(0, 8, 14, 2): "- Fix !createpoll unique option key\n- Add !addoption",
			AssembleVersion(0, 8, 14, 1): "- Clean up !poll",
			AssembleVersion(0, 8, 14, 0): "- Added !poll, !vote, !createpoll, !deletepoll and !results commands",
			AssembleVersion(0, 8, 13, 1): "- Fixed !setconfig rules",
			AssembleVersion(0, 8, 13, 0): "- Added changelog\n- Added !rules command",
			AssembleVersion(0, 8, 12, 0): "- Added temporary silences",
			AssembleVersion(0, 8, 11, 5): "- Added \"dumbass\" to Sweetie Bot's vocabulary",
			AssembleVersion(0, 8, 11, 4): "- Display channels in help for commands",
			AssembleVersion(0, 8, 11, 3): "- Make defaultserver an independent command",
			AssembleVersion(0, 8, 11, 2): "- Add !defaultserver command",
			AssembleVersion(0, 8, 11, 1): "- Fix !autosilence behavior",
			AssembleVersion(0, 8, 11, 0): "- Replace mentions in !search\n- Add temporary ban to !ban command",
			AssembleVersion(0, 8, 10, 0): "- !ping now accepts newlines\n- Added build version to make moonwolf happy",
			AssembleVersion(0, 8, 9, 0):  "- Add silence message for Tawmy\n- Make silence message ping user\n- Fix #27 (Sweetie Bot explodes if you search nothing)\n- Make !lastseen more reliable",
			AssembleVersion(0, 8, 8, 0):  "- Log all commands sent to SB in DB-enabled servers",
			AssembleVersion(0, 8, 7, 0):  "- Default to main server for PMs if it exists\n- Restrict PM commands to the server you belong in (fix #26)\n- Make spam deletion lookback configurable\n- Make !quickconfig complain if permissions are wrong\n- Add giant warning label for Tawmy\n- Prevent parse time crash\n- Make readme more clear on how things work\n- Sort !listguild by user count\n- Fallback to search all users if SB can't find one in the current server",
			AssembleVersion(0, 8, 6, 0):  "- Add full timezone support\n- Deal with discord's broken permissions\n- Improve timezone help messages",
			AssembleVersion(0, 8, 5, 0):  "- Add !userinfo\n- Fix #15 (Lock down !removeevent)\n- Fix guildmember query\n- Use nicknames in more places",
			AssembleVersion(0, 8, 4, 0):  "- Update readme, remove disablebored\n- Add delete command",
			AssembleVersion(0, 8, 3, 0):  "- Actually seed random number generator because Cloud is a F*****G IDIOT\n- Allow newlines in commands\n- Bored module is now fully programmable\n- Display user ID in !aka\n- Hopefully stop sweetie from being an emo teenager\n- Add additional stupid proofing\n- Have bored commands override all restrictions",
			AssembleVersion(0, 8, 2, 0):  "- Enable multi-server message logging\n- Extend !searchquote\n- Attach !lastping to current server\n- Actually make aliases work with commands",
			AssembleVersion(0, 8, 1, 0):  "- Add dynamic collections\n- Add quotes\n- Prevent !aka command from spawning evil twins\n- Add !removealias\n- Use nicknames where possible\n- Fix off by one error\n- Sanitize !search output ",
			AssembleVersion(0, 8, 0, 0):  "- Appease the dark gods of discord's API\n- Allow sweetiebot to track nicknames\n- update help\n- Include nickname in searches",
		},
	}

	rand.Intn(10)
	for i := 0; i < 20+rand.Intn(20); i++ {
		rand.Intn(50)
	}

	db, err := DB_Load(&Log{0, nil}, "mysql", strings.TrimSpace(string(dbauth)))
	if err != nil {
		fmt.Println("Error loading database", err.Error())
		return
	}

	sb.db = db
	sb.dg, err = discordgo.New("Bot " + Token)
	if err != nil {
		fmt.Println("Error creating discord session", err.Error())
		return
	}

	sb.dg.AddHandler(SBReady)
	sb.dg.AddHandler(SBTypingStart)
	sb.dg.AddHandler(SBMessageCreate)
	sb.dg.AddHandler(SBMessageUpdate)
	sb.dg.AddHandler(SBMessageDelete)
	sb.dg.AddHandler(SBMessageAck)
	sb.dg.AddHandler(SBUserUpdate)
	sb.dg.AddHandler(SBPresenceUpdate)
	sb.dg.AddHandler(SBVoiceStateUpdate)
	sb.dg.AddHandler(SBGuildUpdate)
	sb.dg.AddHandler(SBGuildMemberAdd)
	sb.dg.AddHandler(SBGuildMemberRemove)
	sb.dg.AddHandler(SBGuildMemberUpdate)
	sb.dg.AddHandler(SBGuildBanAdd)
	sb.dg.AddHandler(SBGuildBanRemove)
	sb.dg.AddHandler(SBGuildCreate)
	sb.dg.AddHandler(SBChannelCreate)
	sb.dg.AddHandler(SBChannelDelete)

	sb.db.LoadStatements()
	fmt.Println("Finished loading database statements")

	if sb.Debug { // The server does not necessarily tie a standard input to the program
		go WaitForInput()
	}

	//BuildMarkov(1, 1)
	//return
	err = sb.dg.Open()
	if err == nil {
		fmt.Println("Connection established")
		for !sb.quit {
			time.Sleep(400 * time.Millisecond)
		}
	} else {
		fmt.Println("Error opening websocket connection: ", err.Error())
	}

	fmt.Println("Sweetiebot quitting")
	sb.dg.Close()
	sb.db.Close()
}
예제 #26
0
파일: bot.go 프로젝트: dayln/gopherbot
//Login and store the session token. Returns error if failed to authenticate
func (b *Bot) Login() error {
	var err error
	b.dg, err = discordgo.New(b.uname, b.password)
	return err
}
예제 #27
0
파일: main.go 프로젝트: 42wim/matterbridge
func main() {

	var err error
	// Create a new Discord session using the provided login information.
	dg, err := discordgo.New(Email, Password, Token)
	if err != nil {
		fmt.Println("error creating Discord session,", err)
		return
	}

	// If -l set, only display a list of existing applications
	// for the given account.
	if ListOnly {
		aps, err2 := dg.Applications()
		if err2 != nil {
			fmt.Println("error fetching applications,", err)
			return
		}

		for k, v := range aps {
			fmt.Printf("%d : --------------------------------------\n", k)
			fmt.Printf("ID: %s\n", v.ID)
			fmt.Printf("Name: %s\n", v.Name)
			fmt.Printf("Secret: %s\n", v.Secret)
			fmt.Printf("Description: %s\n", v.Description)
		}
		return
	}

	// if -d set, delete the given Application
	if DeleteID != "" {
		err = dg.ApplicationDelete(DeleteID)
		if err != nil {
			fmt.Println("error deleting application,", err)
		}
		return
	}

	// Create a new application.
	ap := &discordgo.Application{}
	ap.Name = AppName
	ap, err = dg.ApplicationCreate(ap)
	if err != nil {
		fmt.Println("error creating new applicaiton,", err)
		return
	}

	fmt.Printf("Application created successfully:\n")
	fmt.Printf("ID: %s\n", ap.ID)
	fmt.Printf("Name: %s\n", ap.Name)
	fmt.Printf("Secret: %s\n\n", ap.Secret)

	// Create the bot account under the application we just created
	bot, err := dg.ApplicationBotCreate(ap.ID)
	if err != nil {
		fmt.Println("error creating bot account,", err)
		return
	}

	fmt.Printf("Bot account created successfully.\n")
	fmt.Printf("ID: %s\n", bot.ID)
	fmt.Printf("Username: %s\n", bot.Username)
	fmt.Printf("Token: %s\n\n", bot.Token)
	fmt.Println("Please save the above posted info in a secure place.")
	fmt.Println("You will need that information to login with your bot account.")

	return
}
예제 #28
0
func (d *Discord) Connect(username string, password string) (err error) {
	if d.instance, err = discordgo.New(username, password); err != nil {
		return
	}
	return
}