Advertisement
Guest User

Untitled

a guest
Dec 6th, 2019
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 12.38 KB | None | 0 0
  1.  
  2.  
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Linq;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. using DSharpPlus;
  11. using DSharpPlus.Entities;
  12. using DSharpPlus.EventArgs;
  13.  
  14. namespace DSPlus.Examples
  15. {
  16. // the class holding the form logic
  17. public partial class FormBot : Form
  18. {
  19. // this will hold the thread on which the bot will run
  20. private Task BotThread { get; set; }
  21.  
  22. // this will hold the bot itself
  23. private Bot Bot { get; set; }
  24.  
  25. // this will hold a token required to make the bot quit cleanly
  26. private CancellationTokenSource TokenSource { get; set; }
  27.  
  28. // these are for UI state
  29. private BotGuild SelectedGuild { get; set; }
  30. private BotChannel SelectedChannel { get; set; }
  31.  
  32.  
  33. public DiscordMember CurrentMember { get; }
  34. public FormBot()
  35. {
  36. InitializeComponent();
  37. }
  38.  
  39. // this occurs when user selects a guild from the guild box
  40. private void lbGuilds_SelectedValueChanged(object sender, EventArgs e)
  41. {
  42. // check if the item is a guild, if not, don't do anything
  43. if (!(lbGuilds.SelectedItem is BotGuild bg))
  44. return;
  45.  
  46. // set the UI state
  47. this.SelectedGuild = bg;
  48. this.SelectedChannel = default(BotChannel);
  49.  
  50. // clear the channel and message lists
  51. this.lbChannels.ClearSelected();
  52. this.lbChannels.Items.Clear();
  53. this.lbBanter.ClearSelected();
  54. this.lbBanter.Items.Clear();
  55.  
  56. // populate the channel list
  57. var chns = bg.Guild.Channels
  58. .Where(xc => xc.Type == ChannelType.Text)
  59. .OrderBy(xc => xc.Position)
  60. .Select(xc => new BotChannel(xc));
  61. this.lbChannels.Items.AddRange(chns.Cast<object>().ToArray());
  62.  
  63. // var number = member.Guild.Members;
  64. // var allmebs = bg.Guild.Members;
  65. var allmebs = bg.Guild.Members
  66. .Select(xc1 => xc1.Id
  67. );
  68. this.listBox1.Items.AddRange(allmebs.Cast<object>().ToArray());
  69.  
  70.  
  71.  
  72. }
  73.  
  74. // this occurs when user selects a channel from the channel box
  75. private void lbChannels_SelectedValueChanged(object sender, EventArgs e)
  76. {
  77. // check if the item is a channel, if not, don't do anything
  78. if (!(lbChannels.SelectedItem is BotChannel bc))
  79. return;
  80.  
  81. // set the UI state
  82. this.SelectedChannel = bc;
  83.  
  84. // clear the message list
  85. this.lbBanter.ClearSelected();
  86. this.lbBanter.Items.Clear();
  87. }
  88.  
  89. // this occurs when user presses the send message button
  90. private void btMsgSend_Click(object sender, EventArgs e)
  91. => this.SendMessage();
  92.  
  93. // this occurs when user presses a button inside the message
  94. // text box, we use that to handle enter key press
  95. private void tbMsg_KeyPress(object sender, KeyPressEventArgs e)
  96. {
  97. // check if the key pressed was enter
  98. if (e.KeyChar == (char)Keys.Return)
  99. {
  100. // if yes, mark the event as handled, and send
  101. // the message
  102. e.Handled = true;
  103. this.SendMessage();
  104. }
  105. }
  106.  
  107. // this occurs when user presses the start/stop button
  108. private void btBotctl_Click(object sender, EventArgs e)
  109. {
  110. // lock the controls until they can be used again
  111. this.btBotctl.Enabled = false;
  112. this.tbMsg.Enabled = false;
  113. this.btMsgSend.Enabled = false;
  114.  
  115. // check if a bot thread is running
  116. if (this.BotThread == null)
  117. {
  118. // start the bot
  119.  
  120. // change the button's text to indicate it now
  121. // stops the bot instead
  122. this.btBotctl.Text = "Stop the bot";
  123.  
  124. // create the bot container
  125. this.Bot = new Bot(this.tbToken.Text);
  126.  
  127. // hook all the bot events
  128. this.Bot.Client.Ready += this.Bot_Ready;
  129. this.Bot.Client.GuildAvailable += this.Bot_GuildAvailable;
  130. this.Bot.Client.GuildCreated += this.Bot_GuildCreated;
  131. this.Bot.Client.GuildUnavailable += this.Bot_GuildUnavailable;
  132. this.Bot.Client.GuildDeleted += this.Bot_GuildDeleted;
  133. this.Bot.Client.MessageCreated += this.Bot_MessageCreated;
  134. this.Bot.Client.ClientErrored += this.Bot_ClientErrored;
  135.  
  136. // create a cancellation token, this will be used
  137. // to cancel the infinite delay task
  138. this.TokenSource = new CancellationTokenSource();
  139.  
  140. // finally, start the thread with the bot
  141. this.BotThread = Task.Run(this.BotThreadCallback);
  142. }
  143. else
  144. {
  145. // stop the bot
  146.  
  147. // change the button's text to indicate it now
  148. // starts the bot instead
  149. this.btBotctl.Text = "Start the bot";
  150.  
  151. // request cancelling the task preventing the
  152. // bot from stopping
  153. // this will effectively stop the bot
  154. this.TokenSource.Cancel();
  155. }
  156.  
  157. // clear the token text box, we don't need it anymore
  158. this.tbToken.Text = "";
  159. }
  160.  
  161. // this is called by the send button and message textbox
  162. // key press handler
  163. private void SendMessage()
  164. {
  165. // check if we have a channel selected, if not, do
  166. // nothing
  167. if (this.SelectedChannel.Channel == null)
  168. return;
  169.  
  170. // check if a message was typed in at all, if not,
  171. // do nothing
  172. if (string.IsNullOrWhiteSpace(this.tbMsg.Text))
  173. return;
  174.  
  175. // start an asynchronous task which will send the
  176. // message, and once it's done, set the message
  177. // textbox's text to empty using the UI thread
  178. _ = Task.Run(() => this.BotSendMessageCallback(this.tbMsg.Text, this.SelectedChannel))
  179. .ContinueWith(t => this.tbMsg.SetProperty(x => x.Text, ""));
  180. }
  181.  
  182. // this method will be ran on the bot's thread
  183. // it will take care of the initialization logic, as
  184. // well as actually handling the bot
  185. private async Task BotThreadCallback()
  186. {
  187. // this will start the bot
  188. await this.Bot.StartAsync().ConfigureAwait(false);
  189.  
  190. // once the bot is started, we can enable the UI
  191. // elements again
  192. this.btBotctl.SetProperty(x => x.Enabled, true);
  193. this.btMsgSend.SetProperty(x => x.Enabled, true);
  194. this.tbMsg.SetProperty(x => x.Enabled, true);
  195.  
  196. // here we wait indefinitely, or until the wait is
  197. // cancelled
  198. try
  199. {
  200. // the token will cancel the way once it's
  201. // requested
  202. await Task.Delay(-1, this.TokenSource.Token).ConfigureAwait(false);
  203. }
  204. catch { /* ignore the exception; it's expected */ }
  205.  
  206. // this will stop the bot
  207. await this.Bot.StopAsync().ConfigureAwait(false);
  208.  
  209. // once the bot is stopped, we can enable the UI
  210. // elements again
  211. this.btBotctl.SetProperty(x => x.Enabled, true);
  212. this.btMsgSend.SetProperty(x => x.Enabled, false);
  213. this.tbMsg.SetProperty(x => x.Enabled, false);
  214. this.SetProperty(x => x.Text, "Example WinForms Bot");
  215.  
  216. // furthermore, we need to clear the listboxes
  217. this.lbGuilds.InvokeAction(new Action(this.lbGuilds.Items.Clear));
  218. this.lbChannels.InvokeAction(new Action(this.lbChannels.Items.Clear));
  219. this.lbBanter.InvokeAction(new Action(this.lbBanter.Items.Clear));
  220.  
  221. // and reset the UI state
  222. this.SelectedGuild = default(BotGuild);
  223. this.SelectedChannel = default(BotChannel);
  224.  
  225. // and finally, dispose of our bot stuff
  226. this.Bot = null;
  227. this.TokenSource = null;
  228. this.BotThread = null;
  229. }
  230.  
  231. // this is used by the send message method, to
  232. // asynchronously send the message
  233. private Task BotSendMessageCallback(string text, BotChannel chn)
  234. => chn.Channel.SendMessageAsync(text);
  235.  
  236. // this handles the bot's ready event
  237. private Task Bot_Ready(ReadyEventArgs e)
  238. {
  239. // set the window title to indicate we are connected
  240. this.SetProperty(xf => xf.Text, "Example WinForms Bot (connected)");
  241. return Task.CompletedTask;
  242. }
  243.  
  244. // called when any of the bot's guilds becomes available
  245. private Task Bot_GuildAvailable(GuildCreateEventArgs e)
  246. {
  247. // add the guild to the bot's guild collection
  248. this.lbGuilds.InvokeAction(new Action<BotGuild>(this.AddGuild), new BotGuild(e.Guild));
  249. return Task.CompletedTask;
  250. }
  251.  
  252. // called when any of the bot joins a guild
  253. private Task Bot_GuildCreated(GuildCreateEventArgs e)
  254. {
  255. // add the guild to the bot's guild collection
  256. this.lbGuilds.InvokeAction(new Action<BotGuild>(this.AddGuild), new BotGuild(e.Guild));
  257. return Task.CompletedTask;
  258. }
  259.  
  260. // called when any of the bot's guilds becomes unavailable
  261. private Task Bot_GuildUnavailable(GuildDeleteEventArgs e)
  262. {
  263. // remove the guild from the bot's guild collection
  264. this.lbGuilds.InvokeAction(new Action<ulong>(this.RemoveGuild), e.Guild.Id);
  265. return Task.CompletedTask;
  266. }
  267.  
  268. // called when any of the bot leaves a guild
  269. private Task Bot_GuildDeleted(GuildDeleteEventArgs e)
  270. {
  271. // remove the guild from the bot's guild collection
  272. this.lbGuilds.InvokeAction(new Action<ulong>(this.RemoveGuild), e.Guild.Id);
  273. return Task.CompletedTask;
  274. }
  275.  
  276. // called when the bot receives a message
  277. private Task Bot_MessageCreated(MessageCreateEventArgs e)
  278. {
  279. // if this message is not meant for the currently
  280. // selected channel, ignore it
  281. if (this.SelectedChannel.Channel?.Id != e.Channel.Id)
  282. return Task.CompletedTask;
  283.  
  284. // if it is, add it to the banter box
  285. this.lbBanter.InvokeAction(new Action<BotMessage>(this.AddMessage), new BotMessage(e.Message));
  286.  
  287. return Task.CompletedTask;
  288. }
  289.  
  290. // called when an unhandled exception occurs in any of the
  291. // event handlers
  292. private Task Bot_ClientErrored(ClientErrorEventArgs e)
  293. {
  294. // show a message box by dispatching it to the UI thread
  295. this.InvokeAction(new Action(() => MessageBox.Show(this, $"Exception in {e.EventName}: {e.Exception.ToString()}", "Unhandled exception in the bot", MessageBoxButtons.OK, MessageBoxIcon.Warning)));
  296. return Task.CompletedTask;
  297. }
  298.  
  299. // this is called when a new guild becomes available
  300. private void AddGuild(BotGuild gld)
  301. => this.lbGuilds.Items.Add(gld);
  302.  
  303. // this is called when a guild is no longer available
  304. private void RemoveGuild(ulong id)
  305. {
  306. var gld = this.lbGuilds.Items.OfType<BotGuild>().FirstOrDefault(xbg => xbg.Id == id);
  307. this.lbGuilds.Items.Remove(gld);
  308. }
  309.  
  310.  
  311. // this is called to add a message to the banter box
  312. private void AddMessage(BotMessage msg)
  313. {
  314. this.lbBanter.Items.Add(msg);
  315. this.lbBanter.SelectedItem = msg;
  316. }
  317.  
  318. private void lbBanter_SelectedIndexChanged(object sender, EventArgs e)
  319. {
  320.  
  321. }
  322.  
  323. private void lbGuilds_SelectedIndexChanged(object sender, EventArgs e)
  324. {
  325.  
  326. }
  327.  
  328. private void tbMsg_TextChanged(object sender, EventArgs e)
  329. {
  330.  
  331. }
  332. }
  333. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement