# C# Discord bot紀錄 ## Discord是什麼? * Discord是一款專為社群設計的免費網路即時通話軟體與數位發行平台,主要針對遊戲玩家、教育人士及商業人士,使用者之間可以在軟體的聊天頻道通過資訊、圖片、影片和音訊進行互動。這款軟體可以在Microsoft Windows、macOS、Android、iOS、Linux和網頁上執行。 -- [維基百科](https://zh.wikipedia.org/wiki/Discord) ## 先行作業 * 建立資料夾,並選擇專案  * 點擊......下一步  * 點選管理NuGet套件  * 先輸入json  * 點擊右邊的齒輪  * 接著輸入 ```shell= https://api.nuget.org/v3/index.json ``` * 找到 Discord-Net and download  ## Discord-bot Developer * 參考 :::success [使用bot.py建立起你的第一個機器人](https://ithelp.ithome.com.tw/articles/10262736) ::: * token  ## 撰寫機器人 * 先上碼 ```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確認可以動,結果如下  * 打開Discord確認是否上線  ```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; } } } ``` ## 結果 * 示意圖  {%hackmd S1DMFioCO %}
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up