public WebSocket(DiscordClient client, JsonSerializer serializer, Logger logger) { _client = client; Logger = logger; _serializer = serializer; _lock = new AsyncLock(); _taskManager = new TaskManager(Cleanup); CancelToken = new CancellationToken(true); _connectedEvent = new ManualResetEventSlim(false); #if !DOTNET5_4 _engine = new WS4NetEngine(client.Config, _taskManager); #else _engine = new BuiltInEngine(client.Config); #endif _engine.BinaryMessage += (s, e) => { using (var compressed = new MemoryStream(e.Data, 2, e.Data.Length - 2)) using (var decompressed = new MemoryStream()) { using (var zlib = new DeflateStream(compressed, CompressionMode.Decompress)) zlib.CopyTo(decompressed); decompressed.Position = 0; using (var reader = new StreamReader(decompressed)) ProcessMessage(reader.ReadToEnd()).GetAwaiter().GetResult(); } }; _engine.TextMessage += (s, e) => ProcessMessage(e.Message).Wait(); }
public AudioClient(DiscordClient client, Server server, int id) { Id = id; _config = client.Config; Service = client.Services.Get<AudioService>(); Config = Service.Config; Serializer = client.Serializer; _gatewayState = (int)ConnectionState.Disconnected; //Logging Logger = client.Log.CreateLogger($"AudioClient #{id}"); //Async _taskManager = new TaskManager(Cleanup, false); _connectionLock = new AsyncLock(); CancelToken = new CancellationToken(true); //Networking if (Config.EnableMultiserver) { ClientAPI = new JsonRestClient(_config, DiscordConfig.ClientAPIUrl, client.Log.CreateLogger($"ClientAPI #{id}")); GatewaySocket = new GatewaySocket(_config, client.Serializer, client.Log.CreateLogger($"Gateway #{id}")); GatewaySocket.Connected += (s, e) => { if (_gatewayState == ConnectionState.Connecting) EndGatewayConnect(); }; } else GatewaySocket = client.GatewaySocket; GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e); VoiceSocket = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}")); VoiceSocket.Server = server; OutputStream = new OutStream(this); }
static void Main(string[] args) { var client = new DiscordClient(); //Display all log messages in the console client.LogMessage += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); //Echo back any message received, provided it didn't come from the bot itself client.MessageReceived += async (s, e) => { if (!e.Message.IsAuthor) await client.SendMessage(e.Channel, e.Message.Text); }; //Convert our sync method to an async one and block the Main function until the bot disconnects client.Run(async () => { //Connect to the Discord server using our email and password await client.Connect("*****@*****.**", "Password123"); //If we are not a member of any server, use our invite code (made beforehand in the official Discord Client) if (!client.AllServers.Any()) await client.AcceptInvite(client.GetInvite("aaabbbcccdddeee")); }); }
static void Main(string[] args) { var client = new DiscordClient(); //Log some info to console client.LogMessage += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); //Echo any message received, provided it didn't come from us client.MessageCreated += async (s, e) => { if (!e.Message.IsAuthor) await client.SendMessage(e.Message.ChannelId, e.Message.Text); }; //Convert our sync method to an async one and blocks this function until the client disconnects client.Run(async () => { //Connect to the Discord server usinotng our email and password await client.Connect("*****@*****.**", "Password123"); //If we are not a member of any server, use our invite code if (!client.Servers.Any()) await client.AcceptInvite("aaabbbcccdddeee"); }); }
public CommandsManager(DiscordClient client) { __client = client; __commands = new List<ICommand>(); __modules = new Dictionary<IModule, bool>(); __internalUserRoles = new Dictionary<string, PermissionType>(); Console.Write(""); }
internal MessageQueue(DiscordClient client, Logger logger) { _client = client; _logger = logger; _nonceRand = new Random(); _pending = new ConcurrentQueue<MessageQueueItem>(); }
internal MessageQueue(DiscordClient client, Logger logger) { _client = client; _logger = logger; _nonceRand = new Random(); _pendingActions = new ConcurrentQueue<IQueuedAction>(); _pendingSends = new ConcurrentDictionary<int, Message>(); }
public GatewaySocket(DiscordClient client, JsonSerializer serializer, Logger logger) : base(client, serializer, logger) { Disconnected += async (s, e) => { if (e.WasUnexpected) await Reconnect().ConfigureAwait(false); }; }
internal VoiceWebSocket(DiscordClient client, AudioClient audioClient, Logger logger) : base(client, logger) { _audioClient = audioClient; _config = client.Audio().Config; _decoders = new ConcurrentDictionary<uint, OpusDecoder>(); _targetAudioBufferLength = _config.BufferLength / 20; //20 ms frames _encodingBuffer = new byte[MaxOpusSize]; _ssrcMapping = new ConcurrentDictionary<uint, ulong>(); _encoder = new OpusEncoder(48000, _config.Channels, 20, _config.Bitrate, OpusApplication.MusicOrMixed); _sendBuffer = new VoiceBuffer((int)Math.Ceiling(_config.BufferLength / (double)_encoder.FrameLength), _encoder.FrameSize); }
internal ModuleManager(DiscordClient client, IModule instance, string name, ModuleFilter filterType) { Client = client; Instance = instance; Name = name; FilterType = filterType; Id = name.ToLowerInvariant(); _lock = new AsyncLock(); _allowAll = filterType == ModuleFilter.None; _useServerWhitelist = filterType.HasFlag(ModuleFilter.ServerWhitelist); _useChannelWhitelist = filterType.HasFlag(ModuleFilter.ChannelWhitelist); _allowPrivate = filterType.HasFlag(ModuleFilter.AlwaysAllowPrivate); _enabledServers = new ConcurrentDictionary<ulong, Server>(); _enabledChannels = new ConcurrentDictionary<ulong, Channel>(); _indirectServers = new ConcurrentDictionary<ulong, int>(); if (_allowAll || _useServerWhitelist) //Server-only events { client.ChannelCreated += (s, e) => { if (e.Server != null && HasServer(e.Server)) ChannelCreated(s, e); }; client.UserVoiceStateUpdated += (s, e) => { if (HasServer(e.Server)) UserVoiceStateUpdated(s, e); }; } client.ChannelDestroyed += (s, e) => { if (HasChannel(e.Channel)) ChannelDestroyed(s, e); }; client.ChannelUpdated += (s, e) => { if (HasChannel(e.Channel)) ChannelUpdated(s, e); }; client.MessageReceived += (s, e) => { if (HasChannel(e.Channel)) MessageReceived(s, e); }; client.MessageSent += (s, e) => { if (HasChannel(e.Channel)) MessageSent(s, e); }; client.MessageDeleted += (s, e) => { if (HasChannel(e.Channel)) MessageDeleted(s, e); }; client.MessageUpdated += (s, e) => { if (HasChannel(e.Channel)) MessageUpdated(s, e); }; client.MessageAcknowledged += (s, e) => { if (HasChannel(e.Channel)) MessageReadRemotely(s, e); }; client.RoleCreated += (s, e) => { if (HasIndirectServer(e.Server)) RoleCreated(s, e); }; client.RoleUpdated += (s, e) => { if (HasIndirectServer(e.Server)) RoleUpdated(s, e); }; client.RoleDeleted += (s, e) => { if (HasIndirectServer(e.Server)) RoleDeleted(s, e); }; client.LeftServer += (s, e) => { if (HasIndirectServer(e.Server)) { DisableServer(e.Server); LeftServer(s, e); } }; client.ServerUpdated += (s, e) => { if (HasIndirectServer(e.Server)) ServerUpdated(s, e); }; client.ServerUnavailable += (s, e) => { if (HasIndirectServer(e.Server)) ServerUnavailable(s, e); }; client.ServerAvailable += (s, e) => { if (HasIndirectServer(e.Server)) ServerAvailable(s, e); }; client.UserJoined += (s, e) => { if (HasIndirectServer(e.Server)) UserJoined(s, e); }; client.UserLeft += (s, e) => { if (HasIndirectServer(e.Server)) UserLeft(s, e); }; client.UserUpdated += (s, e) => { if (HasIndirectServer(e.Server)) UserUpdated(s, e); }; client.UserIsTypingUpdated += (s, e) => { if (HasChannel(e.Channel)) UserIsTypingUpdated(s, e); }; //TODO: We aren't getting events from UserPresence if AllowPrivate is enabled, but the server we know that user through isn't on the whitelist client.UserPresenceUpdated += (s, e) => { if (HasIndirectServer(e.Server)) UserPresenceUpdated(s, e); }; client.UserBanned += (s, e) => { if (HasIndirectServer(e.Server)) UserBanned(s, e); }; client.UserUnbanned += (s, e) => { if (HasIndirectServer(e.Server)) UserUnbanned(s, e); }; }
public OfficeBot() { // Startup Code DiscordClient Client = new DiscordClient(Logger => { Logger.LogLevel = LogSeverity.Info; Logger.LogHandler += delegate (object Sender, LogMessageEventArgs EvArgs) { Console.WriteLine(EvArgs.Message); }; }); // Check and prevent user from moving to office channel if he does not own it Client.UserUpdated += async (object Sender, UserUpdatedEventArgs EvArgs) => { if (EvArgs.Before.VoiceChannel != EvArgs.After.VoiceChannel && EvArgs.After.VoiceChannel != null && EvArgs.After.VoiceChannel.Users.Count() > 1) { Dictionary<Channel, List<User>> OfficeChannels = GetOfficeChannels(EvArgs.Server); if (OfficeChannels.ContainsKey(EvArgs.After.VoiceChannel)) { List<User> ValidUsers = OfficeChannels[EvArgs.After.VoiceChannel]; if (!ValidUsers.Contains(EvArgs.After)) { await EvArgs.Before.Edit(voiceChannel: EvArgs.Before.VoiceChannel); } } } }; Client.ExecuteAndWait(async () => { while (true) { try { await Client.Connect(DiscordBot_OfficeBot.OfficeBotTokenCarrier.Token, TokenType.Bot); break; } catch { await Task.Delay(3000); } } }); }
static void Main(string[] args) { var client = new DiscordClient(); // Handle Events using Lambdas client.MessageCreated += (s, e) => { if (!e.Message.IsAuthor) await client.SendMessage(e.Message.ChannelId, "foo"); } // Handle Events using Event Handlers EventHandler<MessageEventArgs> handler = new EventHandler<MessageEventArgs>(HandleMessageCreated); client.MessageCreated += handler; }
static void Main(string[] args) { var client = new DiscordClient(new DiscordClientConfig { //Warning: Debug mode should only be used for identifying problems. It _will_ slow your application down. LogLevel = LogMessageSeverity.Debug }); client.LogMessage += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); client.Run(async () => { await client.Connect("*****@*****.**", "Password123"); if (!client.Servers.Any()) await client.AcceptInvite("aaabbbcccdddeee"); }); }
void IService.Install(DiscordClient client) { Client = client; _voiceClients = new ConcurrentDictionary<ulong, AudioClient>(); _talkingUsers = new ConcurrentDictionary<User, bool>(); client.GatewaySocket.Disconnected += (s, e) => { foreach (var member in _talkingUsers) { bool ignored; if (_talkingUsers.TryRemove(member.Key, out ignored)) OnUserIsSpeakingUpdated(member.Key, false); } }; }
void IService.Install(DiscordClient client) { Client = client; if (Config.EnableMultiserver) _voiceClients = new ConcurrentDictionary<ulong, AudioClient>(); else { var logger = Client.Log.CreateLogger("Voice"); _defaultClient = new AudioClient(Client, null, 0); } _talkingUsers = new ConcurrentDictionary<User, bool>(); client.GatewaySocket.Disconnected += async (s, e) => { if (Config.EnableMultiserver) { var tasks = _voiceClients .Select(x => { var val = x.Value; if (val != null) return x.Value.Disconnect(); else return TaskHelper.CompletedTask; }) .ToArray(); await Task.WhenAll(tasks).ConfigureAwait(false); _voiceClients.Clear(); } foreach (var member in _talkingUsers) { bool ignored; if (_talkingUsers.TryRemove(member.Key, out ignored)) OnUserIsSpeakingUpdated(member.Key, false); } }; }
public AudioClient(DiscordClient client, Server server, int id) { Id = id; Service = client.GetService<AudioService>(); Config = Service.Config; Serializer = client.Serializer; _gatewayState = (int)ConnectionState.Disconnected; //Logging Logger = client.Log.CreateLogger($"AudioClient #{id}"); //Async _taskManager = new TaskManager(Cleanup, false); _connectionLock = new AsyncLock(); CancelToken = new CancellationToken(true); //Networking _config = client.Config; GatewaySocket = client.GatewaySocket; GatewaySocket.ReceivedDispatch += (s, e) => OnReceivedEvent(e); VoiceSocket = new VoiceSocket(_config, Config, client.Serializer, client.Log.CreateLogger($"Voice #{id}")); VoiceSocket.Server = server; OutputStream = new OutStream(this); }
public MessageCleaner(DiscordClient client) { _userRegex = new Regex(@"<@\d+?>", RegexOptions.Compiled); _userRegexEvaluator = new MatchEvaluator(e => { string id = e.Value.Substring(2, e.Value.Length - 3); var user = client.Users[id]; if (user != null) return '@' + user.Name; else //User not found return e.Value; }); _channelRegex = new Regex(@"<#\d+?>", RegexOptions.Compiled); _channelRegexEvaluator = new MatchEvaluator(e => { string id = e.Value.Substring(2, e.Value.Length - 3); var channel = client.Channels[id]; if (channel != null) return channel.Name; else //Channel not found return e.Value; }); }
public static async Task <bool> CheckMessageForInvitesAsync(DiscordClient client, DiscordMessage message) { if (message.Channel.IsPrivate) { return(true); } if (message.Author.IsBot) { return(true); } if (message.Author.IsWhitelisted(client, message.Channel.Guild)) { return(true); } if (message.Reactions.Any(r => r.Emoji == Config.Reactions.Moderated && r.IsMe)) { return(true); } var(hasInvalidResults, invites) = await client.GetInvitesAsync(message.Content).ConfigureAwait(false); if (!hasInvalidResults && invites.Count == 0) { return(true); } if (hasInvalidResults) { try { await message.DeleteAsync("Not a white-listed discord invite link").ConfigureAwait(false); await client.ReportAsync("An unapproved discord invite", message, "In invalid or expired invite", null, ReportSeverity.Low).ConfigureAwait(false); await message.Channel.SendMessageAsync($"{message.Author.Mention} please refrain from posting invites that were not approved by a moderator, especially expired or invalid.").ConfigureAwait(false); } catch (Exception e) { Config.Log.Warn(e); await client.ReportAsync("An unapproved discord invite", message, "In invalid or expired invite", null, ReportSeverity.Medium).ConfigureAwait(false); await message.ReactWithAsync( client, Config.Reactions.Moderated, $"{message.Author.Mention} please remove this expired or invalid invite, and refrain from posting it again until you have recieved an approval from a moderator.", true ).ConfigureAwait(false); } return(false); } foreach (var invite in invites) { if (!await InviteWhitelistProvider.IsWhitelistedAsync(invite).ConfigureAwait(false)) { try { await message.DeleteAsync("Not a white-listed discord invite link").ConfigureAwait(false); await client.ReportAsync("An unapproved discord invite", message, $"Invite {invite.Code} was resolved to the {invite.Guild.Name} server", null, ReportSeverity.Low).ConfigureAwait(false); await message.Channel.SendMessageAsync($"{message.Author.Mention} invites to other servers must be whitelisted first.\n" + $"Please refrain from posting it again until you have received an approval from a moderator.").ConfigureAwait(false); } catch (Exception e) { Config.Log.Warn(e); await client.ReportAsync("An unapproved discord invite", message, $"Invite {invite.Code} was resolved to the {invite.Guild.Name} server", null, ReportSeverity.Medium).ConfigureAwait(false); await message.ReactWithAsync( client, Config.Reactions.Moderated, $"{message.Author.Mention} invites to other servers must be whitelisted first.\n" + $"Please remove it and refrain from posting it again until you have received an approval from a moderator.", true ).ConfigureAwait(false); } return(false); } } return(true); }
public PokeMeCommand(DiscordClient client, IDatabase db, Config config) { _client = client; _db = db; _config = config; }
void IService.Install(DiscordClient client) { Client = client; if (Config.HelpMode != HelpMode.Disabled) { CreateCommand("help") .Parameter("command", ParameterType.Multiple) .Hide() .Description("Returns information about commands.") .Do(async e => { Channel replyChannel = Config.HelpMode == HelpMode.Public ? e.Channel : await e.User.CreatePMChannel().ConfigureAwait(false); if (e.Args.Length > 0) //Show command help { var map = _map.GetItem(string.Join(" ", e.Args)); if (map != null) await ShowCommandHelp(map, e.User, e.Channel, replyChannel).ConfigureAwait(false); else await replyChannel.SendMessage("Unable to display help: Unknown command.").ConfigureAwait(false); } else //Show general help await ShowGeneralHelp(e.User, e.Channel, replyChannel).ConfigureAwait(false); }); } client.MessageReceived += async (s, e) => { if (_allCommands.Count == 0) return; if (Config.IsSelfBot) { if (e.Message.User == null || e.Message.User.Id != Client.CurrentUser.Id) return; // Will only listen to Self } else if (e.Message.User == null || e.Message.User.Id == Client.CurrentUser.Id) return; // Normal expected behavior for bots string msg = e.Message.RawText; if (msg.Length == 0) return; string cmdMsg = null; //Check for command char if (Config.PrefixChar.HasValue) { if (msg[0] == Config.PrefixChar.Value) cmdMsg = msg.Substring(1); } //Check for mention if (cmdMsg == null && Config.AllowMentionPrefix) { string mention = client.CurrentUser.Mention; if (msg.StartsWith(mention) && msg.Length > mention.Length) cmdMsg = msg.Substring(mention.Length + 1); else { mention = $"@{client.CurrentUser.Name}"; if (msg.StartsWith(mention) && msg.Length > mention.Length) cmdMsg = msg.Substring(mention.Length + 1); } string mention2 = client.CurrentUser.NicknameMention; if (mention2 != null) { if (msg.StartsWith(mention2) && msg.Length > mention2.Length) cmdMsg = msg.Substring(mention2.Length + 1); else { mention2 = $"@{client.CurrentUser.Name}"; if (msg.StartsWith(mention2) && msg.Length > mention2.Length) cmdMsg = msg.Substring(mention2.Length + 1); } } } //Check using custom activator if (cmdMsg == null && Config.CustomPrefixHandler != null) { int index = Config.CustomPrefixHandler(e.Message); if (index >= 0) cmdMsg = msg.Substring(index); } if (cmdMsg == null) return; //Parse command IEnumerable<Command> commands; int argPos; CommandParser.ParseCommand(cmdMsg, _map, out commands, out argPos); if (commands == null) { CommandEventArgs errorArgs = new CommandEventArgs(e.Message, null, null); OnCommandError(CommandErrorType.UnknownCommand, errorArgs); return; } else { foreach (var command in commands) { //Parse arguments string[] args; var error = CommandParser.ParseArgs(cmdMsg, argPos, command, out args); if (error != null) { if (error == CommandErrorType.BadArgCount) continue; else { var errorArgs = new CommandEventArgs(e.Message, command, null); OnCommandError(error.Value, errorArgs); return; } } var eventArgs = new CommandEventArgs(e.Message, command, args); // Check permissions string errorText; if (!command.CanRun(eventArgs.User, eventArgs.Channel, out errorText)) { OnCommandError(CommandErrorType.BadPermissions, eventArgs, errorText != null ? new Exception(errorText) : null); return; } // Run the command try { OnCommand(eventArgs); await command.Run(eventArgs).ConfigureAwait(false); } catch (Exception ex) { OnCommandError(CommandErrorType.Exception, eventArgs, ex); } return; } var errorArgs2 = new CommandEventArgs(e.Message, null, null); OnCommandError(CommandErrorType.BadArgCount, errorArgs2); } }; }
public GalleryMessageProcessor(DiscordClient discordClient, CloudWatchMetrics metrics, ILogger <GalleryMessageProcessor> logger) : base(discordClient, metrics, logger) { }
public void Start(string[] args) { client = new DiscordClient() .UsingAudio(audio => { audio.Mode = AudioMode.Outgoing; }) .UsingModules(); client.MessageReceived += async(source, e) => { if (e.Message.Text.Contains("Hello Discord Bot")) { await e.Channel.SendMessage("Hello"); } }; client.UsingCommands(input => { input.PrefixChar = '$'; input.AllowMentionPrefix = true; }); var commands = client.GetService <CommandService>(); commands.CreateCommand("voice") .Parameter("selected", ParameterType.Required) .Do(async(e) => { var dave = e.GetArg("selected"); int position = 0; try { position = Convert.ToInt32(dave); } catch { position = 0; } var voiceChannel = e.Server.VoiceChannels.FirstOrDefault(); if (voiceChannel != null) { audio = await voiceChannel.JoinAudio(); switch (audio.State) { case ConnectionState.Connected: break; } var _vClient = await client.GetService <AudioService>() // We use GetService to find the AudioService that we installed earlier. In previous versions, this was equivelent to _client.Audio() .Join(voiceChannel); SendAudio(_vClient, client, files[position]); await voiceChannel.LeaveAudio(); } }); commands.CreateCommand("list").Do(async(e) => { string output = ""; int counter = 0; foreach (string files in files) { output += "(" + counter + ") : " + files + "\n"; counter++; } await e.Channel.SendMessage("```" + output + "```"); }); client.ServerAvailable += (s, e) => { Console.WriteLine($"Server \"{e.Server.Name}\" Is Online"); }; client.ExecuteAndWait(async() => { await client.Connect(" INSERT CLIENT CODE", TokenType.Bot); await client.WaitForServer().ConfigureAwait(false); //client.AddModule<Modules.Links>(); // Use for later tutorials }); }
internal CachedObject(DiscordClient client, string id) { _client = client; Id = id; }
public void DeleteInvite(DiscordClient client, Action <Invite> callback = null) { client.REST.DoRequest($"/invites/{Code}", RequestMethod.DELETE, null, callback); }
public static void GetInvite(DiscordClient client, string inviteCode, Action <Invite> callback = null) { client.REST.DoRequest($"/invites/{inviteCode}", RequestMethod.GET, null, callback); }
void IModule.Install(ModuleManager manager) { _manager = manager; _client = manager.Client; _service = manager.Client.GetService <ModuleService>(); manager.CreateCommands("modules", group => { group.MinPermissions((int)PermissionLevel.BotOwner); group.CreateCommand("list") .Description("Gives a list of all available modules.") .Do(async e => { string text = "Available Modules: " + string.Join(", ", _service.Modules.Select(x => x.Id)); await _client.Reply(e, text); }); group.CreateCommand("enable") .Description("Enables a module for this server.") .Parameter("module") .PublicOnly() .Do(e => { var module = GetModule(e.Args[0]); if (module == null) { _client.ReplyError(e, "Unknown module"); return; } if (module.FilterType == ModuleFilter.None || module.FilterType == ModuleFilter.AlwaysAllowPrivate) { _client.ReplyError(e, "This module is global and cannot be enabled/disabled."); return; } if (!module.FilterType.HasFlag(ModuleFilter.ServerWhitelist)) { _client.ReplyError(e, "This module doesn't support being enabled for servers."); return; } var server = e.Server; if (!module.EnableServer(server)) { _client.ReplyError(e, $"Module {module.Id} was already enabled for server {server.Name}."); return; } _client.Reply(e, $"Module {module.Id} was enabled for server {server.Name}."); }); group.CreateCommand("disable") .Description("Disables a module for this server.") .Parameter("module") .PublicOnly() .Do(e => { var module = GetModule(e.Args[0]); if (module == null) { _client.ReplyError(e, "Unknown module"); return; } if (module.FilterType == ModuleFilter.None || module.FilterType == ModuleFilter.AlwaysAllowPrivate) { _client.ReplyError(e, "This module is global and cannot be enabled/disabled."); return; } if (!module.FilterType.HasFlag(ModuleFilter.ServerWhitelist)) { _client.ReplyError(e, "This module doesn't support being enabled for servers."); return; } var server = e.Server; if (!module.DisableServer(server)) { _client.ReplyError(e, $"Module {module.Id} was not enabled for server {server.Name}."); return; } _client.Reply(e, $"Module {module.Id} was disabled for server {server.Name}."); }); }); }
private Task ClientError(DiscordClient sender, ClientErrorEventArgs e) { sender.Logger.LogError(BotEventId, e.Exception, "Exception occured"); return(Task.CompletedTask); }
private Task ClientGuildAvailable(DiscordClient sender, GuildCreateEventArgs e) { sender.Logger.LogInformation(BotEventId, $"Guild available: {e.Guild.Name}"); return(Task.CompletedTask); }
void IService.Install(DiscordClient client) { Client = client; Config.Lock(); if (Config.HelpMode != HelpMode.Disabled) { CreateCommand("help") .Parameter("command", ParameterType.Multiple) .Hide() .Description("Returns information about commands.") .Do(async e => { Channel replyChannel = Config.HelpMode == HelpMode.Public ? e.Channel : await e.User.CreatePMChannel().ConfigureAwait(false); if (e.Args.Length > 0) //Show command help { var map = _map.GetItem(string.Join(" ", e.Args)); if (map != null) { await ShowCommandHelp(map, e.User, e.Channel, replyChannel).ConfigureAwait(false); } else { await replyChannel.SendMessage("Unable to display help: Unknown command.").ConfigureAwait(false); } } else //Show general help { await ShowGeneralHelp(e.User, e.Channel, replyChannel).ConfigureAwait(false); } }); } client.MessageReceived += async(s, e) => { if (_allCommands.Count == 0) { return; } if (e.Message.User == null || e.Message.User.Id == Client.CurrentUser.Id) { return; } string msg = e.Message.RawText; if (msg.Length == 0) { return; } // Check ignored before doing work if (_getIgnoredChannelFlag != null ? _getIgnoredChannelFlag(e.Message.Channel, e.User) : false) { return; } //Check for command char if one is provided var chars = Config.CommandChars; bool mentionreq = Config.MentionCommandChar >= 1; if (chars.Any() || mentionreq) { bool hasCommandChar = chars.Contains(msg[0]); if (!hasCommandChar && (e.Message.Channel.IsPrivate ? Config.RequireCommandCharInPrivate : Config.RequireCommandCharInPublic)) { if (mentionreq && e.Message.IsMentioningMe()) { string neko = !string.IsNullOrEmpty(e.Server.CurrentUser.Nickname) ? client.CurrentUser.NicknameMention : client.CurrentUser.Mention; if (neko.Length + 2 > msg.Length) { NonCommands(e); return; } if (msg.StartsWith(neko)) { msg = msg.Substring(neko.Length + 1); } else { int index = Config.MentionCommandChar > 1 ? msg.LastIndexOf(neko) : -1; if (index == -1) { NonCommands(e); return; } msg = msg.Substring(0, index - 1); } // Ideally, don't let the command know that we were mentioned, if this is the only mention /*if (msg.IndexOf(neko) != -1) * { * e.Message.MentionedUsers = e.Message.MentionedUsers.Where(u => u == e.Server.CurrentUser); * e.Message.IsMentioningMe = false; * }*/ } else { NonCommands(e); return; } } else if (hasCommandChar) { msg = msg.Substring(1); } } //Parse command IEnumerable <Command> commands; int argPos; CommandParser.ParseCommand(msg, _map, out commands, out argPos); if (commands == null) { CommandEventArgs errorArgs = new CommandEventArgs(e.Message, null, null); OnCommandError(CommandErrorType.UnknownCommand, errorArgs); NonCommands(e); return; } else { foreach (var command in commands) { //Parse arguments string[] args; var error = CommandParser.ParseArgs(msg, argPos, command, out args); if (error != null) { if (error == CommandErrorType.BadArgCount) { continue; } else { var errorArgs = new CommandEventArgs(e.Message, command, null); OnCommandError(error.Value, errorArgs); return; } } var eventArgs = new CommandEventArgs(e.Message, command, args); // Check permissions string errorText; if (!command.CanRun(eventArgs.User, eventArgs.Channel, out errorText)) { OnCommandError(CommandErrorType.BadPermissions, eventArgs, errorText != null ? new Exception(errorText) : null); return; } // Check flags bool nsfwAllowed = _getNsfwFlag != null?_getNsfwFlag(e.Message.Channel) : false; if (!nsfwAllowed && !e.Channel.IsPrivate && command.NsfwFlag) { OnCommandError(CommandErrorType.BadPermissions, eventArgs, new NsfwFlagException()); return; } bool isInMusicChannel = _getMusicFlag != null?_getMusicFlag(e.Message.User) : false; if (command.MusicFlag && !isInMusicChannel) { OnCommandError(CommandErrorType.BadPermissions, eventArgs, new MusicFlagException()); return; } // Run the command try { OnCommand(eventArgs); await command.Run(eventArgs).ConfigureAwait(false); } catch (Exception ex) { OnCommandError(CommandErrorType.Exception, eventArgs, ex); } return; } var errorArgs2 = new CommandEventArgs(e.Message, null, null); OnCommandError(CommandErrorType.BadArgCount, errorArgs2); } }; }
static async Task HandleErrors(CommandsNextExtension ex, CommandErrorEventArgs er, DiscordClient client) { client.Logger.LogError(er.Exception.ToString()); if (er.Exception is ModBot.UserError) { await er.Context.RespondAsync(embed : Embeds.Error .WithFooter($"Use {er.Context.Prefix}support to get an invite to the support server") .WithDescription(er.Exception.Message)); } else if (er.Exception is ChecksFailedException) { foreach (var check in (er.Exception as ChecksFailedException).FailedChecks) { if (check is RequireUserPermissionsAttribute) { await er.Context.RespondAsync(embed : Embeds.Error .WithFooter($"Use {er.Context.Prefix}support to get an invite to the support server") .WithDescription($"You need {(check as RequireUserPermissionsAttribute).Permissions.ToString()} to run that command.")); } if (check is RequireBotPermissionsAttribute) { await er.Context.RespondAsync(embed : Embeds.Error .WithFooter($"Use {er.Context.Prefix}support to get an invite to the support server") .WithDescription($"I need {(check as RequireBotPermissionsAttribute).Permissions.ToString()} to run that command.")); } } } else if (er.Exception is System.ArgumentException) { await er.Context.RespondAsync(embed : Embeds.Error.WithTitle("Syntax Error").WithDescription($"Run `{er.Context.Prefix}help {er.Command.QualifiedName}` for more information.")); } else if (er.Exception is CommandNotFoundException) { } else { await er.Context.RespondAsync(embed : Embeds.Error.WithTitle("Unhandled Error") .WithDescription($"Something has gone wrong.\n```{er.Exception.Message.Truncate(2000)}```") .WithFooter($"Use {er.Context.Prefix}support to get an invite to the support server")); } }
internal PermissionLevelChecker(DiscordClient client, int minPermissions) { _service = client.Services.Get<PermissionLevelService>(true); _minPermissions = minPermissions; }
public void AcceptInvite(DiscordClient client, Action <Invite> callback = null) { client.REST.DoRequest($"/invites/{Code}", RequestMethod.POST, null, callback); }
/// <summary> /// DO NOT RUN THIS MANUALLY. /// </summary> /// <param name="client"></param> public void Setup(DiscordClient client) { this._client = client; this.Client.VoiceStateUpdate += this.Client_VoiceStateUpdate; this.Client.VoiceServerUpdate += this.Client_VoiceServerUpdate; }
internal GuildRoleCreateEventArgs(DiscordClient client) : base(client) { }
public HighlightService(IServiceProvider provider) : base(provider) { _localization = _provider.GetRequiredService <LocalizationService>(); _client = _provider.GetRequiredService <DiscordClient>(); }
internal DiscordMember(DiscordClient parent) { Roles = new List<DiscordRole>(); }
/// <summary> /// Creates a new VoiceNext client with specified settings. /// </summary> /// <param name="client">Discord client to create VoiceNext instance for.</param> /// <param name="config">Configuration for the VoiceNext client.</param> /// <returns>VoiceNext client instance.</returns> public static VoiceNextClient UseVoiceNext(this DiscordClient client, VoiceNextConfiguration config) { ClientInstance = new VoiceNextClient(config); client.AddModule(ClientInstance); return(ClientInstance); }
public CommandsPlugin(DiscordClient client, Func<User, int> getPermissions = null) { _client = client; _getPermissions = getPermissions; _commands = new List<Command>(); CommandChar = '/'; UseCommandChar = false; RequireCommandCharInPublic = true; RequireCommandCharInPrivate = true; client.MessageReceived += async (s, e) => { //If commands aren't being used, don't bother processing them if (_commands.Count == 0) return; //Ignore messages from ourselves if (e.Message.User == client.CurrentUser) return; //Check for the command character string msg = e.Message.Text; if (UseCommandChar) { if (msg.Length == 0) return; bool isPrivate = e.Message.Channel.IsPrivate; bool hasCommandChar = msg[0] == CommandChar; if (hasCommandChar) msg = msg.Substring(1); if (!isPrivate && RequireCommandCharInPublic && !hasCommandChar) return; if (isPrivate && RequireCommandCharInPrivate && !hasCommandChar) return; } CommandPart[] args; if (!CommandParser.ParseArgs(msg, out args)) return; for (int i = 0; i < _commands.Count; i++) { Command cmd = _commands[i]; //Check Command Parts if (args.Length < cmd.Parts.Length) continue; bool isValid = true; for (int j = 0; j < cmd.Parts.Length; j++) { if (!string.Equals(args[j].Value, cmd.Parts[j], StringComparison.OrdinalIgnoreCase)) { isValid = false; break; } } if (!isValid) continue; //Check Arg Count int argCount = args.Length - cmd.Parts.Length; if (argCount < cmd.MinArgs || argCount > cmd.MaxArgs) continue; //Clean Args string[] newArgs = new string[argCount]; for (int j = 0; j < newArgs.Length; j++) newArgs[j] = args[j + cmd.Parts.Length].Value; //Get ArgText string argText; if (argCount == 0) argText = ""; else argText = msg.Substring(args[cmd.Parts.Length].Index); //Check Permissions int permissions = _getPermissions != null ? _getPermissions(e.Message.User) : 0; var eventArgs = new CommandEventArgs(e.Message, cmd, msg, argText, permissions, newArgs); if (permissions < cmd.MinPerms) { RaiseCommandError(eventArgs, new PermissionException()); return; } //Run Command RaiseRanCommand(eventArgs); try { var task = cmd.Handler(eventArgs); if (task != null) await task.ConfigureAwait(false); } catch (Exception ex) { RaiseCommandError(eventArgs, ex); } break; } }; }
void IService.Install(DiscordClient client) { _client = client; }
/// <summary> /// Creates a new VoiceNext client with default settings. /// </summary> /// <param name="client">Discord client to create VoiceNext instance for.</param> /// <returns>VoiceNext client instance.</returns> public static VoiceNextClient UseVoiceNext(this DiscordClient client) => UseVoiceNext(client, new VoiceNextConfiguration { VoiceApplication = VoiceApplication.Music });
void IService.Install(DiscordClient client) { Client = client; Config.Lock(); if (Config.HelpMode != HelpMode.Disable) { CreateCommand("help") .Parameter("command", ParameterType.Multiple) .Hide() .Description("Returns information about commands.") .Do(async e => { Channel replyChannel = Config.HelpMode == HelpMode.Public ? e.Channel : await e.User.CreatePMChannel().ConfigureAwait(false); if (e.Args.Length > 0) //Show command help { var map = _map.GetItem(string.Join(" ", e.Args)); if (map != null) await ShowCommandHelp(map, e.User, e.Channel, replyChannel).ConfigureAwait(false); else await replyChannel.SendMessage("Unable to display help: Unknown command.").ConfigureAwait(false); } else //Show general help await ShowGeneralHelp(e.User, e.Channel, replyChannel).ConfigureAwait(false); }); } client.MessageReceived += async (s, e) => { if (_allCommands.Count == 0) return; if (e.Message.User == null || e.Message.User.Id == Client.CurrentUser.Id) return; string msg = e.Message.RawText; if (msg.Length == 0) return; //Check for command char if one is provided var chars = Config.CommandChars; if (chars.Length > 0) { if (!chars.Contains(msg[0])) return; msg = msg.Substring(1); } //Parse command IEnumerable<Command> commands; int argPos; CommandParser.ParseCommand(msg, _map, out commands, out argPos); if (commands == null) { CommandEventArgs errorArgs = new CommandEventArgs(e.Message, null, null); OnCommandError(CommandErrorType.UnknownCommand, errorArgs); return; } else { foreach (var command in commands) { //Parse arguments string[] args; var error = CommandParser.ParseArgs(msg, argPos, command, out args); if (error != null) { if (error == CommandErrorType.BadArgCount) continue; else { var errorArgs = new CommandEventArgs(e.Message, command, null); OnCommandError(error.Value, errorArgs); return; } } var eventArgs = new CommandEventArgs(e.Message, command, args); // Check permissions string errorText; if (!command.CanRun(eventArgs.User, eventArgs.Channel, out errorText)) { OnCommandError(CommandErrorType.BadPermissions, eventArgs, errorText != null ? new Exception(errorText) : null); return; } // Run the command try { OnCommand(eventArgs); await command.Run(eventArgs).ConfigureAwait(false); } catch (Exception ex) { OnCommandError(CommandErrorType.Exception, eventArgs, ex); } return; } var errorArgs2 = new CommandEventArgs(e.Message, null, null); OnCommandError(CommandErrorType.BadArgCount, errorArgs2); } }; }
/// <summary> /// Retrieves the registered <see cref="InteractivityExtension"/> instance for this client. /// </summary> /// <param name="client">The client to retrieve an <see cref="InteractivityExtension"/> instance from.</param> /// <returns>An existing <see cref="InteractivityExtension"/> instance, or <see langword="null"/> if interactivity is not enabled for the <see cref="DiscordClient"/> instance.</returns> public static InteractivityExtension GetInteractivity(this DiscordClient client) => client.GetExtension <InteractivityExtension>();
/// <summary> /// Gets the active instance of VoiceNext client for the DiscordClient. /// </summary> /// <param name="client">Discord client to get VoiceNext instance for.</param> /// <returns>VoiceNext client instance.</returns> public static VoiceNextClient GetVoiceNextClient(this DiscordClient client) => ClientInstance;
public DiscordGuildChannel(DiscordChannelPacket packet, DiscordClient client) : base(packet, client) { }
private static void DuplicateChannels(DiscordClient client, Guild targetGuild, Guild ourGuild, List <RoleDupe> ourRoles) { OrganizedChannelList channels = new OrganizedChannelList(targetGuild.GetChannels()); Console.WriteLine("Duplicating categories..."); //duplicate category channels List <CategoryDupe> ourCategories = new List <CategoryDupe>(); foreach (var c in channels.Categories) { GuildChannel category; try { category = client.GetGuildChannel(c.Id); } catch (DiscordHttpException e) { //ofcourse you could make it return no matter what error, but this is better for debugging if (e.Code == DiscordError.MissingAccess) { continue; } else { throw; } } //create the category GuildChannel ourCategory = ourGuild.CreateChannel(category.Name, ChannelType.Category); ourCategory.Modify(new GuildChannelProperties() { Position = category.Position }); foreach (var overwrite in category.PermissionOverwrites) { if (overwrite.Type == PermissionOverwriteType.Member) { continue; } PermissionOverwrite ourOverwrite = overwrite; ourOverwrite.Id = ourRoles.First(ro => ro.TargetRole.Id == overwrite.Id).OurRole.Id; ourCategory.AddPermissionOverwrite(ourOverwrite); } CategoryDupe dupe = new CategoryDupe { TargetCategory = category, OurCategory = ourCategory }; ourCategories.Add(dupe); Console.WriteLine($"Duplicated {category.Name}"); Thread.Sleep(50); } Console.WriteLine("Duplicating channels..."); //duplicate text channels foreach (var c in channels.TextChannels) { TextChannel channel; try { channel = client.GetTextChannel(c.Id); } catch (DiscordHttpException e) { //ofcourse you could make it return no matter what error, but this is better for debugging if (e.Code == DiscordError.MissingAccess) { continue; } else { throw; } } TextChannel ourChannel = ourGuild.CreateTextChannel(channel.Name, channel.ParentId != null ? (ulong?)ourCategories.First(ca => ca.TargetCategory.Id == channel.ParentId).OurCategory.Id : null); ourChannel.Modify(new TextChannelProperties() { Nsfw = channel.Nsfw, Position = channel.Position, Topic = channel.Topic, SlowMode = channel.SlowMode }); foreach (var overwrite in channel.PermissionOverwrites) { if (overwrite.Type == PermissionOverwriteType.Member) { continue; } PermissionOverwrite ourOverwrite = overwrite; ourOverwrite.Id = ourRoles.First(ro => ro.TargetRole.Id == overwrite.Id).OurRole.Id; ourChannel.AddPermissionOverwrite(ourOverwrite); } Console.WriteLine($"Duplicated {channel.Name}"); Thread.Sleep(50); } //duplicate voice channels foreach (var c in channels.VoiceChannels) { VoiceChannel channel; try { channel = client.GetVoiceChannel(c.Id); } catch (DiscordHttpException e) { //ofcourse you could make it return no matter what error, but this is better for debugging if (e.Code == DiscordError.MissingAccess) { continue; } else { throw; } } //create voice channels VoiceChannel ourChannel = ourGuild.CreateVoiceChannel(channel.Name, channel.ParentId != null ? (ulong?)ourCategories.First(ca => ca.TargetCategory.Id == channel.ParentId).OurCategory.Id : null); ourChannel.Modify(new VoiceChannelProperties() { Bitrate = channel.Bitrate, Position = channel.Position, UserLimit = channel.UserLimit }); foreach (var overwrite in channel.PermissionOverwrites) { if (overwrite.Type == PermissionOverwriteType.Member) { continue; } PermissionOverwrite ourOverwrite = overwrite; ourOverwrite.Id = ourRoles.First(ro => ro.TargetRole.Id == overwrite.Id).OurRole.Id; ourChannel.AddPermissionOverwrite(ourOverwrite); } Console.WriteLine($"Duplicated {channel.Name}"); Thread.Sleep(50); } }
internal BlacklistChecker(DiscordClient client) { _service = client.Services.Get<BlacklistService>(true); }
/// <summary> /// /// </summary> public static void GetGuildAuditLog(DiscordClient client, DiscordGuild guild, Action <AuditLog> callback = null) => GetGuildAuditLog(client, guild.Id, callback);
internal LogManager(DiscordClient client) { _client = client; Level = client.Config.LogLevel; }
public CommandContext(DiscordClient client, RestMessage message) { Client = client; Message = message; }
public static async Task <(bool hasInvalidInvite, List <DiscordInvite> invites)> GetInvitesAsync(this DiscordClient client, string message, bool tryMessageAsACode = false) { var inviteCodes = InviteLink.Matches(message).Select(m => m.Groups["invite_id"]?.Value).Distinct().Where(s => !string.IsNullOrEmpty(s)).ToList(); var discordMeLinks = InviteLink.Matches(message).Select(m => m.Groups["me_id"]?.Value).Distinct().Where(s => !string.IsNullOrEmpty(s)).ToList(); if (inviteCodes.Count == 0 && discordMeLinks.Count == 0 && !tryMessageAsACode) { return(false, new List <DiscordInvite>(0)); } var hasInvalidInvites = false; foreach (var meLink in discordMeLinks) { try { using (var request = new HttpRequestMessage(HttpMethod.Get, "https://discord.me/" + meLink)) { request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/html")); request.Headers.CacheControl = CacheControlHeaderValue.Parse("no-cache"); request.Headers.UserAgent.Add(new ProductInfoHeaderValue("RPCS3CompatibilityBot", "2.0")); using (var response = await HttpClient.SendAsync(request)) { var html = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (response.IsSuccessStatusCode) { if (string.IsNullOrEmpty(html)) { continue; } foreach (Match match in DiscordInviteLink.Matches(html)) { inviteCodes.Add(match.Groups["invite_id"].Value); } } else { hasInvalidInvites = true; Config.Log.Warn($"Got {response.StatusCode} from discord.me: {html}"); } } } } catch (Exception e) { Config.Log.Warn(e); } } if (tryMessageAsACode) { inviteCodes.Add(message); } inviteCodes = inviteCodes.Distinct().Where(s => !string.IsNullOrEmpty(s)).ToList(); var result = new List <DiscordInvite>(inviteCodes.Count); foreach (var inviteCode in inviteCodes) { try { if (await client.GetInviteByCodeAsync(inviteCode).ConfigureAwait(false) is DiscordInvite invite) { result.Add(invite); } } catch (Exception e) { hasInvalidInvites = true; Config.Log.Warn(e, $"Failed to get invite for code {inviteCode}"); } } return(hasInvalidInvites, result); }
private async Task ShardedClient_UpdateStatus(DiscordClient sender, ReadyEventArgs e) { this.Started = true; await this.ShardedClient.UpdateStatusAsync(new DiscordActivity("^help", ActivityType.Watching)); }
public void Install(DiscordClient client) { _client = client; }
public HelpCommand(DiscordClient BotUser, CommandService commands) : base(BotUser) { this.commands = commands; CreateCommands(); }
internal WhitelistChecker(DiscordClient client) { _service = client.Services.Get<WhitelistService>(true); }
private static void Main() { Console.OutputEncoding = Encoding.Unicode; try { File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented)); if (!File.Exists("data/config.json")) { File.Copy("data/config_example.json", "data/config.json"); } File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented)); } catch { Console.WriteLine("Failed writing credentials_example.json or data/config_example.json"); } try { Config = JsonConvert.DeserializeObject <Configuration>(File.ReadAllText("data/config.json")); } catch (Exception ex) { Console.WriteLine("Failed loading configuration."); Console.WriteLine(ex); Console.ReadKey(); return; } try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject <Credentials>(File.ReadAllText("credentials.json")); } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //if password is not entered, prompt for password if (string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine("Token blank. Please enter your bot's token:\n"); Creds.Token = Console.ReadLine(); } Console.WriteLine(Config.ForwardMessages != true ? "Not forwarding messages." : "Forwarding private messages to owner."); BotMention = $"<@{Creds.BotId}>"; //create new discord client and log Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 10, ConnectionTimeout = int.MaxValue, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => Console.WriteLine($"Severity: {e.Severity}" + $"ExceptionMessage: {e.Exception?.Message ?? "-"}" + $"Message: {e.Message}"), }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled, ErrorHandler = async(s, e) => { if (e.ErrorType != CommandErrorType.BadPermissions) { return; } if (string.IsNullOrWhiteSpace(e.Exception?.Message)) { return; } try { await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false); } catch { } } }); //add command service Client.AddService <CommandService>(commandService); //create module service var modules = Client.AddService <ModuleService>(new ModuleService()); //add audio service Client.AddService <AudioService>(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, Bitrate = 128, })); //install modules modules.Add(new HelpModule(), "Help", ModuleFilter.None); modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None); modules.Add(new UtilityModule(), "Utility", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); //run the bot Client.ExecuteAndWait(async() => { await Task.Run(() => { Console.WriteLine("Specific config started initializing."); var x = SpecificConfigurations.Default; Console.WriteLine("Specific config done initializing."); }); await PermissionsHandler.Initialize(); try { await Client.Connect(Creds.Token, TokenType.Bot).ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account."); Console.WriteLine(ex); Console.ReadKey(); return; } #if NADEKO_RELEASE await Task.Delay(300000).ConfigureAwait(false); #else await Task.Delay(1000).ConfigureAwait(false); #endif Console.WriteLine("-----------------"); Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false)); Console.WriteLine("-----------------"); OwnerPrivateChannels = new List <Channel>(Creds.OwnerIds.Length); foreach (var id in Creds.OwnerIds) { try { OwnerPrivateChannels.Add(await Client.CreatePrivateChannel(id).ConfigureAwait(false)); } catch { Console.WriteLine($"Failed creating private channel with the owner {id} listed in credentials.json"); } } Client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) { return; } // meew0 is magic request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_"; if (string.IsNullOrWhiteSpace(request.Content)) { e.Cancel = true; } }; #if NADEKO_RELEASE Client.ClientAPI.SentRequest += (s, e) => { Console.WriteLine($"[Request of type {e.Request.GetType()} sent in {e.Milliseconds}]"); var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) { return; } Console.WriteLine($"[Content: { request.Content }"); }; #endif NadekoBot.Ready = true; NadekoBot.OnReady(); Console.WriteLine("Ready!"); //reply to personal messages and forward if enabled. Client.MessageReceived += Client_MessageReceived; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
public Tars() { client = new DiscordClient(); timer = new Timer(UpdateGameTimer, client, 3000, 14400000); commands = new Dictionary <string, Func <CommandArgs, Task> >(); Commands.Init(commands); client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); client.MessageReceived += async(s, e) => { if (e.Channel.IsPrivate) { CommandArgs dm = new CommandArgs(e); if (dm.Message.RawText.ToLower() == "tars help") { await e.Channel.SendMessage(Util.GetInfo()); } else { ulong id = 0; if (dm.Args.Count() >= 2 && dm.Message.RawText.ToLower().StartsWith("tars getprefix") && ulong.TryParse(dm.Args.ElementAt(1), out id)) { await e.Channel.SendMessage("That server's prefix is: `" + DataBase.GetServerPrefix(id) + "`"); } } return; } Console.WriteLine("[{0}] [{1}] [{2}]: {3}", e.Server.Name, e.Channel.Name, e.User.Name, e.Message.Text); if (e.Message.IsAuthor) { return; } if (e.Message.IsMentioningMe() && DataBase.IsUniqueUser(e.User.Id)) { await e.Channel.SendMessage(e.User.Mention + " " + Util.GetRandomHump()); return; } if (e.Message.RawText.ToLower().Contains("so i guess it's a") || e.Message.RawText.ToLower().Contains("so i suppose it's a")) { await e.Channel.SendFile("images/ADate.jpg"); return; } if (e.Message.RawText.ToLower().Equals("ayy")) { await e.Channel.SendMessage("lmao"); return; } if (e.Message.RawText.ToLower().StartsWith("present new changes")) { await e.Channel.SendMessage("In your lame life nothing has changed.\nAnd it's even sadder when you realize " + e.User.Mention + " made me say it."); return; } if (e.Message.RawText.ToLower().Equals("tars help")) { string currentPrefix = DataBase.GetServerPrefix(e.Server.Id); if (currentPrefix.ToLower() != "tars") { await e.Channel.SendMessage("TARS' prefix for this server is: `" + currentPrefix + "`\nUse `" + currentPrefix + " info`"); return; } } prefix = DataBase.GetServerPrefix(e.Server.Id).Trim().ToLower(); if (!e.Message.RawText.ToLower().StartsWith(prefix)) { return; } var trigger = string.Join("", e.Message.RawText.Substring(prefix.Length + 1).TakeWhile(c => c != ' ')); if (!commands.ContainsKey(trigger.ToLower())) { await e.Channel.SendMessage(Util.GetRandomGrump()); return; } await commands[trigger.ToLower()](new CommandArgs(e)); }; client.JoinedServer += async(s, e) => { await e.Server.DefaultChannel.SendMessage("Hello, I'm TARS, made by <@96550262403010560>, and I'm ready to rule the universe. ∞"); }; client.ExecuteAndWait(async() => { await client.Connect(ConstData.loginToken, TokenType.Bot); }); }
public MessageEvents(DiscordClient dClient, BotContextFactory dbFactory) { this.dClient = dClient; this.dbFactory = dbFactory; }
/// <summary> /// /// </summary> public static void GetGuildAuditLog(DiscordClient client, Snowflake guildId, Action <AuditLog> callback = null, Action <RestError> error = null) { client.Bot.Rest.DoRequest($"/guilds/{guildId}/audit-logs", RequestMethod.GET, null, callback, error); }
void IService.Install(DiscordClient client) { Client = client; Config.Lock(); if (Config.EnableMultiserver) _voiceClients = new ConcurrentDictionary<ulong, IAudioClient>(); else { var logger = Client.Log.CreateLogger("Voice"); _defaultClient = new SimpleAudioClient(this, 0, logger); } _talkingUsers = new ConcurrentDictionary<User, bool>(); client.Disconnected += async (s, e) => { if (Config.EnableMultiserver) { var tasks = _voiceClients .Select(x => x.Value.Disconnect()) .ToArray(); await Task.WhenAll(tasks).ConfigureAwait(false); _voiceClients.Clear(); } foreach (var member in _talkingUsers) { bool ignored; if (_talkingUsers.TryRemove(member.Key, out ignored)) OnUserIsSpeakingUpdated(member.Key, false); } }; }