# C# Discord bot紀錄 ## Discord是什麼? * Discord是一款專為社群設計的免費網路即時通話軟體與數位發行平台,主要針對遊戲玩家、教育人士及商業人士,使用者之間可以在軟體的聊天頻道通過資訊、圖片、影片和音訊進行互動。這款軟體可以在Microsoft Windows、macOS、Android、iOS、Linux和網頁上執行。 -- [維基百科](https://zh.wikipedia.org/wiki/Discord) ## 先行作業 * 建立資料夾,並選擇專案 ![](https://i.imgur.com/qOqTgk8.png) * 點擊......下一步 ![](https://i.imgur.com/wLQ8yu5.png) * 點選管理NuGet套件 ![](https://i.imgur.com/7754TGi.png) * 先輸入json ![](https://i.imgur.com/L9mLYWJ.png) * 點擊右邊的齒輪 ![](https://i.imgur.com/o0AtgVu.png) * 接著輸入 ```shell= https://api.nuget.org/v3/index.json ``` * 找到 Discord-Net and download ![](https://i.imgur.com/6Flh7QD.png) ## Discord-bot Developer * 參考 :::success [使用bot.py建立起你的第一個機器人](https://ithelp.ithome.com.tw/articles/10262736) ::: * token ![](https://i.imgur.com/NGg6Mn5.png) ## 撰寫機器人 * 先上碼 ```csharp= using Discord; using Discord.WebSocket; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DC_Bot { class Program { public static void Main(string[] args) => new Program().MainAsync().GetAwaiter().GetResult(); private DiscordSocketClient _client; public async Task MainAsync() { _client = new DiscordSocketClient(); _client.MessageReceived += CommandHandler; _client.Log += Log; var token = File.ReadAllText("token.txt"); await _client.LoginAsync(TokenType.Bot, token); await _client.StartAsync(); await Task.Delay(-1); } private Task Log(LogMessage msg) { Console.WriteLine(msg.ToString()); return Task.CompletedTask; } } } ``` * 按F5確認可以動,結果如下 ![](https://i.imgur.com/PtTeREu.png) * 打開Discord確認是否上線 ![](https://i.imgur.com/uORswqJ.png) ```csharp= using Discord; using Discord.WebSocket; using System; using System.IO; using System.Threading.Tasks; namespace DC_Bot { class Program { // private Task Log(LogMessage msg) { Console.WriteLine(msg.ToString()); return Task.CompletedTask; } private Task CommandHandler(SocketMessage message) { string command = ""; int lengthOfCommand = -1; if (!message.Content.StartsWith('!')) return Task.CompletedTask; if (message.Author.IsBot) return Task.CompletedTask; if (message.Content.Contains(' ')) lengthOfCommand = message.Content.IndexOf(' '); else lengthOfCommand = message.Content.Length; command = message.Content.Substring(1, lengthOfCommand - 1).ToLower(); if (command.Equals("hello")) { message.Channel.SendMessageAsync($@"Hello {message.Author.Mention}"); } return Task.CompletedTask; } } } ``` ## 結果 * 示意圖 ![](https://i.imgur.com/oIUnBxr.png) {%hackmd S1DMFioCO %}