// this occurs when user selects a guild from the guild box private void lbGuilds_SelectedValueChanged(object sender, EventArgs e) { // check if the item is a guild, if not, don't do anything if (!(lbGuilds.SelectedItem is BotGuild bg)) { return; } // set the UI state this.SelectedGuild = bg; this.SelectedChannel = default(BotChannel); // clear the channel and message lists this.lbChannels.ClearSelected(); this.lbChannels.Items.Clear(); this.lbBanter.ClearSelected(); this.lbBanter.Items.Clear(); // populate the channel list var chns = bg.Guild.Channels.Values .Where(xc => xc.Type == ChannelType.Text) .OrderBy(xc => xc.Position) .Select(xc => new BotChannel(xc)); this.lbChannels.Items.AddRange(chns.Cast <object>().ToArray()); }
// this occurs when user selects a channel from the channel box private void lbChannels_SelectedValueChanged(object sender, EventArgs e) { // check if the item is a channel, if not, don't do anything if (!(lbChannels.SelectedItem is BotChannel bc)) { return; } // set the UI state this.SelectedChannel = bc; // clear the message list this.lbBanter.ClearSelected(); this.lbBanter.Items.Clear(); }
// this method will be ran on the bot's thread // it will take care of the initialization logic, as // well as actually handling the bot private async Task BotThreadCallback() { // this will start the bot await this.Bot.StartAsync().ConfigureAwait(false); // once the bot is started, we can enable the UI // elements again this.btBotctl.SetProperty(x => x.Enabled, true); this.btMsgSend.SetProperty(x => x.Enabled, true); this.tbMsg.SetProperty(x => x.Enabled, true); // here we wait indefinitely, or until the wait is // cancelled try { // the token will cancel the way once it's // requested await Task.Delay(-1, this.TokenSource.Token).ConfigureAwait(false); } catch { /* ignore the exception; it's expected */ } // this will stop the bot await this.Bot.StopAsync().ConfigureAwait(false); // once the bot is stopped, we can enable the UI // elements again this.btBotctl.SetProperty(x => x.Enabled, true); this.btMsgSend.SetProperty(x => x.Enabled, false); this.tbMsg.SetProperty(x => x.Enabled, false); this.SetProperty(x => x.Text, "Example WinForms Bot"); // furthermore, we need to clear the listboxes this.lbGuilds.InvokeAction(new Action(this.lbGuilds.Items.Clear)); this.lbChannels.InvokeAction(new Action(this.lbChannels.Items.Clear)); this.lbBanter.InvokeAction(new Action(this.lbBanter.Items.Clear)); // and reset the UI state this.SelectedGuild = default(BotGuild); this.SelectedChannel = default(BotChannel); // and finally, dispose of our bot stuff this.Bot = null; this.TokenSource = null; this.BotThread = null; }
// this is used by the send message method, to // asynchronously send the message private Task BotSendMessageCallback(string text, BotChannel chn) => chn.Channel.SendMessageAsync(text);