public CommandArgs(SocketMessage Message, Command Command, string CommandText, string ArgText, int? Permssions, string[] Args) { this.Message = Message; this.Command = Command; this.CommandText = CommandText; this.ArgText = ArgText; this.Permssions = Permssions; this.Args = Args; }
/// <summary> /// When a message has been received, call a couple functions which /// controls the ayy channel, the YouTube command which needs to be global. /// (So that I can easily add it wiht multiple commands) /// And it controls the regular users so that messages get added and blahblah. /// </summary> public static async Task MessageReceivedAsync(SocketMessage message) { await Modules.Games.AyyGame.GameAsync(message); await Modules.YouTube.ReceivedMessageAsync(message); await qtbot.Modules.MultipleSelector.MultiSelectorController.ReceivedMessageAsync(message); if ((message.Channel as ITextChannel) != null) return; if (Tools.GetServerInfo((message.Channel as IGuildChannel).Guild.Id).RegularUsersEnabled) await Modules.RegularUsers.ReceivedMessageAsync(message); }
public void Chat(String text) { SocketMessage sm = new SocketMessage("LOBCHAT"); text = text.Trim(); try { if (text.ToLower().Substring(0, 3).Equals("/r ")) text = "/w " + strLastWhisperFrom + " " + text.Substring(3); } catch (Exception e) { } sm.Arguments.Add(text); writeMessage(sm); }
public static async Task GameAsync(SocketMessage e) { if (e.Channel.Id == 134267667245694976 && Storage.ayyscore > 0) { try { string msg = e.Content; if (msg[0] == '/') msg = msg.Substring(1); if (!msg.ToLower().Replace(" ", "").EndsWith("ayy")) { var info = Tools.GetServerInfo((e.Channel as ITextChannel).GuildId); string text = "get as long a chain of /ayy 's before it gets broken. High Score: {0} Current Score: {1}"; var oldayy = Storage.ayyscore; bool newHighScore = Storage.ayyscore > info.ayyHighScore; info.ayyScore = oldayy; Storage.ayyscore = 0; await Tools.ReplyAsync(e.Author, e.Channel, $"You failed! The chain has been broken. The score was: {oldayy}", true); if(newHighScore) { info.ayyHighScore = oldayy; string date = Tools.CalculateTime((int)(DateTime.Now - info.ayyScoreDateReached).TotalMinutes); info.ayyScoreDateReached = DateTime.Now; await Tools.ReplyAsync(e.Author, e.Channel, $"A new high score has been reached after {date}. The new highscore is {oldayy}", false); } await (e.Channel as ITextChannel)?.ModifyAsync(x => { x.Topic = String.Format(text, info.ayyScore, Storage.ayyscore); }); } } catch (Exception) { } } }
/// <summary> /// Called when the server sends data that isn't intercepted by the Socket Client class. /// </summary> /// <param name="input">Data sent from the server as a String</param> public abstract void handleInput(SocketMessage input);
/// <summary> /// Message received /// </summary> /// <param name="sm">Socket Message received</param> public abstract void OnMessageReceived(SocketMessage sm);
public static async Task MessageRecieved(SocketMessage arg) { MessageEventHandler.MessageRecieved(arg, false); }
public async Task ToggleSpam(SocketMessage msg, string[] args) { State.SpammerEnabled = !State.SpammerEnabled; File.WriteAllText("state.data", JsonConvert.SerializeObject(State)); await msg.Channel.SendMessageAsync("Spam has been toggled to " + State.SpammerEnabled); }
public async Task Reload(SocketMessage msg, string[] args) { bot.UpdateConfiguration("config.json"); await msg.Channel.SendMessageAsync("Configuration reloaded."); }
public Input(SocketMessage message, Match match) { Message = message; Match = match; }
protected override void OnEventNotification(SocketMessage message) { }
public async Task HandleCommandAsync(SocketMessage messageParam) { // Don't process the command if it was a system message var message = messageParam as SocketUserMessage; if (message == null) { return; } // Create a WebSocket-based command context based on the message var context = new SocketCommandContext(_client, message); guildData d = MongoUtil.getGuildData(context.Guild.Id); // Create a number to track where the prefix ends and the command begins int argPos = Backbone.DEFAULT_PREFIX.Length; string p = Backbone.DEFAULT_PREFIX; if (d != null) { //Command argPos = d.prefix.Length; p = d.prefix; } // Determine if the message is a command based on the prefix and make sure no bots trigger commands if (!(message.HasStringPrefix(p, ref argPos) || message.HasMentionPrefix(_client.CurrentUser, ref argPos)) || message.Author.IsBot) { //Automod /** * Check if Automod is enabled, * the current channel is not meant to be ignored, * and then if the message is blacklisted */ if (d.automodEnabled && !d.ignoredChannelIds.Contains(context.Channel.Id) && d.illegalMsg(message.Content)) { await message.DeleteAsync(); return; } return; } else { Console.WriteLine($"Command Received: {message.Content}"); } // Execute the command with the command context we just // created, along with the service provider for precondition checks. // Keep in mind that result does not indicate a return value // rather an object stating if the command executed successfully. var result = await _commands.ExecuteAsync( context : context, argPos : argPos, services : null); // Optionally, we may inform the user if the command fails // to be executed; however, this may not always be desired, // as it may clog up the request queue should a user spam a // command. if (!result.IsSuccess) { await context.Channel.SendMessageAsync($"An error ocurred: ```{result.ErrorReason}```\nPlease report this at" + @"`https://github.com/Bytestorm1/OpenUtil/issues`" + "with screenshots if possible."); } }
public bool CanExecute(SocketMessage message) { var botId = UserIds.BadgerBot; return(message.Content.Contains($"hugs <@{botId}>")); }
public async Task Execute(SocketMessage message) { await message.Channel.SendMessageAsync("BadgerBot doesn't care. BadgerBot tears out " + message.Author.Mention + "s hair."); }
private async Task MessageReceivedAsync(SocketMessage message) { if (message.Author.Id == client.CurrentUser.Id) { return; } if (message.Content == "/create") { await Create(message); } if (message.Content == "/import") { await Import(message); } if (message.Content == "/balance") { await Balance(message); } if (message.Content == "/token") { await TokenBalance(message); } if (message.Content == "/help") { await Help(message); } if (message.Content.Contains("/send")) { await Send(message); } if (message.Content.Contains("/symbols")) { await Symbols(message); } if (message.Content.Contains("/orders")) { await Orders(message); } if (message.Content.Contains("/sell_order")) { await SellOrder(message); } if (message.Content.Contains("/buy_order")) { await BuyOrder(message); } if (message.Content.Contains("/address")) { await Address(message); } }
// /send token amount (address or nickname, or ENS) - *Send a crypto* private async Task Send(SocketMessage message) { var args = message.Content.Split(' '); var token = args[1]; var amount = args[2]; var destination = args[3]; var author = await accountService.ReadUser(message.Author.Id); var(_, type) = NickConverter.Convert(destination); if (type == TransactionDestination.Nick) { var dest = await accountService.ReadUser(destination); var trData = new TransactionData { Currency = token.ToUpperInvariant(), From = GetAddress(token, author), To = GetAddress(token, dest), Value = amount }; var guid = await guidService.GenerateString(author.Identifier, author.NickName, trData); var url = GetSendUrl(token, guid); await message.Channel.SendMessageAsync(url); } if (type == TransactionDestination.Wallet) { var trData = new TransactionData { Currency = token.ToUpperInvariant(), From = GetAddress(token, author), To = destination, Value = amount }; var guid = await guidService.GenerateString(author.Identifier, author.NickName, trData); var url = GetSendUrl(token, guid); await message.Channel.SendMessageAsync(url); } if (type == TransactionDestination.ENS) { var dest = await balanceService.GetEnc(destination); var trData = new TransactionData { Currency = "ETH", From = GetAddress(token, author), To = dest, Value = amount }; var guid = await guidService.GenerateString(author.Identifier, author.NickName, trData); var url = GetSendUrl(token, guid); await message.Channel.SendMessageAsync(url); } }
// Method to execute on recieveing a message private async Task MessageRecievedAsync(SocketMessage m) { // return if it's not a message sent by valid user if (!(m is SocketUserMessage msg)) { return; } // Don't respond to other bots and webhooks if (msg.Author.IsBot) { return; } if (msg.Author.IsWebhook) { return; } // Also don't respond to self if (msg.Author.Id == _client.CurrentUser.Id) { return; } // message is private message if (msg.Channel is Discord.IPrivateChannel) { var kas = _client.Guilds.FirstOrDefault().Users.Single(x => x.Id == 333769079569776642); var builder = new EmbedBuilder(); builder.WithAuthor(msg.Author); builder.WithDescription(msg.Content); if (msg.Attachments.Count > 0) { using (var client = new HttpClient()){ // get enumerator of attachments list var enumerator = msg.Attachments.GetEnumerator(); Stream attachment; string fName; // execute as long as there are items in the list while (enumerator.MoveNext()) { // get filename of the attachment fName = enumerator.Current.Filename; // only image attachments can be downloaded, other throw 404 error // if attachment isn't an image just display name, size // and id of original message if (!enumerator.Current.Width.HasValue && !enumerator.Current.Height.HasValue) { await kas.SendMessageAsync($"ID: {msg.Id}, type: binary\nname: {fName}\nsize: {enumerator.Current.Size} bytes"); } // if attachment is image download it and resend it as new else { attachment = await client.GetStreamAsync(enumerator.Current.ProxyUrl); await kas.SendFileAsync(attachment, fName, $"ID: {msg.Id}, type: image"); } } } } await kas.SendMessageAsync("", false, builder.Build()); return; } // Create new command context // it provides all relevant info about user that has sent the message and the channel it was sent in var context = new SocketCommandContext(_client, msg); // define at which position command prefix is at int argPos = 0; // return if message doesn't have a command prefix (bot can also be mentioned instead of of using prefix) if (msg.HasStringPrefix(_config[context.Guild.Id].Prefix, ref argPos) || msg.HasMentionPrefix(_client.CurrentUser, ref argPos)) { // find correct module and execute the command // get back a result of executed command var result = await _commands.ExecuteAsync(context, argPos, _services); // if the result isn't a success respond to user if (!result.IsSuccess) { await context.Channel.SendMessageAsync(result.ToString()); } } }
/// <summary> /// Reads data from the socket. Handles fragmented data and data fracturing. /// </summary> /// <returns>SocketMessage with data recieved, or a SocketMessage with .Empty being true on no message.</returns> private SocketMessage readSocket() { String strBuff = ""; String strTemp; int intTimeoutCount = 0; Boolean bDone = false; SocketReadState sr = SocketReadState.WaitingForStart; System.Text.Encoding enc = System.Text.Encoding.ASCII; byte[] bb; while (!bDone) { bb = new byte[256]; try { //sock.Receive(bb); sock.Receive(bb, 256, SocketFlags.None); } catch (System.Net.Sockets.SocketException se) { if (se.SocketErrorCode == SocketError.TimedOut) { if (!strBuff.Equals("")) { intTimeoutCount++; if (intTimeoutCount == 10) { Close("readSocket timed out in the middle of a message", false); return new SocketMessage(); } else { try { Thread.Sleep(100); } catch (Exception e) { // TODO handle this exception I suppose. } continue; } } else { writeMessage(new PingMessage()); return new SocketMessage(); } } else { Close("Socket error: " + se.ErrorCode.ToString() + " : " + se.Message, false); return new SocketMessage(); } } catch (Exception e) { return new SocketMessage(); } try { strTemp = enc.GetString(bb, 0, Array.IndexOf(bb, (byte)0)); } catch (Exception e) { strTemp = ""; } if (strTemp.Equals("")) return new SocketMessage(); intLastPing = 0; foreach(char c in strTemp) { switch (sr) { case SocketReadState.WaitingForStart: if (c == 2) { sr = SocketReadState.Reading; continue; } else if (c == 1) { return new SocketMessage(); } else if (c == 6) { Close("Remote Host requested close.", false); return new SocketMessage(); } break; case SocketReadState.Reading: if (c != 5) strBuff += c; else { sr = SocketReadState.Ended; continue; } break; } } if (sr == SocketReadState.Ended) { sr = SocketReadState.inHeader; SocketMessage sm = new SocketMessage(); strTemp = ""; foreach (char c in strBuff) { if (sr == SocketReadState.inHeader) { if (c != 3) { strTemp += c; continue; } else { sm.Header = strTemp; strTemp = ""; sr = SocketReadState.inArgument; continue; } } else if (sr == SocketReadState.inArgument) { if (c != 4) { strTemp += c; continue; } else { sm.Arguments.Add(strTemp); strTemp = ""; continue; } } } if (!strTemp.Trim().Equals("")) { if (sr == SocketReadState.inHeader) sm.Header = strTemp; else if (sr == SocketReadState.inArgument) sm.Arguments.Add(strTemp); } return sm; } } return new SocketMessage(); }
private void SendToClient(Socket client, String sMsg, int MessageType) { if (client.Poll(10, SelectMode.SelectWrite)) { SocketMessage sm = new SocketMessage(); sm.MessageType = MessageType; sm.Message = sMsg; sm.Client = clientPool[client]; sm.Time = DateTime.Now; byte[] byteMsg = PackageServerData(sm); if (client.Connected) client.Send(byteMsg, byteMsg.Length, SocketFlags.None); } }
private async Task ResolveCommand(SocketMessage message, BotInstance instance) { ch.Handle(message, instance); }
private async Task OnMessage(SocketMessage msg) { if (msg.Content.StartsWith(Configuration.UserbotPrefix) && msg.Author.Id == Configuration.OwnerID) { var args = msg.Content.Split(' ').ToList(); var command = args[0].Substring(Configuration.UserbotPrefix.Length); args.RemoveAt(0); if (command == "status") { var props = typeof(State).GetProperties(); await msg.Channel.SendMessageAsync($"```{String.Join('\n', props.Select(x => $"{x.Name}: {x.GetValue(State)}"))}```"); } if (command == "reload") { Configuration = JsonConvert.DeserializeObject <Configuration>(File.ReadAllText("config.json")); await msg.Channel.SendMessageAsync("Configuration reloaded."); } if (command == "toggleguilds") { State.WhitelistGuilds = !State.WhitelistGuilds; await msg.Channel.SendMessageAsync("Whitelisting of guilds has been toggled to " + State.WhitelistGuilds); File.WriteAllText("state.data", JsonConvert.SerializeObject(State)); } if (command == "togglepokemon") { State.WhitelistPokemon = !State.WhitelistPokemon; await msg.Channel.SendMessageAsync("Whitelisting of pokemon has been toggled to " + State.WhitelistPokemon); File.WriteAllText("state.data", JsonConvert.SerializeObject(State)); } if (command == "echo") { await msg.Channel.SendMessageAsync(String.Join(' ', args)); } return; } var guild = ((SocketGuildChannel)msg.Channel).Guild; if (State.WhitelistGuilds && !Configuration.WhitelistedGuilds.Contains(guild.Id)) { return; } if (msg.Author.Id != POKECORD_ID || msg.Embeds?.Count == 0) { return; } Embed embed = msg.Embeds.First(); if (embed.Description?.Contains(Configuration.PokecordPrefix + "catch") != true || !embed.Image.HasValue) { return; } Console.WriteLine("Detected pokemon, catching..."); var watch = System.Diagnostics.Stopwatch.StartNew(); string name = pokemon.GetPokemon(await http.GetStreamAsync(embed.Image.Value.Url)); watch.Stop(); Console.WriteLine($"Found pokemon in {watch.ElapsedMilliseconds}ms"); if (State.WhitelistPokemon && !Configuration.WhitelistedPokemon.Any(x => x.Equals(name, StringComparison.OrdinalIgnoreCase))) { Console.WriteLine("Pokemon is not whitelisted, ignoring."); Logger.Log($"Ignored a {name} in #{msg.Channel.Name} ({guild.Name})"); return; } var resp = await responseGrabber.SendMessageAndGrabResponse( (ITextChannel)msg.Channel, $"{Configuration.PokecordPrefix}catch {name}", x => x.Channel.Id == msg.Channel.Id && x.Author.Id == POKECORD_ID && x.MentionedUsers.Any(y => y.Id == Client.CurrentUser.Id) && x.Content.StartsWith("Congratulations"), 5 ); Console.WriteLine(resp == null ? "The Pokecord bot did not respond, catch was a fail." : "Catch confirmed by the Pokecord bot."); if (resp != null) { if (Configuration.EnableCatchResponse) { await msg.Channel.SendMessageAsync(Configuration.CatchResponse); } Logger.Log($"Caught a {name} in #{resp.Channel.Name} ({guild.Name})"); } else { Logger.Log($"Failed to catch {name} in #{msg.Channel.Name} ({guild.Name})"); } Console.WriteLine(); }
private async Task HandleCommandAsync(SocketMessage message) { var msg = message as SocketUserMessage; if (msg == null) { return; } if (msg.Author.IsBot || msg.Author.IsWebhook) { return; } string prefix = _config.Get().Prefix; var context = new SocketCommandContext(_client, msg); if (context.Guild != null) { using (var db = new Database.GuildConfigContext(_config)) { var gConfig = await db.GetCachedGuildFullConfigAsync(context.Guild.Id); if (gConfig?.Prefix != null) { prefix = gConfig.Prefix; } } } int argPos = 0; if (msg.HasStringPrefix(prefix, ref argPos, StringComparison.OrdinalIgnoreCase)) { if (_config.Get().BlacklistedGuilds.Any(x => x == (context.Guild?.Id ?? 0))) { return; } var res = await _cmd.GetExecutableCommandAsync(context, argPos, _provider); if (res.IsSuccess()) { _logger.Log($"Run cmd: u{msg.Author.Id} {res.Command.Match.Command.Name}"); using (var dbc = new Database.AnalyticsContext(_config)) { string param = null; try { var paramStart = argPos + res.Command.Match.Command.Name.Length; var textBigger = context.Message.Content.Length > paramStart; param = textBigger ? context.Message.Content.Substring(paramStart) : null; } catch (Exception) { } dbc.CommandsData.Add(new CommandsAnalytics() { CmdName = res.Command.Match.Command.Name, GuildId = context.Guild?.Id ?? 0, UserId = context.User.Id, Date = DateTime.Now, CmdParams = param, }); await dbc.SaveChangesAsync(); } switch (res.Command.Match.Command.RunMode) { case RunMode.Async: await res.Command.ExecuteAsync(_provider); break; default: case RunMode.Sync: if (!await _executor.TryAdd(res.Command, TimeSpan.FromSeconds(1))) { await context.Channel.SendMessageAsync("", embed : "Przekroczono czas oczekiwania!".ToEmbedMessage(EMType.Error).Build()); } break; } } else { await ProcessResultAsync(res.Result, context, argPos, prefix); } } }
public async Task Status(SocketMessage msg, string[] args) { var props = typeof(State).GetProperties(); await msg.Channel.SendMessageAsync($"```{String.Join('\n', props.Select(x => $"{x.Name}: {x.GetValue(State)}"))}```"); }
private async Task MessageReceived(SocketMessage msg) { try { if (msg.Author.IsBot || !(msg is SocketUserMessage message)) { return; } var argPos = 0; var prefixes = new List <string>(_configuration.BotPrefixes); Server server = null; ExecutionObject executionObj; if (message.Channel is ITextChannel channel) { var guild = channel.Guild; _database.Execute(x => { server = x.Load <Server>($"{guild.Id}") ?? new Server(); }); switch (server.BlockingType) { case BlockingType.Whitelist when !server.Whitelist.Contains(channel.Id): case BlockingType.Blacklist when server.Blacklist.Contains(channel.Id): return; case BlockingType.None: break; } prefixes.AddRange(server.Prefixes); executionObj = new ExecutionObject { Server = server }; } else { executionObj = new ExecutionObject(); } if (message.HasMentionPrefix(_client.CurrentUser, ref argPos) || prefixes.Any(x => message.HasStringPrefix(x, ref argPos, StringComparison.OrdinalIgnoreCase))) { var context = new ShardedCommandContext(_client, message); var parameters = message.Content.Substring(argPos).TrimStart('\n', ' '); _services.GetService <CachingService>().ExecutionObjects[message.Id] = executionObj; var result = await _commands.ExecuteAsync(context, parameters, _services, MultiMatchHandling.Best); if (!result.IsSuccess) { await HandleErrorAsync(result, context, parameters, server); } } } catch (Exception e) { Console.WriteLine(e); throw; } }
public async Task TogglePokemon(SocketMessage msg, string[] args) { State.WhitelistPokemon = !State.WhitelistPokemon; File.WriteAllText("state.data", JsonConvert.SerializeObject(State)); await msg.Channel.SendMessageAsync("Whitelisting of pokemon has been toggled to " + State.WhitelistPokemon); }
private async Task <bool> HasBypassAuthority(SocketMessage message) { return(await _bypassCheck.HasBypassAuthority(message, FilterType.Profanity)); }
public static async Task MessageRecieved(SocketMessage parameterMessage, bool edited = false) { // Don't handle the command if it is a system message var message = parameterMessage; if (GenericBot.GlobalConfiguration.BlacklistedIds.Contains(message.Author.Id)) { return; } if (parameterMessage.Author.Id == GenericBot.DiscordClient.CurrentUser.Id) { return; } if (parameterMessage.Channel.GetType().FullName.ToLower().Contains("dmchannel")) { var msg = GenericBot.DiscordClient.GetApplicationInfoAsync().Result.Owner.GetOrCreateDMChannelAsync().Result .SendMessageAsync($"```\nDM from: {message.Author}({message.Author.Id})\nContent: {message.Content}\n```").Result; if (parameterMessage.Content.Trim().Split().Length == 1) { var guild = VerificationEngine.GetGuildFromCode(parameterMessage.Content, message.Author.Id); if (guild == null) { await message.ReplyAsync("Invalid verification code"); } else { await guild.GetUser(message.Author.Id) .AddRoleAsync(guild.GetRole(GenericBot.GuildConfigs[guild.Id].VerifiedRole)); if (guild.TextChannels.HasElement(c => c.Id == (GenericBot.GuildConfigs[guild.Id].UserLogChannelId), out SocketTextChannel logChannel)) { logChannel.SendMessageAsync($"`{DateTime.UtcNow.ToString(@"yyyy-MM-dd HH:mm tt")}`: `{message.Author}` (`{message.Author.Id}`) just verified"); } await message.ReplyAsync($"You've been verified on **{guild.Name}**!"); await msg.ModifyAsync(m => m.Content = $"```\nDM from: {message.Author}({message.Author.Id})\nContent: {message.Content.SafeSubstring(1900)}\nVerified on {guild.Name}\n```"); } } } var guildDb = new DBGuild(message.GetGuild().Id); if (guildDb.Users.Any(u => u.ID.Equals(message.Author.Id))) // if already exists { guildDb.Users.Find(u => u.ID.Equals(message.Author.Id)).AddUsername(message.Author.Username); guildDb.Users.Find(u => u.ID.Equals(message.Author.Id)).AddNickname(message.Author as SocketGuildUser); } else { guildDb.Users.Add(new DBUser(message.Author as SocketGuildUser)); } guildDb.Save(); if (!edited) { //new GuildMessageStats(parameterMessage.GetGuild().Id).AddMessage(parameterMessage.Author.Id).Save(); } if (parameterMessage.Author.Id != GenericBot.DiscordClient.CurrentUser.Id && GenericBot.GuildConfigs[parameterMessage.GetGuild().Id].FourChannelId == parameterMessage.Channel.Id) { await parameterMessage.DeleteAsync(); await parameterMessage.ReplyAsync( $"**[Anonymous]** {string.Format("{0:yyyy-MM-dd HH\\:mm\\:ss}", DateTimeOffset.UtcNow)}\n{parameterMessage.Content}"); } System.Threading.Thread pointThread = new System.Threading.Thread(() => { try { lock (message.GetGuild().Id.ToString()) { DBGuild db = new DBGuild(message.GetGuild().Id); if (db.Users == null) { return; } if (!edited) { db.GetUser(message.Author.Id).PointsCount += (decimal)(.01); if (GenericBot.GuildConfigs[message.GetGuild().Id].Levels.Any(kvp => kvp.Key <= db.GetUser(message.Author.Id).PointsCount)) { foreach (var level in GenericBot.GuildConfigs[message.GetGuild().Id].Levels .Where(kvp => kvp.Key <= db.GetUser(message.Author.Id).PointsCount) .Where(kvp => !(message.Author as SocketGuildUser).Roles.Any(r => r.Id.Equals(kvp.Value)))) { (message.Author as SocketGuildUser).AddRoleAsync(message.GetGuild().GetRole(level.Value)); } } } var thanksRegex = new Regex(@"(\b)((thanks?)|(thx)|(ty))(\b)", RegexOptions.IgnoreCase); if (thanksRegex.IsMatch(message.Content) && GenericBot.GuildConfigs[message.GetGuild().Id].PointsEnabled && message.MentionedUsers.Any()) { if (new DBGuild(message.GetGuild().Id).GetUser(message.Author.Id).LastThanks.AddMinutes(1) < DateTimeOffset.UtcNow) { List <IUser> givenUsers = new List <IUser>(); foreach (var user in message.MentionedUsers) { if (user.Id == message.Author.Id) { continue; } db.GetUser(user.Id).PointsCount++; givenUsers.Add(user); } if (givenUsers.Any()) { message.ReplyAsync($"{givenUsers.Select(us => $"**{(us as SocketGuildUser).GetDisplayName()}**").ToList().SumAnd()} recieved a {GenericBot.GuildConfigs[message.GetGuild().Id].PointsName} of thanks from **{(message.Author as SocketGuildUser).GetDisplayName()}**"); db.GetUser(message.Author.Id).LastThanks = DateTimeOffset.UtcNow; } else { message.ReplyAsync("You can't give yourself a point!"); } } } db.Save(); } } catch (Exception ex) { //GenericBot.Logger.LogErrorMessage($"{ex.Message}\nGuild:{message.GetGuild().Name} | {message.GetGuild().Id}\nChannel:{message.Channel.Name} | {message.Channel.Id}\nUser:{message.Author} | {message.Author.Id}\n{message.Content}"); } }); pointThread.IsBackground = true; pointThread.Start(); GenericBot.QuickWatch.Restart(); try { var commandInfo = CommandHandler.ParseMessage(parameterMessage); CustomCommand custom = new CustomCommand(); if (parameterMessage.Channel is IDMChannel) { goto DMChannel; } if (parameterMessage.MentionedUsers.Contains(GenericBot.DiscordClient.CurrentUser) && parameterMessage.Content.ToLower().Contains("prefix")) { string pref = GenericBot.GlobalConfiguration.DefaultPrefix; if (!String.IsNullOrEmpty(GenericBot.GuildConfigs[(parameterMessage.Channel as SocketGuildChannel).Guild.Id].Prefix)) { pref = GenericBot.GuildConfigs[(parameterMessage.Channel as SocketGuildChannel).Guild.Id].Prefix; } await parameterMessage.ReplyAsync($"Try `{pref}`!"); } if (GenericBot.GuildConfigs[parameterMessage.GetGuild().Id].CustomCommands .HasElement(c => c.Name == commandInfo.Name, out custom) || GenericBot.GuildConfigs[parameterMessage.GetGuild().Id].CustomCommands .HasElement(c => c.Aliases.Any(a => a.Equals(commandInfo.Name)), out custom)) { if (custom.Delete) { await parameterMessage.DeleteAsync(); } await parameterMessage.ReplyAsync(custom.Response); //new GuildMessageStats(parameterMessage.GetGuild().Id).AddCommand(parameterMessage.Author.Id, custom.Name).Save(); } DMChannel: GenericBot.LastCommand = commandInfo; commandInfo.Command.ExecuteCommand(GenericBot.DiscordClient, message, commandInfo.Parameters).FireAndForget(); GenericBot.Logger.LogGenericMessage($"Guild: {parameterMessage.GetGuild().Name} ({parameterMessage.GetGuild().Id}) Channel: {parameterMessage.Channel.Name} ({parameterMessage.Channel.Id}) User: {parameterMessage.Author} ({parameterMessage.Author.Id}) Command: {commandInfo.Command.Name} Parameters {JsonConvert.SerializeObject(commandInfo.Parameters)}"); //new GuildMessageStats(parameterMessage.GetGuild().Id).AddCommand(parameterMessage.Author.Id, commandInfo.Command.Name).Save(); } catch (NullReferenceException nullRefEx) { } catch (Exception ex) { if (parameterMessage.Author.Id == GenericBot.GlobalConfiguration.OwnerId) { await parameterMessage.ReplyAsync("```\n" + $"{ex.Message}\n{ex.StackTrace}".SafeSubstring(1000) + "\n```"); } await GenericBot.Logger.LogErrorMessage(ex.Message); //else Console.WriteLine($"{ex.Message}\n{ex.StackTrace}"); } }
public async Task Echo(SocketMessage msg, string[] args) => await msg.Channel.SendMessageAsync(String.Join(' ', args));
private static async Task _client_MessageUpdated(Cacheable <IMessage, ulong> arg1, SocketMessage arg2, ISocketMessageChannel arg3) { if (!(arg3 is SocketGuildChannel channel)) { return; } Server server = await DatabaseQueries.GetOrCreateServerAsync(channel.Guild.Id); if (server.LogUpdatedMessages == 0) { return; } if (!arg1.HasValue) { return; } IMessage oldMsg = arg1.Value; if (oldMsg.Author.IsBot) { return; } string content = oldMsg.Content; if (content == arg2.Content) { return; } if (string.IsNullOrEmpty(content)) { content = "<No previous text>"; } var sb = new StringBuilder($"📝 `[{GetFormattedTimestamp()}]` `ID: {oldMsg.Author.Id}` "); sb.Append($"Message updated. Author: **{oldMsg.Author}**. Channel: **{((SocketTextChannel) oldMsg.Channel).Mention}**."); if (server.IsPremium) { string arg2Content = arg2.Content.IsNullOrEmpty() ? "<No content>" : arg2.Content; sb.AppendLine($"\nOld Content:\n\"**{content}**\""); sb.Append($"New Content:\n\"**{arg2Content}**\""); } string msg = sb.ToString(); try { await _client.GetGuild(server.ServerId).GetTextChannel(server.LogUpdatedMessages).SendMessageAsync(msg); } catch (Exception) { await ConsoleLogger.LogAsync($"Failed to send message updated log to channel {server.LogUpdatedMessages} " + $"in guild {server.ServerId}. Resetting this log channel to 0 so it " + "doesn't happen again!", LogLvl.WARN); server.LogUpdatedMessages = 0; await DatabaseQueries.UpdateAsync(server); } }
public async Task Display(SocketMessage msg, string[] args) => await msg.Channel.SendMessageAsync($"{Configuration.PokecordPrefix}pokemon --name {String.Join(' ', args)}");
/// <summary> /// Send a SocketMessage. /// </summary> /// <param name="message">Message to send.</param> public void WriteMessage(SocketMessage message) { lock (SocketLocker) { if(message.Header.ToLower() != "ping") Debug.WriteLine("Writing message({0}):", message.Header,message.Data); byte[] data = SocketMessage.Serialize(message); byte[] messagesize = BitConverter.GetBytes(data.LongLength); try { Sock.Client.Send(messagesize); Sock.Client.Send(data); Sock.GetStream().Flush(); } catch (SocketException se) { if (se.ErrorCode == 10058) return; DelegateQueue.Enqueue(()=>Close(DisconnectReason.RemoteHostDropped)); } catch (ObjectDisposedException) { DelegateQueue.Enqueue(()=>Close(DisconnectReason.RemoteHostDropped)); } catch (NullReferenceException) { } catch (Exception) { if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); } } }
public async Task DisplayAll(SocketMessage msg, string[] args) => await msg.Channel.SendMessageAsync($"{Configuration.PokecordPrefix}pokemon");
/// <summary> /// Sends a message to the remote socket. /// </summary> /// <param name="sm">SocketMessage to be sent.</param> /// <returns>true on success, false on error. Note: Success just means that the message has been sent, it doesn't verifiy it was recieved.</returns> public Boolean writeMessage(SocketMessage sm) { try { sock.Send(Encoding.ASCII.GetBytes(sm.getMessage())); return true; } catch (SocketException se) { handleError(se.SocketErrorCode + " : " + se.Message); } catch (Exception ioe) { handleError(ioe.Message); } return false; }
public async Task Details(SocketMessage msg, string[] args) => await msg.Channel.SendMessageAsync($"{Configuration.PokecordPrefix}detailed");
/// <summary> /// 打包客户端信息 /// </summary> /// <param name="sm"></param> /// <returns></returns> private byte[] PackageServerData(SocketMessage sm) { StringBuilder msg = new StringBuilder(); String sMsg = sm.Message; String[] splitString = sMsg.Split('&'); if (sm.MessageType == MSGTALK || sm.MessageType == MSGALL) { msg.AppendFormat("chat\r\n{0} {1}\r\n{2}\r\n", splitString[0], sm.Time.ToShortTimeString(), sm.MessageType); msg.Append(splitString[1]); } else if (sm.MessageType == MSGLOGIN) { String sName = splitString[1]; msg.AppendFormat("login\r\n{0}", sName); } else if (sm.MessageType == MSGLOGOUT) { String sName = splitString[1]; msg.AppendFormat("logout\r\n{0}", sName); } byte[] content = null; if (!sm.Client.IsHandShaked) { //客户端为winform tcpip消息发生重叠,使用{进行分割} if (sm.MessageType == MSGLOGIN ) content = Encoding.UTF8.GetBytes("{" + msg.ToString() + "}"); else content= Encoding.UTF8.GetBytes( msg.ToString() ); return content; } byte[] temp = Encoding.UTF8.GetBytes(msg.ToString()); if (temp.Length < 126) { content = new byte[temp.Length + 2]; content[0] = 0x81; content[1] = (byte)temp.Length; Array.Copy(temp, 0, content, 2, temp.Length); } else if (temp.Length < 0xFFFF) { content = new byte[temp.Length + 4]; content[0] = 0x81; content[1] = 126; content[2] = (byte)(temp.Length & 0xFF); content[3] = (byte)(temp.Length >> 8 & 0xFF); Array.Copy(temp, 0, content, 4, temp.Length); } else { // 暂不处理超长内容 } // Array.Copy(temp, 0, content, 4, temp.Length); return content; }
public async Task Exit(SocketMessage msg, string[] args) { await Client.LogoutAsync(); Environment.Exit(0); }
public override void handleInput(SocketMessage input) { String head = input.Header; String a = ""; String[] up ; List<String> args = input.Arguments; switch (head) { case "LOGSUCCESS": loggedIn = true; try { strUserName = args[0]; } catch (Exception e) { } eConnection.Invoke("LIN"); break; case "LOGERROR": MessageBox.Show("E-Mail or password is incorrect.", "Error"); break; case "REGERR0": MessageBox.Show("Lobby server error. Please try again later."); break; case "REGERR1": MessageBox.Show("Please enter a valid e-mail address."); break; case "REGERR2": MessageBox.Show("Password must be at least 6 characters long."); break; case "REGERR3": MessageBox.Show("Nickname already exists."); break; case "REGERR4": MessageBox.Show("E-Mail already registered."); break; case "REGSUCCESS": MessageBox.Show("Account successfully registered."); break; default: if (loggedIn) { switch (head) { case "USERONLINE": //User[] temp = new User[args.Count]; try { a = args[0]; up = a.Split(new char[1] { ':' }); OnlineUsers.Add(new User(up[0], up[1])); eUserEvent.Invoke(new User(up[0], up[1]), true); } catch (Exception e) { break; } break; case "USEROFFLINE": try { a = args[0]; up = a.Split(new char[1] { ':' }); for (int i = 0; i < OnlineUsers.Count; i++) { if (OnlineUsers[i].Email.Equals(up[0])) { eUserEvent.Invoke(OnlineUsers[i], false); OnlineUsers.RemoveAt(i); break; } } } catch (Exception e) { break; } break; case "ONLINELIST": try { OnlineUsers = new List<User>(0); for (int i = 0; i < args.Count; i++) { a = (String)args[i]; up = a.Split(new char[1] { ':' }); if (up.Length == 2) OnlineUsers.Add(new User(up[0], up[1])); } eUserEvent.Invoke(new User("", ""), true); } catch (Exception e) { } break; case "LOBCHAT": try { eLobbyChat.Invoke(LobbyChatTypes.Global, (String)args[0], (String)args[1]); } catch (Exception e) { } break; case "LOBW": try { String[] s = args[0].Split(new char[1] { ':' }); strLastWhisperFrom = s[0]; eLobbyChat.Invoke(LobbyChatTypes.Whisper, (String)args[0], (String)args[1]); } catch(Exception e){}; break; case "CHATERROR": try{ eLobbyChat.Invoke(LobbyChatTypes.Error, "ERROR", (String)args[0]); } catch(Exception e){}; break; case "CHATINFO": try { eLobbyChat.Invoke(LobbyChatTypes.System, "SYSTEM", (String)args[0]); } catch(Exception e){}; break; default: #if (DEBUG) MessageBox.Show(input.getMessage() , "Input from sock"); #endif break; } } break; } }
public void Register(String email, String username, String password) { SocketMessage sm = new SocketMessage("REG"); sm.Arguments.Add(username); sm.Arguments.Add(email); sm.Arguments.Add(password); this.writeMessage(sm); }
public async Task StartTrade(SocketMessage msg, string[] args) => await msg.Channel.SendMessageAsync($"{Configuration.PokecordPrefix}trade <@{Configuration.OwnerID}>");
public string RunCommand(string command, SocketMessage message) { string response = ""; string commandWord = ""; string[] commandArray = command.Split(' '); if (commandArray.Length > 0) { commandWord = commandArray[0].ToLower(); } string commandParameters = command.Substring(commandWord.Length, command.Length - commandWord.Length); ServerModel server; string parameterError = "This command requires parameters."; string authorMention = message.Author.Mention; switch (commandWord) { case "": response = "I didn't hear a command in there."; break; case "status": if (string.IsNullOrWhiteSpace(commandParameters)) { response = parameterError; } else { server = GetServer(commandParameters); if (server == null) { response = string.Format("I can't find \"{0}\"", commandParameters); } else { response = string.Format("{0} is {1}!", server.Name, IsServerOnline(server.Port) ? "Online" : "Offline"); } } break; case "restart": case "start": if (string.IsNullOrWhiteSpace(commandParameters)) { response = parameterError; } else { server = GetServer(commandParameters); if (server == null) { response = string.Format("I can't find \"{0}\"", commandParameters); } else { if (StartServer(server)) { //TODO: sleep for x seconds then check if server is online response = string.Format("Starting up the {0} server!", server.Name); } else { response = string.Format("I'm afraid I can't do that, {0}. The {1} server is already online.", authorMention, server.Name); } } } break; case "servers": response = "Server List: "; foreach (var x in Servers) { response += string.Format("\n{0}: {1}\nAddress: {2}\nPort: {3}", x.Name, IsServerOnline(x.Port) ? "Online" : "Offline", x.Address, x.Port); } break; case "help": var commandModels = new List <CommandModel>(); Configuration.GetSection("commands").Bind(commandModels); response += "Commands: "; foreach (var x in commandModels) { response += string.Format("\n{0}", x.Command); } response += "\nstatus (server name)\nrestart (server name)\nservers"; break; default: int commandIndex = 0; bool nullCommand = false; while (!nullCommand) { string sharedKey = "commands:" + commandIndex + ":"; string commandName = Configuration[sharedKey + "Command"]; nullCommand = commandName == null; if (nullCommand) { response = authorMention + " I do not know this command."; break; } else if (command == commandName) { response = authorMention + " " + Configuration[sharedKey + "Response"]; break; } else { commandIndex++; } } break; } return(response); }
public void Login(String email, String password) { Encoding enc = Encoding.ASCII; byte[] buffer = new byte[0]; String pass = ""; try { buffer = enc.GetBytes(password); } catch (Exception e) { } SHA1CryptoServiceProvider cryptoTransformSHA1 = new SHA1CryptoServiceProvider(); try { pass = BitConverter.ToString(cryptoTransformSHA1.ComputeHash(buffer)).Replace("-", ""); } catch (Exception e) { } cryptoTransformSHA1.Dispose(); pass = pass.ToLower(); SocketMessage sm = new SocketMessage("LOG"); sm.Arguments.Add(email); sm.Arguments.Add(pass); this.writeMessage(sm); }
public async Task AddId(SocketMessage msg, string[] args) => await msg.Channel.SendMessageAsync($"{Configuration.PokecordPrefix}p add {String.Join(' ', args)}");
public async Task Confirm(SocketMessage msg, string[] args) => await msg.Channel.SendMessageAsync($"{Configuration.PokecordPrefix}confirm");
Task MessageUpdated(Cacheable <IMessage, ulong> _, SocketMessage message, IMessageChannel channel) => HandleMessageAsync(message, MessageEvent.Modify);