-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathVoiceModule.cs
More file actions
159 lines (124 loc) · 5.81 KB
/
Copy pathVoiceModule.cs
File metadata and controls
159 lines (124 loc) · 5.81 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
using System.Diagnostics;
using NetCord;
using NetCord.Gateway.Voice;
using NetCord.Logging;
using NetCord.Rest;
using NetCord.Services.ApplicationCommands;
namespace MyBot;
public class VoiceModule : ApplicationCommandModule<ApplicationCommandContext>
{
[SlashCommand("play", "Plays music", Contexts = [InteractionContextType.Guild])]
public async Task PlayAsync(string track)
{
// Check if the specified track is a well formed uri
if (!Uri.IsWellFormedUriString(track, UriKind.Absolute))
{
await RespondAsync(InteractionCallback.Message("Invalid track!"));
return;
}
var guild = Context.Guild!;
// Get the user voice state
if (!guild.VoiceStates.TryGetValue(Context.User.Id, out var voiceState))
{
await RespondAsync(InteractionCallback.Message("You are not connected to any voice channel!"));
return;
}
var client = Context.Client;
// You should check if the bot is already connected to the voice channel.
// If so, you should use an existing 'VoiceClient' instance instead of creating a new one.
// You also need to add a synchronization here. 'JoinVoiceChannelAsync' should not be used concurrently for the same guild
var voiceClient = await client.JoinVoiceChannelAsync(
guild.Id,
voiceState.ChannelId.GetValueOrDefault(),
new VoiceClientConfiguration
{
Logger = new ConsoleLogger(),
});
// Connect
await voiceClient.StartAsync();
// Enter speaking state, to be able to send voice
await voiceClient.EnterSpeakingStateAsync(new SpeakingProperties(SpeakingFlags.Microphone));
// Respond to the interaction
await RespondAsync(InteractionCallback.Message($"Playing {Path.GetFileName(track)}!"));
// Create a stream that sends voice to Discord
var voiceStream = voiceClient.CreateVoiceStream();
// We create this stream to automatically convert the PCM data returned by FFmpeg to Opus data.
// The Opus data is then written to 'voiceStream' that sends the data to Discord
OpusEncodeStream stream = new(voiceStream, PcmFormat.Short, VoiceChannels.Stereo, OpusApplication.Audio);
ProcessStartInfo startInfo = new("ffmpeg")
{
RedirectStandardOutput = true,
};
var arguments = startInfo.ArgumentList;
// Set reconnect attempts in case of a lost connection to 1
arguments.Add("-reconnect");
arguments.Add("1");
// Set reconnect attempts in case of a lost connection for streamed media to 1
arguments.Add("-reconnect_streamed");
arguments.Add("1");
// Set the maximum delay between reconnection attempts to 5 seconds
arguments.Add("-reconnect_delay_max");
arguments.Add("5");
// Specify the input
arguments.Add("-i");
arguments.Add(track);
// Set the logging level to quiet mode
arguments.Add("-loglevel");
arguments.Add("-8");
// Set the number of audio channels to 2 (stereo)
arguments.Add("-ac");
arguments.Add("2");
// Set the output format to 16-bit signed little-endian
arguments.Add("-f");
arguments.Add("s16le");
// Set the audio sampling rate to 48 kHz
arguments.Add("-ar");
arguments.Add("48000");
// Direct the output to stdout
arguments.Add("pipe:1");
// Start the FFmpeg process
var ffmpeg = Process.Start(startInfo)!;
// Copy the FFmpeg stdout to 'stream', which encodes the voice using Opus and passes it to 'voiceStream'
await ffmpeg.StandardOutput.BaseStream.CopyToAsync(stream);
// Flush 'stream' to make sure all the data has been sent and to indicate to Discord that we have finished sending
await stream.FlushAsync();
}
[SlashCommand("echo", "Creates echo", Contexts = [InteractionContextType.Guild])]
public async Task<string> EchoAsync()
{
var guild = Context.Guild!;
var userId = Context.User.Id;
// Get the user voice state
if (!guild.VoiceStates.TryGetValue(userId, out var voiceState))
return "You are not connected to any voice channel!";
var client = Context.Client;
// You should check if the bot is already connected to the voice channel.
// If so, you should use an existing 'VoiceClient' instance instead of creating a new one.
// You also need to add a synchronization here. 'JoinVoiceChannelAsync' should not be used concurrently for the same guild
var voiceClient = await client.JoinVoiceChannelAsync(
guild.Id,
voiceState.ChannelId.GetValueOrDefault(),
new VoiceClientConfiguration
{
ReceiveHandler = new BufferedVoiceReceiveHandler(), // Required to receive voice
Logger = new ConsoleLogger(),
});
// Connect
await voiceClient.StartAsync();
// Enter speaking state, to be able to send voice
await voiceClient.EnterSpeakingStateAsync(new SpeakingProperties(SpeakingFlags.Microphone));
voiceClient.VoiceReceive += args =>
{
// If the timestamp is null, the packet was lost.
// We skip it, which mirrors the packet loss to the echo recipients.
if (args.IsLost)
return default;
// Pass current user voice directly to SendAsync to create echo
if (voiceClient.Cache.SsrcUsers.TryGetValue(args.Ssrc, out var voiceUserId) && voiceUserId == userId)
voiceClient.SendVoice(args.SequenceNumber, args.Timestamp, args.Frame);
return default;
};
// Return the response
return "Echo!";
}
}