forked from DSharpPlus/Example-Bots
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
228 lines (191 loc) · 8.51 KB
/
Copy pathProgram.cs
File metadata and controls
228 lines (191 loc) · 8.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
// THIS FILE IS A PART OF EMZI0767'S BOT EXAMPLES
//
// --------
//
// Copyright 2017 Emzi0767
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// --------
//
// This is a voice example. It shows how to properly utilize VoiceNext.
using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using DSharpPlus;
using DSharpPlus.CommandsNext;
using DSharpPlus.CommandsNext.Exceptions;
using DSharpPlus.Entities;
using DSharpPlus.EventArgs;
using DSharpPlus.VoiceNext;
using DSharpPlus.VoiceNext.Codec;
using Newtonsoft.Json;
namespace DSPlus.Examples
{
public class Program
{
public DiscordClient Client { get; set; }
public CommandsNextModule Commands { get; set; }
public VoiceNextClient Voice { get; set; }
public static void Main(string[] args)
{
// since we cannot make the entry method asynchronous,
// let's pass the execution to asynchronous code
var prog = new Program();
prog.RunBotAsync().GetAwaiter().GetResult();
}
public async Task RunBotAsync()
{
// first, let's load our configuration file
var json = "";
using (var fs = File.OpenRead("config.json"))
using (var sr = new StreamReader(fs, new UTF8Encoding(false)))
json = await sr.ReadToEndAsync();
// next, let's load the values from that file
// to our client's configuration
var cfgjson = JsonConvert.DeserializeObject<ConfigJson>(json);
var cfg = new DiscordConfiguration
{
Token = cfgjson.Token,
TokenType = TokenType.Bot,
AutoReconnect = true,
LogLevel = LogLevel.Debug,
UseInternalLogHandler = true
};
// then we want to instantiate our client
this.Client = new DiscordClient(cfg);
// If you are on Windows 7 and using .NETFX, install
// DSharpPlus.WebSocket.WebSocket4Net from NuGet,
// add appropriate usings, and uncomment the following
// line
//this.Client.SetWebSocketClient<WebSocket4NetClient>();
// If you are on Windows 7 and using .NET Core, install
// DSharpPlus.WebSocket.WebSocket4NetCore from NuGet,
// add appropriate usings, and uncomment the following
// line
//this.Client.SetWebSocketClient<WebSocket4NetCoreClient>();
// If you are using Mono, install
// DSharpPlus.WebSocket.WebSocketSharp from NuGet,
// add appropriate usings, and uncomment the following
// line
//this.Client.SetWebSocketClient<WebSocketSharpClient>();
// if using any alternate socket client implementations,
// remember to add the following to the top of this file:
//using DSharpPlus.Net.WebSocket;
// next, let's hook some events, so we know
// what's going on
this.Client.Ready += this.Client_Ready;
this.Client.GuildAvailable += this.Client_GuildAvailable;
this.Client.ClientErrored += this.Client_ClientError;
// up next, let's set up our commands
var ccfg = new CommandsNextConfiguration
{
// let's use the string prefix defined in config.json
StringPrefix = cfgjson.CommandPrefix,
// enable responding in direct messages
EnableDms = true,
// enable mentioning the bot as a command prefix
EnableMentionPrefix = true
};
// and hook them up
this.Commands = this.Client.UseCommandsNext(ccfg);
// let's hook some command events, so we know what's
// going on
this.Commands.CommandExecuted += this.Commands_CommandExecuted;
this.Commands.CommandErrored += this.Commands_CommandErrored;
// up next, let's register our commands
this.Commands.RegisterCommands<ExampleVoiceCommands>();
// let's set up voice
var vcfg = new VoiceNextConfiguration
{
VoiceApplication = VoiceApplication.Music
};
// and let's enable it
this.Voice = this.Client.UseVoiceNext(vcfg);
// finally, let's connect and log in
await this.Client.ConnectAsync();
// for this example you will need to read the
// VoiceNext setup guide, and include ffmpeg.
// and this is to prevent premature quitting
await Task.Delay(-1);
}
private Task Client_Ready(ReadyEventArgs e)
{
// let's log the fact that this event occured
e.Client.DebugLogger.LogMessage(LogLevel.Info, "ExampleBot", "Client is ready to process events.", DateTime.Now);
// since this method is not async, let's return
// a completed task, so that no additional work
// is done
return Task.CompletedTask;
}
private Task Client_GuildAvailable(GuildCreateEventArgs e)
{
// let's log the name of the guild that was just
// sent to our client
e.Client.DebugLogger.LogMessage(LogLevel.Info, "ExampleBot", $"Guild available: {e.Guild.Name}", DateTime.Now);
// since this method is not async, let's return
// a completed task, so that no additional work
// is done
return Task.CompletedTask;
}
private Task Client_ClientError(ClientErrorEventArgs e)
{
// let's log the details of the error that just
// occured in our client
e.Client.DebugLogger.LogMessage(LogLevel.Error, "ExampleBot", $"Exception occured: {e.Exception.GetType()}: {e.Exception.Message}", DateTime.Now);
// since this method is not async, let's return
// a completed task, so that no additional work
// is done
return Task.CompletedTask;
}
private Task Commands_CommandExecuted(CommandExecutionEventArgs e)
{
// let's log the name of the command and user
e.Context.Client.DebugLogger.LogMessage(LogLevel.Info, "ExampleBot", $"{e.Context.User.Username} successfully executed '{e.Command.QualifiedName}'", DateTime.Now);
// since this method is not async, let's return
// a completed task, so that no additional work
// is done
return Task.CompletedTask;
}
private async Task Commands_CommandErrored(CommandErrorEventArgs e)
{
// let's log the error details
e.Context.Client.DebugLogger.LogMessage(LogLevel.Error, "ExampleBot", $"{e.Context.User.Username} tried executing '{e.Command?.QualifiedName ?? "<unknown command>"}' but it errored: {e.Exception.GetType()}: {e.Exception.Message ?? "<no message>"}", DateTime.Now);
// let's check if the error is a result of lack
// of required permissions
if (e.Exception is ChecksFailedException ex)
{
// yes, the user lacks required permissions,
// let them know
var emoji = DiscordEmoji.FromName(e.Context.Client, ":no_entry:");
// let's wrap the response into an embed
var embed = new DiscordEmbedBuilder
{
Title = "Access denied",
Description = $"{emoji} You do not have the permissions required to execute this command.",
Color = new DiscordColor(0xFF0000) // red
};
await e.Context.RespondAsync("", embed: embed);
}
}
}
// this structure will hold data from config.json
public struct ConfigJson
{
[JsonProperty("token")]
public string Token { get; private set; }
[JsonProperty("prefix")]
public string CommandPrefix { get; private set; }
}
}