/// <summary> /// Method for configuring <see cref="LavalinkExtension"/>, accessing each configuration individually. /// </summary> /// <param name="botBase"></param> /// <param name="hostname">Sets the hostname associated with the Lavalink.</param> /// <param name="port">Sets the port associated with the Lavalink.</param> /// <param name="password">Sets the password associated with the Lavalink.</param> /// <param name="secured">Sets the secured status associated with the Lavalink.</param> /// <param name="region">Sets the voice region ID for the Lavalink connection. This should be used if nodes should be filtered by region with <see cref="LavalinkExtension.GetIdealNodeConnection(DiscordVoiceRegion)"/>.</param> /// <param name="resumeKey">Sets the resume key for the Lavalink connection. This will allow existing voice sessions to continue for a certain time after the client is disconnected.</param> /// <param name="resumeTimeout">Sets the time in seconds when all voice sessions are closed after the client disconnects. Defaults to 1 minute.</param> /// <param name="webSocketCloseTimeout">Sets the time in miliseconds to wait for Lavalink's voice WebSocket to close after leaving a voice channel. This will be the delay before the guild connection is removed. Defaults to 3 minutes.</param> /// <param name="socketAutoReconnect">Sets whether the connection wrapper should attempt automatic reconnects should the connection drop.</param> public static void LavalinkSetup(this TarsBase botBase, string hostname, int port, string password, bool secured = false, DiscordVoiceRegion region = null, string resumeKey = null, TimeSpan?resumeTimeout = null, TimeSpan?webSocketCloseTimeout = null, bool socketAutoReconnect = true) { _botBase = botBase; var connectionEndpoint = new ConnectionEndpoint(hostname, port, secured); _lavalinkConfiguration = new LavalinkConfiguration { SocketEndpoint = connectionEndpoint, RestEndpoint = connectionEndpoint, Password = password, Region = region, ResumeKey = resumeKey, ResumeTimeout = (int)(resumeTimeout?.TotalSeconds ?? TimeSpan.FromMinutes(1).TotalSeconds), WebSocketCloseTimeout = (int)(webSocketCloseTimeout?.TotalMilliseconds ?? TimeSpan.FromSeconds(3).TotalMilliseconds), SocketAutoReconnect = _socketAutoReconnect = socketAutoReconnect }; _lavalink = botBase.Discord.UseLavalink(); botBase.Discord.Heartbeated += DiscordHeartbeated; RegisterExitEvent(); RegisterLavalinkAsService(botBase); HttpClientSetup(); }
private async void Notify(ConnectionEndpoint endpoint, NetworkEvent networkEvent) { lock (this) { pendingCount++; if (pendingCount == 1) { Trace("Queue started"); syncPendingSent = new SyncEvent(); } } await Task.Delay(Parameters.CallLatency); endpoint.Notify(networkEvent); lock (this) { pendingCount--; if (pendingCount == 0) { Trace("Queue empty"); syncPendingSent.SetComplete(); } } }
private async Task <LavalinkNodeConnection> ConnectLavaNodeAsync() { ConnectionEndpoint endpoint = new ConnectionEndpoint { Hostname = "server.local", Port = 2333 }; LavalinkConfiguration lavalinkConfig = new LavalinkConfiguration { Password = ReadConfig.Config.LavaLinkPass, RestEndpoint = endpoint, SocketEndpoint = endpoint, SocketAutoReconnect = false }; LavalinkExtension lavalink = Client.UseLavalink(); LavalinkNodeConnection res = null; try { res = await lavalink.ConnectAsync(lavalinkConfig); } catch (WebSocketException e) { SystemService.Instance.Logger.Log("Failed to start connection with Lavalink server:\n" + e.Message); } return(res); }
public NetworkEventMonitor(ConnectionEndpoint endpoint) { this.endpoint = endpoint; endpoint.EventFired += (networkEvent) => { received.Add(networkEvent); }; }
internal VoiceNextConnection(DiscordClient client, DiscordGuild guild, DiscordChannel channel, VoiceNextConfiguration config, VoiceServerUpdatePayload server, VoiceStateUpdatePayload state) { Discord = client; Guild = guild; Channel = channel; TransmittingSSRCs = new ConcurrentDictionary <uint, AudioSender>(); _userSpeaking = new AsyncEvent <UserSpeakingEventArgs>(Discord.EventErrorHandler, "VNEXT_USER_SPEAKING"); _userJoined = new AsyncEvent <VoiceUserJoinEventArgs>(Discord.EventErrorHandler, "VNEXT_USER_JOINED"); _userLeft = new AsyncEvent <VoiceUserLeaveEventArgs>(Discord.EventErrorHandler, "VNEXT_USER_LEFT"); _voiceReceived = new AsyncEvent <VoiceReceiveEventArgs>(Discord.EventErrorHandler, "VNEXT_VOICE_RECEIVED"); _voiceSocketError = new AsyncEvent <SocketErrorEventArgs>(Discord.EventErrorHandler, "VNEXT_WS_ERROR"); TokenSource = new CancellationTokenSource(); Configuration = config; Opus = new Opus(AudioFormat); //this.Sodium = new Sodium(); Rtp = new Rtp(); ServerData = server; StateData = state; var eps = ServerData.Endpoint; var epi = eps.LastIndexOf(':'); var eph = string.Empty; var epp = 80; if (epi != -1) { eph = eps.Substring(0, epi); epp = int.Parse(eps.Substring(epi + 1)); } else { eph = eps; } ConnectionEndpoint = new ConnectionEndpoint { Hostname = eph, Port = epp }; ReadyWait = new TaskCompletionSource <bool>(); IsInitialized = false; IsDisposed = false; PlayingWait = null; PacketQueue = new ConcurrentQueue <VoicePacket>(); KeepaliveTimestamps = new ConcurrentDictionary <ulong, long>(); UdpClient = Discord.Configuration.UdpClientFactory(); VoiceWs = Discord.Configuration.WebSocketClientFactory(Discord.Configuration.Proxy); VoiceWs.Disconnected += VoiceWS_SocketClosed; VoiceWs.MessageRecieved += VoiceWS_SocketMessage; VoiceWs.Connected += VoiceWS_SocketOpened; VoiceWs.Errored += VoiceWs_SocketErrored; }
static void Main(string[] args) { ServerCommandLineOptions options = CommandLineParser.ParseArgs <ServerCommandLineOptions>(args, new ServerCommandLineOptions()); CommunicationServerSettings settings = Configuration.FromFile <CommunicationServerSettings>(options.Conf); IConnectionEndpoint endpoint = new ConnectionEndpoint(options.Port); CommunicationServer server = new CommunicationServer(endpoint, settings); server.Start(); }
internal VoiceNextConnection(DiscordClient client, DiscordGuild guild, DiscordChannel channel, VoiceNextConfiguration config, VoiceServerUpdatePayload server, VoiceStateUpdatePayload state) { Discord = client; Guild = guild; Channel = channel; SSRCMap = new ConcurrentDictionary <uint, ulong>(); _userSpeaking = new AsyncEvent <UserSpeakingEventArgs>(Discord.EventErrorHandler, "USER_SPEAKING"); _userLeft = new AsyncEvent <VoiceUserLeaveEventArgs>(Discord.EventErrorHandler, "USER_LEFT"); #if !NETSTANDARD1_1 _voiceReceived = new AsyncEvent <VoiceReceiveEventArgs>(Discord.EventErrorHandler, "VOICE_RECEIVED"); #endif _voiceSocketError = new AsyncEvent <SocketErrorEventArgs>(Discord.EventErrorHandler, "VOICE_WS_ERROR"); TokenSource = new CancellationTokenSource(); Configuration = config; Opus = new OpusCodec(48000, 2, Configuration.VoiceApplication); Sodium = new SodiumCodec(); Rtp = new RtpCodec(); ServerData = server; StateData = state; var eps = ServerData.Endpoint; var epi = eps.LastIndexOf(':'); var eph = string.Empty; var epp = 80; if (epi != -1) { eph = eps.Substring(0, epi); epp = int.Parse(eps.Substring(epi + 1)); } else { eph = eps; } ConnectionEndpoint = new ConnectionEndpoint { Hostname = eph, Port = epp }; ReadyWait = new TaskCompletionSource <bool>(); IsInitialized = false; IsDisposed = false; PlayingWait = null; PlaybackSemaphore = new SemaphoreSlim(1, 1); UdpClient = Discord.Configuration.UdpClientFactory(); VoiceWs = Discord.Configuration.WebSocketClientFactory(Discord.Configuration.Proxy); VoiceWs.OnDisconnect += VoiceWS_SocketClosed; VoiceWs.OnMessage += VoiceWS_SocketMessage; VoiceWs.OnConnect += VoiceWS_SocketOpened; VoiceWs.OnError += VoiceWs_SocketErrored; }
public MusicModule() { this.endpoint = new ConnectionEndpoint("127.0.0.1", 2333); this.configuration = new LavalinkConfiguration { Password = "******", RestEndpoint = this.endpoint, SocketEndpoint = this.endpoint, ResumeKey = "tutorial-bot" }; }
internal ConnectionEndpoint Register(string instanceID) { Debug.Assert(!connections.ContainsKey(instanceID)); var endpoint = new ConnectionEndpoint { ID = instanceID, }; connections.Add(instanceID, endpoint); return(endpoint); }
// Token: 0x0600007E RID: 126 RVA: 0x000027F4 File Offset: 0x000009F4 internal VoiceNextConnection(DiscordClient client, DiscordGuild guild, DiscordChannel channel, VoiceNextConfiguration config, VoiceServerUpdatePayload server, VoiceStateUpdatePayload state) { this.Discord = client; this.Guild = guild; this.Channel = channel; this.TransmittingSSRCs = new ConcurrentDictionary <uint, AudioSender>(); this._userSpeaking = new AsyncEvent <UserSpeakingEventArgs>(new Action <string, Exception>(this.Discord.EventErrorHandler), "VNEXT_USER_SPEAKING"); this._userJoined = new AsyncEvent <VoiceUserJoinEventArgs>(new Action <string, Exception>(this.Discord.EventErrorHandler), "VNEXT_USER_JOINED"); this._userLeft = new AsyncEvent <VoiceUserLeaveEventArgs>(new Action <string, Exception>(this.Discord.EventErrorHandler), "VNEXT_USER_LEFT"); this._voiceReceived = new AsyncEvent <VoiceReceiveEventArgs>(new Action <string, Exception>(this.Discord.EventErrorHandler), "VNEXT_VOICE_RECEIVED"); this._voiceSocketError = new AsyncEvent <SocketErrorEventArgs>(new Action <string, Exception>(this.Discord.EventErrorHandler), "VNEXT_WS_ERROR"); this.TokenSource = new CancellationTokenSource(); this.Configuration = config; this.Opus = new Opus(this.AudioFormat); this.Rtp = new Rtp(); this.ServerData = server; this.StateData = state; string endpoint = this.ServerData.Endpoint; int num = endpoint.LastIndexOf(':'); string hostname = string.Empty; int port = 80; if (num != -1) { hostname = endpoint.Substring(0, num); port = int.Parse(endpoint.Substring(num + 1)); } else { hostname = endpoint; } ConnectionEndpoint webSocketEndpoint = default(ConnectionEndpoint); webSocketEndpoint.Hostname = hostname; webSocketEndpoint.Port = port; this.WebSocketEndpoint = webSocketEndpoint; this.ReadyWait = new TaskCompletionSource <bool>(); this.IsInitialized = false; this.IsDisposed = false; this.PlayingWait = null; this.PacketQueue = new ConcurrentQueue <VoicePacket>(); this.KeepaliveTimestamps = new ConcurrentDictionary <ulong, long>(); this.PauseEvent = new AsyncManualResetEvent(true); this.UdpClient = this.Discord.Configuration.UdpClientFactory.Invoke(); this.VoiceWs = this.Discord.Configuration.WebSocketClientFactory.Invoke(this.Discord.Configuration.Proxy); this.VoiceWs.Disconnected += new AsyncEventHandler <SocketCloseEventArgs>(this.VoiceWS_SocketClosed); this.VoiceWs.MessageReceived += new AsyncEventHandler <SocketMessageEventArgs>(this.VoiceWS_SocketMessage); this.VoiceWs.Connected += new AsyncEventHandler(this.VoiceWS_SocketOpened); this.VoiceWs.ExceptionThrown += new AsyncEventHandler <SocketErrorEventArgs>(this.VoiceWs_SocketException); }
static async Task MainAsync() { Discord = new DiscordClient(new DiscordConfiguration() { Token = Environment.GetEnvironmentVariable("TOKEN"), TokenType = TokenType.Bot, MinimumLogLevel = LogLevel.Debug, AutoReconnect = true, }); var commands = Discord.UseCommandsNext(new CommandsNextConfiguration() { StringPrefixes = new[] { ">" } }); commands.RegisterCommands <MyFirstModule>(); commands.RegisterCommands <MusicModule>(); commands.RegisterCommands <BobaModule>(); commands.RegisterCommands <EggModule>(); commands.RegisterCommands <DameModule>(); var endpoint = new ConnectionEndpoint { Hostname = "newmydiscordbot-lavalink.herokuapp.com", // From your server configuration. //Port = Convert.ToInt32(Environment.GetEnvironmentVariable("PORT") ?? "80") // From your server configuration //Hostname = "127.0.0.1", Port = 80 }; Console.WriteLine(endpoint.Port); var lavalinkConfig = new LavalinkConfiguration { Password = "******", // From your server configuration. //Password= "******", RestEndpoint = endpoint, SocketEndpoint = endpoint, ResumeTimeout = 50 }; var lavalink = Discord.UseLavalink(); await Discord.ConnectAsync(new DSharpPlus.Entities.DiscordActivity("Anime", DSharpPlus.Entities.ActivityType.Watching)); await lavalink.ConnectAsync(lavalinkConfig); await Task.Delay(-1); }
private LavalinkConfiguration CreateLavalinkConfig() { var endpoint = new ConnectionEndpoint { Hostname = jsonSettings.LavaHost, Port = jsonSettings.LavaPort }; var lavalinkConfig = new LavalinkConfiguration { Password = jsonSettings.LavaPassword, RestEndpoint = endpoint, SocketEndpoint = endpoint }; return(lavalinkConfig); }
public MusicService(LaveyBot bot) { this._bot = bot; this._log = LogManager.GetLogger("MusicService"); this._players = new ConcurrentDictionary <ulong, MusicPlayer>(); this._endpoint = new ConnectionEndpoint(this._bot.Config.Lavalink.Endpoint.Hostname, this._bot.Config.Lavalink.Endpoint.Port); this._config = new LavalinkConfiguration { Password = bot.Config.Lavalink.Password, RestEndpoint = this._endpoint, SocketEndpoint = this._endpoint }; this._bot.Discord.Ready += this.OnReady; this._bot.Discord.Heartbeated += this.OnHeartbeat; }
public LavalinkConfiguration GetLavalinkConfiguration() { ConnectionEndpoint endpoint = new ConnectionEndpoint { Hostname = global.botConfig.lavalinkServerIp, Port = global.botConfig.lavalinkServerPort }; LavalinkConfiguration config = new LavalinkConfiguration { Password = global.botConfig.lavalinkPassword, RestEndpoint = endpoint, SocketEndpoint = endpoint, }; return(config); }
public async Task <ConnectionState> Connect(InstanceInfo registration) { await CallService(); endpoint = simulation.RegisterConnection(InstanceID); endpoint.EventFired += FireEventReceived; // TODO remove MonitoredAccounts from registration //await Monitor(registration.MonitoredAccounts); switch (ServiceState) { case ServiceState.Operational: return(ConnectionState.Online); case ServiceState.Limited: return(ConnectionState.Connected); case ServiceState.Down: default: throw new ApplicationException(); } }
protected override async Task <Socket> CreateSocket(ConnectionEndpoint endpoint, CancellationToken cancellation) { Socket s = null; int maxTries = 3; int retry = 0; try { while (true) { s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); await s.ConnectAsync(_SocksEndpoint, cancellation).ConfigureAwait(false); NetworkStream stream = new NetworkStream(s, false); await stream.WriteAsync(SelectionMessage, 0, SelectionMessage.Length, cancellation).ConfigureAwait(false); await stream.FlushAsync(cancellation).ConfigureAwait(false); var selectionResponse = await stream.ReadBytes(2, cancellation); if (selectionResponse[0] != 5) { throw new SocksException("Invalid version in selection reply"); } if (selectionResponse[1] != 0) { throw new SocksException("Unsupported authentication method in selection reply"); } var connectBytes = CreateConnectMessage(endpoint.Host, endpoint.Port); await stream.WriteAsync(connectBytes, 0, connectBytes.Length, cancellation).ConfigureAwait(false); await stream.FlushAsync(cancellation).ConfigureAwait(false); var connectResponse = await stream.ReadBytes(10, cancellation); if (connectResponse[0] != 5) { throw new SocksException("Invalid version in connect reply"); } if (connectResponse[1] != 0) { var code = (SocksErrorCode)connectResponse[1]; Logs.TOR.LogDebug($"TOR failed to connect to hidden service with error {Enum.GetName(code.GetType(), code)} (Code {(int)code})"); if (!IsTransient(code) || retry++ >= maxTries) { throw new SocksException(code); } SafeDispose(ref s); await Task.Delay(1000, cancellation).ConfigureAwait(false); continue; } if (connectResponse[2] != 0) { throw new SocksException("Invalid RSV in connect reply"); } if (connectResponse[3] != 1) { throw new SocksException("Invalid ATYP in connect reply"); } for (int i = 4; i < 4 + 4; i++) { if (connectResponse[i] != 0) { throw new SocksException("Invalid BIND address in connect reply"); } } if (connectResponse[8] != 0 || connectResponse[9] != 0) { throw new SocksException("Invalid PORT address connect reply"); } Logs.TOR.LogDebug("TOR is connected to hidden service"); return(s); } } catch (TaskCanceledException ex) { SafeDispose(ref s); throw new TaskCanceledException("TOR failed to connect to the remote server", ex); } catch { SafeDispose(ref s); throw; } }
/// <summary> /// Gets the lavalink node connection for specified endpoint. /// </summary> /// <param name="endpoint">Endpoint at which the node resides.</param> /// <returns>Lavalink node connection.</returns> public LavalinkNodeConnection GetNodeConnection(ConnectionEndpoint endpoint) => this.ConnectedNodes.ContainsKey(endpoint) ? this.ConnectedNodes[endpoint] : null;
private static async Task MainAsync() { _client = new DiscordClient(new DiscordConfiguration { Token = Configuration.Discord.UseProduction ? Configuration.Discord.Production : Configuration.Discord.Development, TokenType = TokenType.Bot, #if DEBUG MinimumLogLevel = LogLevel.Debug, #else MinimumLogLevel = LogLevel.Information, #endif Intents = DiscordIntents.All }); _client.GuildMemberAdded += OnGuildMemberAdded; _client.GuildMemberRemoved += OnGuildMemberRemoved; _client.GuildCreated += OnGuildCreated; _client.GuildDeleted += OnGuildDeleted; _client.GuildBanAdded += OnGuildBanAdded; _client.GuildBanRemoved += OnGuildBanRemoved; _client.MessageCreated += OnMessageCreated; _client.UseInteractivity(new InteractivityConfiguration { PollBehaviour = PollBehaviour.DeleteEmojis, Timeout = TimeSpan.FromSeconds(30) }); var commands = _client.UseCommandsNext(new CommandsNextConfiguration { StringPrefixes = new[] {"wyrobot!"}, IgnoreExtraArguments = true, EnableMentionPrefix = false, PrefixResolver = ResolvePrefixAsync }); commands.RegisterEvents(); commands.RegisterConverter(new BoolConverter()); commands.SetHelpFormatter<CustomHelpFormatter>(); commands.RegisterCommands<SettingsCommands>(); commands.RegisterCommands<LevelingCommands>(); commands.RegisterCommands<LevelingSettingsCommands>(); commands.RegisterCommands<LevelRewardsSettingsCommands>(); commands.RegisterCommands<ModerationCommands>(); commands.RegisterCommands<ModerationSettingsCommands>(); commands.RegisterCommands<WelcomeSettingsCommands>(); commands.RegisterCommands<MusicCommands>(); var endpoint = new ConnectionEndpoint { Hostname = Configuration.Lavalink.Host, Port = Configuration.Lavalink.Port }; var lavalinkConfig = new LavalinkConfiguration { Password = Configuration.Lavalink.Password, RestEndpoint = endpoint, SocketEndpoint = endpoint }; var lavalink = _client.UseLavalink(); SanctionHandler.InitializeAndStart(_client); await _client.ConnectAsync(new DiscordActivity { Name = "with code", ActivityType = ActivityType.Playing }); await lavalink.ConnectAsync(lavalinkConfig); await Task.Delay(-1); }
private async Task HandleDispatch(JObject jo) { var opc = (int)jo["op"]; var opp = jo["d"] as JObject; switch (opc) { case 2: // READY Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", "OP2 received", DateTime.Now); var vrp = opp.ToObject <VoiceReadyPayload>(); SSRC = vrp.SSRC; ConnectionEndpoint = new ConnectionEndpoint(ConnectionEndpoint.Hostname, vrp.Port); // this is not the valid interval // oh, discord //this.HeartbeatInterval = vrp.HeartbeatInterval; HeartbeatTask = Task.Run(HeartbeatAsync); await Stage1(vrp).ConfigureAwait(false); break; case 4: // SESSION_DESCRIPTION Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", "OP4 received", DateTime.Now); var vsd = opp.ToObject <VoiceSessionDescriptionPayload>(); Key = vsd.SecretKey; Sodium = new DSharpPlus.VoiceNext.Codec.Sodium(Key.AsMemory()); await Stage2(vsd).ConfigureAwait(false); break; case 5: // SPEAKING // Don't spam OP5 //this.Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", "OP5 received", DateTime.Now); var spd = opp.ToObject <VoiceSpeakingPayload>(); var spk = new UserSpeakingEventArgs(Discord) { Speaking = spd.Speaking, SSRC = spd.SSRC.Value, }; if (spk.UserId != 0 && TransmittingSSRCs.TryGetValue(spk.SSRC, out var txssrc5) && txssrc5.UserId == 0) { txssrc5.UserId = spk.UserId; } else { var opus = Opus.CreateDecoder(); var vtx = new AudioSender(spk.SSRC, opus) { UserId = spd.UserId.Value }; if (!TransmittingSSRCs.TryAdd(spk.SSRC, vtx)) { Opus.DestroyDecoder(opus); } } await _userSpeaking.InvokeAsync(spk).ConfigureAwait(false); break; case 6: // HEARTBEAT ACK var dt = DateTime.Now; var ping = (int)(dt - LastHeartbeat).TotalMilliseconds; Volatile.Write(ref _wsPing, ping); Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", $"Received voice heartbeat ACK, ping {ping.ToString("#,##0", CultureInfo.InvariantCulture)}ms", dt); LastHeartbeat = dt; break; case 8: // HELLO // this sends a heartbeat interval that we need to use for heartbeating HeartbeatInterval = opp["heartbeat_interval"].ToObject <int>(); break; case 9: // RESUMED Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", "OP9 received", DateTime.Now); HeartbeatTask = Task.Run(HeartbeatAsync); break; case 12: // CLIENT_CONNECTED var ujpd = opp.ToObject <VoiceUserJoinPayload>(); { var opus = Opus.CreateDecoder(); var vtx = new AudioSender(ujpd.SSRC, opus) { UserId = ujpd.UserId }; if (!TransmittingSSRCs.TryAdd(vtx.SSRC, vtx)) { Opus.DestroyDecoder(opus); } } await _userJoined.InvokeAsync(new VoiceUserJoinEventArgs(Discord) { UserId = ujpd.UserId, SSRC = ujpd.SSRC }).ConfigureAwait(false); break; case 13: // CLIENT_DISCONNECTED var ulpd = opp.ToObject <VoiceUserLeavePayload>(); var txssrc = TransmittingSSRCs.FirstOrDefault(x => x.Value.Id == ulpd.UserId); if (TransmittingSSRCs.ContainsKey(txssrc.Key)) { TransmittingSSRCs.TryRemove(txssrc.Key, out var txssrc13); Opus.DestroyDecoder(txssrc13.Decoder); } await _userLeft.InvokeAsync(new VoiceUserLeaveEventArgs(Discord) { UserId = ulpd.UserId, SSRC = txssrc.Key }).ConfigureAwait(false); break; default: Discord.DebugLogger.LogMessage(LogLevel.Warning, "VoiceNext", $"Unknown opcode received: {opc.ToString(CultureInfo.InvariantCulture)}", DateTime.Now); break; } }
public static async Task Main(string[] args) { Console.WriteLine(new Figlet().ToAscii("kuvuBot"), Color.Cyan); LoadConfig(); await LangController.LoadTranslations(); var conf = new DiscordConfiguration { Token = Config.Token, TokenType = TokenType.Bot, AutoReconnect = true, #if DEBUG LogLevel = LogLevel.Debug, #else LogLevel = LogLevel.Info, #endif UseInternalLogHandler = true, HttpTimeout = TimeSpan.FromSeconds(60) }; Client = new DiscordShardedClient(conf); Lavalink = await Client.UseLavalinkAsync(); var services = new ServiceCollection() .AddSingleton(Config) .AddSingleton(Client); services.AddSingleton(services); Commands = await Client.UseCommandsNextAsync(new CommandsNextConfiguration { EnableDefaultHelp = true, PrefixResolver = async msg => { var kuvuGuild = await msg.Channel.Guild.GetKuvuGuild(); return(msg.GetStringPrefixLength(kuvuGuild.Prefix, StringComparison.CurrentCultureIgnoreCase)); }, Services = services.BuildServiceProvider() }); foreach (var extension in Commands.Values) { extension.SetHelpFormatter <HelpFormatter>(); extension.RegisterFriendlyConverters(); extension.CommandExecuted += Commands_CommandExecuted; extension.CommandErrored += Commands_CommandErrored; extension.RegisterCommands(Assembly.GetExecutingAssembly()); } Client.ClientErrored += e => { Console.WriteLine(e.Exception); return(Task.CompletedTask); }; Client.Ready += Client_Ready; Client.GuildCreated += Client_GuildEvents; Client.GuildDeleted += Client_GuildEvents; Client.GuildDownloadCompleted += e => { Client.DebugLogger.LogMessage(LogLevel.Info, "kuvuBot", $"Guild download completed {e.Guilds.Count}", DateTime.Now); Loaded = true; return(Client_GuildEvents(e)); }; Client.MessageReactionAdded += MinesweeperCommand.Client_MessageReactionAdded; Client.SocketErrored += Client_SocketErrored; services.RegisterFeatures(); UpdateDatabase(); await Client.StartAsync(); Client.Ready += e => e.Client.UpdateStatusAsync(GetDiscordActivity(), Config.Status.UserStatus); try { var endpoint = new ConnectionEndpoint { Hostname = Config.Lavalink.Ip, Port = Config.Lavalink.Port }; foreach (var extension in Lavalink.Values) { MusicCommand.Lavalink = await extension.ConnectAsync(new LavalinkConfiguration { Password = Config.Lavalink.Password, RestEndpoint = endpoint, SocketEndpoint = endpoint }); } } catch (Exception ex) { if (ex is SocketException || ex is HttpRequestException || ex is WebSocketException) { Console.WriteLine("Can't connect to lavalink! (music commands are disabled)", Color.Red); } else { throw; } } await Task.Delay(-1); }
public override void Setup(ConnectionEndpoint endpoint) { _endpoint = new NativeEndpoint(endpoint.Hostname, endpoint.Port); }
public async Task RodandoBot(string[] args) { var discord = new DiscordClient(new DiscordConfiguration { Token = Parameters.token, TokenType = TokenType.Bot, MinimumLogLevel = LogLevel.Debug }); discord.UseInteractivity(new InteractivityConfiguration() { Timeout = System.TimeSpan.FromSeconds(30), PollBehaviour = PollBehaviour.KeepEmojis, PaginationBehaviour = PaginationBehaviour.Ignore, PaginationDeletion = PaginationDeletion.KeepEmojis }); this.Database = new DataContext(); this.StartsRepository = new StartsRepository(this.Database); this.ItemRepository = new ItemRepository(this.Database); this.CharactersRepository = new CharactersRepository(this.Database); this.AtributesRepository = new AtributesRepository(this.Database); this.MonsterRepository = new MonsterRepository(this.Database); this.BattleService = new BattleService(this.Database); var services = new ServiceCollection() .AddSingleton(this.Database) .AddSingleton(this.StartsRepository) .AddSingleton(this.ItemRepository) .AddSingleton(this.CharactersRepository) .AddSingleton(this.AtributesRepository) .AddSingleton(this.MonsterRepository) .AddSingleton(this.BattleService) .BuildServiceProvider(); var commands = discord.UseCommandsNext(new CommandsNextConfiguration { Services = services, StringPrefixes = Parameters.Prefix }); commands.RegisterCommands <LavaLinkCommands>(); commands.RegisterCommands <StartCommands>(); commands.RegisterCommands <AssignAtributtesCharacter>(); commands.RegisterCommands <StatusCommands>(); commands.RegisterCommands <ItemCommands>(); commands.RegisterCommands <MonsterCommands>(); commands.RegisterCommands <BattleCommands>(); commands.RegisterCommands <B3Commands>(); //B3Api.B3Api.B3(args); var endPoint = new ConnectionEndpoint { Hostname = "127.0.0.1", Port = 2333 }; var lavaLinkConfig = new LavalinkConfiguration { Password = "******", RestEndpoint = endPoint, SocketEndpoint = endPoint }; var lavalink = discord.UseLavalink(); await discord.ConnectAsync(); await lavalink.ConnectAsync(lavaLinkConfig); //espera infinita, para o bot ficar online continuamente. await Task.Delay(-1); }
private async Task HandleDispatch(JObject jo) { var opc = (int)jo["op"]; var opp = jo["d"] as JObject; switch (opc) { case 2: Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", "OP2 received", DateTime.Now); var vrp = opp.ToObject <VoiceReadyPayload>(); SSRC = vrp.SSRC; ConnectionEndpoint = new ConnectionEndpoint { Hostname = ConnectionEndpoint.Hostname, Port = vrp.Port }; HeartbeatInterval = vrp.HeartbeatInterval; HeartbeatTask = Task.Run(Heartbeat); await Stage1().ConfigureAwait(false); break; case 4: Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", "OP4 received", DateTime.Now); var vsd = opp.ToObject <VoiceSessionDescriptionPayload>(); Key = vsd.SecretKey; await Stage2().ConfigureAwait(false); break; case 5: // Don't spam OP5 //this.Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", "OP5 received", DateTime.Now); var spd = opp.ToObject <VoiceSpeakingPayload>(); var spk = new UserSpeakingEventArgs(Discord) { Speaking = spd.Speaking, SSRC = spd.SSRC.Value, User = Discord.InternalGetCachedUser(spd.UserId.Value) }; if (!SSRCMap.ContainsKey(spk.SSRC)) { SSRCMap.AddOrUpdate(spk.SSRC, spk.User.Id, (k, v) => spk.User.Id); } await _userSpeaking.InvokeAsync(spk).ConfigureAwait(false); break; case 6: var dt = DateTime.Now; var ping = (int)(dt - LastHeartbeat).TotalMilliseconds; Volatile.Write(ref _ping, ping); Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", $"Received voice heartbeat ACK, ping {ping.ToString("#,##0", CultureInfo.InvariantCulture)}ms", dt); LastHeartbeat = dt; break; case 8: // this sends a heartbeat interval that appears to be consistent with regular GW hello // however opcodes don't match (8 != 10) // so we suppress it so that users are not alerted // HELLO break; case 9: Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", "OP9 received", DateTime.Now); HeartbeatTask = Task.Run(Heartbeat); break; case 13: var ulpd = opp.ToObject <VoiceUserLeavePayload>(); var usr = await Discord.GetUserAsync(ulpd.UserId).ConfigureAwait(false); var ssrc = SSRCMap.FirstOrDefault(x => x.Value == ulpd.UserId); if (ssrc.Value != 0) { SSRCMap.TryRemove(ssrc.Key, out _); } Discord.DebugLogger.LogMessage(LogLevel.Debug, "VoiceNext", $"User '{usr.Username}#{usr.Discriminator}' ({ulpd.UserId.ToString(CultureInfo.InvariantCulture)}) left voice chat in '{Channel.Guild.Name}' ({Channel.Guild.Id.ToString(CultureInfo.InvariantCulture)})", DateTime.Now); await _userLeft.InvokeAsync(new VoiceUserLeaveEventArgs(Discord) { User = usr }).ConfigureAwait(false); break; default: Discord.DebugLogger.LogMessage(LogLevel.Warning, "VoiceNext", $"Unknown opcode received: {opc.ToString(CultureInfo.InvariantCulture)}", DateTime.Now); break; } }
public async Task RunBotAsync() { // read config string json; await using (FileStream fs = File.OpenRead(Path.Combine(Directory.GetCurrentDirectory(), "config.json"))) using (StreamReader sr = new StreamReader(fs, new UTF8Encoding(false))) json = await sr.ReadToEndAsync(); Configuration = JsonConvert.DeserializeObject <ConfigJson>(json); // setup client DiscordConfiguration cfg = new DiscordConfiguration { Token = Configuration.Token, TokenType = TokenType.Bot, Intents = DiscordIntents.GuildMessages | DiscordIntents.Guilds | DiscordIntents.GuildMembers | DiscordIntents.GuildBans | DiscordIntents.GuildVoiceStates, AutoReconnect = true, MinimumLogLevel = LogLevel.Debug, LogTimestampFormat = "dd MMM yyy - hh:mm:ss" }; Client = new DiscordShardedClient(cfg); Client.Ready += new Ready(Client).Client_Ready; Client.GuildAvailable += new GuildAvailable(Client).Client_GuildAvailable; Client.ClientErrored += new ClientErrored(Client).Client_ClientErrored; // load custom commands List <Type> typesToRegister = new List <Type>(); if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "CustomCommands"))) { Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "CustomCommands"); } else { string[] assemblyList = Directory.GetFiles( Path.Combine(Directory.GetCurrentDirectory(), "CustomCommands"), "*.dll", SearchOption.AllDirectories); foreach (string assemblyPath in assemblyList) { Assembly assembly = Assembly.LoadFile(assemblyPath); Type type = assembly.GetType("SecretariaEletronica.CustomCommands.Main"); typesToRegister.Add(type); } } // setup commandsnext CommandsNextConfiguration commandCfg = new CommandsNextConfiguration { StringPrefixes = Configuration.CommandPrefix, EnableDms = true, EnableMentionPrefix = true }; Commands = await Client.UseCommandsNextAsync(commandCfg); foreach (CommandsNextExtension cmdNext in Commands.Values) { cmdNext.CommandExecuted += new CommandExecuted().Commands_CommandExecuted; cmdNext.CommandErrored += new CommandErrored().Commands_CommandErrored; cmdNext.RegisterCommands <CustomCommands>(); cmdNext.RegisterCommands <DrawningCommands>(); cmdNext.RegisterCommands <LavaLinkCommands>(); cmdNext.RegisterCommands <MiscCommands>(); cmdNext.RegisterCommands <ModeratorCommands>(); cmdNext.RegisterCommands <VoiceCommands>(); cmdNext.RegisterCommands <WaxCommands>(); foreach (Type type in typesToRegister) { cmdNext.RegisterCommands(type); } } // setup lavalink ConnectionEndpoint endpoint = new ConnectionEndpoint { Hostname = Configuration.LavaLinkIp, Port = Configuration.LavaLinkPort }; LavalinkConfiguration lavalinkConfig = new LavalinkConfiguration { Password = Configuration.LavaLinkPass, RestEndpoint = endpoint, SocketEndpoint = endpoint }; Voice = await Client.UseVoiceNextAsync(new VoiceNextConfiguration()); LavaLink = await Client.UseLavalinkAsync(); await Client.StartAsync(); foreach (LavalinkExtension lava in LavaLink.Values) { await lava.ConnectAsync(lavalinkConfig); } // setup mongodb _mongoClient = new MongoClient(Configuration.MongoUrl); Database = _mongoClient.GetDatabase("SecretariaEletronica"); await Task.Delay(-1); }
/// <summary> /// Creates a new Lavalink REST client. /// </summary> /// <param name="restEndpoint">The REST server endpoint to connect to.</param> /// <param name="password">The password for the remote server.</param> public LavalinkRestClient(ConnectionEndpoint restEndpoint, string password) { this.RestEndpoint = restEndpoint; this.ConfigureHttpHandling(password); }
public async Task RunAsync() { var json = string.Empty; using (var fs = File.OpenRead(Path.GetFullPath(@"C:\Users\niedz\Desktop\C#\CustomBot\CustomBot\bin\Debug\net5.0\config.json"))) using (var sr = new StreamReader(fs, new UTF8Encoding(false))) json = await sr.ReadToEndAsync(); var configJson = JsonConvert.DeserializeObject <ConfigJson>(json); var config = new DiscordConfiguration { Token = configJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = LogLevel.Debug }; var endpoint = new ConnectionEndpoint { Hostname = "127.0.0.1", Port = 2333 }; var lavalinkConfig = new LavalinkConfiguration { Password = "******", RestEndpoint = endpoint, SocketEndpoint = endpoint }; Client = new DiscordClient(config); Client.Ready += OnClientReady; Client.UseInteractivity(new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(2) }); var commandsConfig = new CommandsNextConfiguration { StringPrefixes = new string[] { configJson.Prefix }, EnableDms = false, EnableMentionPrefix = true, DmHelp = false, Services = _serviceProvider }; var lavalink = Client.UseLavalink(); Commands = Client.UseCommandsNext(commandsConfig); Commands.RegisterCommands <PlaylistCommands>(); Commands.RegisterCommands <FounderCommands>(); Commands.RegisterCommands <JavalinkCommands>(); Voice = Client.UseVoiceNext(); await Client.ConnectAsync(); await lavalink.ConnectAsync(lavalinkConfig); await Task.Delay(-1); }
private static async Task MainAsync() { var json = string.Empty; using (var fs = File.OpenRead("../../../config.json")) //a hacky way to arrive at the config directory using (var sr = new StreamReader(fs, new UTF8Encoding(false))) json = await sr.ReadToEndAsync().ConfigureAwait(false); var configJson = JsonConvert.DeserializeObject <ConfigJson>(json); //json config reading complete discord = new DiscordClient(new DiscordConfiguration() { Token = configJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = LogLevel.Debug, Intents = DiscordIntents.GuildEmojis | DiscordIntents.GuildVoiceStates | DiscordIntents.GuildMessageReactions | DiscordIntents.GuildMessages | DiscordIntents.Guilds }); DiscordChannel channel = null; var commands = discord.UseCommandsNext(new CommandsNextConfiguration() { StringPrefixes = new[] { configJson.Prefix } }); commands.RegisterCommands <FirstModule>(); var endpoint = new ConnectionEndpoint { Hostname = "127.0.0.1", Port = 5688 }; var lavalinkConfig = new LavalinkConfiguration { Password = "******", RestEndpoint = endpoint, SocketEndpoint = endpoint }; var lavalink = discord.UseLavalink(); //below are the event listeners discord.VoiceStateUpdated += async(s, e) => //when someone joins leaves or moves voice channel { DiscordGuild guild = e.Guild; DiscordChannel currentChannel = e.Channel; string user = e.User.Username; if (user.Equals("User")) { await discord.SendMessageAsync(await discord.GetChannelAsync(803584072572076055), $"{user }alert ", true); } }; discord.MessageCreated += async(s, e) => { String user = e.Author.Username; //await e.Message.ModifyAsync("ahhhh another one."); if (e.Message.Content.ToLower().Contains("fiddlesticks")) { await e.Message.DeleteAsync(); await e.Message.RespondAsync($"Wuh-oh {user}, we don't use that kinda language 'round these parts."); } if (e.Author.Username.Equals("User") && e.Message.Content.ToLowerInvariant().Contains("lol")) { await e.Message.RespondAsync($"It probably wasn't that funny {user}, chill out"); } }; await discord.ConnectAsync(); await lavalink.ConnectAsync(lavalinkConfig); await Task.Delay(-1); }
static async Task Main() { var builder = new HostBuilder(); builder.ConfigureHostConfiguration(configHost => { configHost.SetBasePath(Directory.GetCurrentDirectory()); configHost.AddInMemoryCollection(new[] { new KeyValuePair <string, string>(HostDefaults.EnvironmentKey, Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT")), }) .AddEnvironmentVariables(); }).ConfigureAppConfiguration((hostContext, configApp) => { configApp.SetBasePath(Directory.GetCurrentDirectory()); configApp.AddJsonFile("appsettings.json", false, true); configApp.AddJsonFile( $"appsettings.{hostContext.HostingEnvironment.EnvironmentName}.json", optional: true); configApp.AddJsonFile("/app/secrets/appsettings.secrets.json", optional: true); configApp.AddJsonFile("appsettings.local.json", optional: true, reloadOnChange: false); //load local settings configApp.AddEnvironmentVariables(); }).ConfigureLogging((hostContext, configLogging) => { var formatElastic = hostContext.Configuration.GetValue("FormatLogsInElasticFormat", false); var logConf = new LoggerConfiguration() .ReadFrom.Configuration(hostContext.Configuration); if (formatElastic) { var logFormatter = new ExceptionAsObjectJsonFormatter(renderMessage: true); logConf.WriteTo.Console(logFormatter); } else { logConf.WriteTo.Console(); } Log.Logger = logConf.CreateLogger(); configLogging.AddSerilog(dispose: true); }).ConfigureServices((hostContext, services) => { var serviceProvider = services.BuildServiceProvider(); var logger = serviceProvider.GetRequiredService <ILogger <Program> >(); services.AddGigDataApiEngine(); services.AddGigDataApiEngineDataFetching(hostContext.Configuration); services.AddGigDataApiEnginePlatformAuthentication(hostContext.Configuration); services.AutoRegisterHandlersFromAssemblyOf <DataFetchCompleteHandler>(); services.AutoRegisterHandlersFromAssemblyOf <DataFetchCompleteMessageHandler>(); //Gigplatform data update handler. var rebusSection = hostContext.Configuration.GetSection("Rebus"); var inputQueueName = rebusSection.GetValue <string>("InputQueueName"); var errorQueueName = rebusSection.GetValue <string>("ErrorQueueName"); var timeoutsFilesystemFolder = rebusSection.GetValue <string>("TimeoutsFilesystemFolder"); services.Configure <RebusConfiguration>(c => { c.InputQueueName = inputQueueName; c.ErrorQueueName = errorQueueName; }); var rabbitMqConnectionString = hostContext.Configuration.GetConnectionString("RabbitMq"); var rabbitMqConnectionEndpoint = new ConnectionEndpoint { ConnectionString = rabbitMqConnectionString }; var jsonSerializerSettings = new JsonSerializerSettings { ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, ContractResolver = new PrivateResolver() }; services.AddRebus(c => c .Transport(t => t.UseRabbitMq(new List <ConnectionEndpoint> { rabbitMqConnectionEndpoint }, inputQueueName)) .Timeouts(t => { if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { //we can't use file system since it uses locking api on the underlying file stream which is not supported on OS X. //See: https://github.com/dotnet/coreclr/commit/0daa63e9ed40323b6f248ded8959530ea94f19aa t.StoreInMemory(); } else { t.UseFileSystem(timeoutsFilesystemFolder); } }) .Options(o => { o.SimpleRetryStrategy(errorQueueAddress: errorQueueName, secondLevelRetriesEnabled: true); o.SetNumberOfWorkers(1); o.SetMaxParallelism(1); }) .Logging(l => l.Serilog()) .Routing(r => r.TypeBased() .Map <FetchDataForPlatformConnectionMessage>(inputQueueName) .Map <PlatformConnectionUpdateNotificationMessage>(inputQueueName)) .Serialization(s => s.UseNewtonsoftJson(jsonSerializerSettings)) ); if (hostContext.HostingEnvironment.IsDevelopment()) { services.AddDistributedMemoryCache(); } else { services.AddDistributedRedisCache(a => { a.Configuration = hostContext.Configuration.GetConnectionString("Redis"); a.InstanceName = "master"; }); } var ravenDbSection = hostContext.Configuration.GetSection("RavenDb"); var urls = new List <string>(); ravenDbSection.GetSection("Urls").Bind(urls); var databaseName = ravenDbSection.GetValue <string>("DatabaseName"); var certPwd = ravenDbSection.GetValue <string>("CertPwd"); var certPath = ravenDbSection.GetValue <string>("CertPath"); var keyPath = ravenDbSection.GetValue <string>("KeyPath"); logger.LogInformation($"Will use the following database name: '{databaseName}'"); logger.LogInformation($"Will use the following database urls: {string.Join(", ", urls)}"); DocumentStoreHolder.Logger = logger; DocumentStoreHolder.Urls = urls.ToArray(); DocumentStoreHolder.DatabaseName = databaseName; DocumentStoreHolder.CertPwd = certPwd; DocumentStoreHolder.CertPath = certPath; DocumentStoreHolder.KeyPath = keyPath; DocumentStoreHolder.TypeInAssemblyContainingIndexesToCreate = typeof(Users_ByPlatformConnectionPossiblyRipeForDataFetch); services.AddSingleton(DocumentStoreHolder.Store); services.AddHostedService <TimedDataFetcherTriggerTask>(); }); var host = builder.Build(); using (host) { var logger = host.Services.GetRequiredService <ILogger <Program> >(); logger.LogInformation("Setting up handler for unhandled exceptions."); var currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += (sender, eventArgs) => { var exception = (Exception)eventArgs.ExceptionObject; logger.LogError(exception, "Got unhandled exception"); }; logger.LogInformation("Will start Rebus"); host.Services.UseRebus(); logger.LogInformation("Starting host."); await host.RunAsync(); } }
public async Task RunAsync() { #region Abrindo o arquivo de configuração do bot. string projectPath = Path.GetFullPath(Path.Combine(AppContext.BaseDirectory, "..\\..\\..\\")); string configFilePath = $"{projectPath}{ConfigurationManager.AppSettings["ClientConfigJson"]}"; string json = string.Empty; FileStream fileStream = null; try { fileStream = File.OpenRead(configFilePath); using (StreamReader streamReader = new StreamReader(fileStream, new UTF8Encoding(false))) { fileStream = null; json = await streamReader.ReadToEndAsync().ConfigureAwait(false); } } finally { if (fileStream != null) { fileStream.Dispose(); } } configJson = JsonConvert.DeserializeObject <ConfigJson>(json); #endregion #region Configurando o bot com o Token do arquivo de configuração. DiscordConfiguration config = new DiscordConfiguration { Token = configJson.Token, TokenType = TokenType.Bot, AutoReconnect = true, MinimumLogLevel = LogLevel.Debug }; #endregion #region Instanciando o bot(_client) e configurando a extensão de interactividade. Client = new DiscordClient(config); Client.Ready += OnClientReady; Client.UseInteractivity(new InteractivityConfiguration { Timeout = TimeSpan.FromMinutes(2), }); await Client.ConnectAsync(); #endregion #region Inicializando o serviço de audio do _client ConnectionEndpoint endpoint = new ConnectionEndpoint { Hostname = configJson.EndpointHostname, Port = configJson.EndpointPort }; LavalinkConfiguration lavalinkConfig = new LavalinkConfiguration { Password = configJson.LavalinkPassword, RestEndpoint = endpoint, SocketEndpoint = endpoint, }; Lavalink = Client.UseLavalink(); LavalinkNode = await Lavalink.ConnectAsync(lavalinkConfig); #endregion #region Configuração e registro dos comandos do bot. CommandsNextConfiguration commandsConfiguration = new CommandsNextConfiguration() { StringPrefixes = new string[] { configJson.CommandPrefix }, EnableDms = false, EnableMentionPrefix = true, DmHelp = false }; Commands = Client.UseCommandsNext(commandsConfiguration); Commands.RegisterCommands <ModeratorCommands>(); Commands.RegisterCommands <UserCommands>(); #endregion LavalinkNode.PlaybackFinished += Lavalink_PlaybackFinished; await Task.Delay(-1); }