public async Task SetMessage([Remainder] string mess) { var db = new BotBaseContext(); var message = db.Message.AsQueryable().Where(msg => msg.UserId == Context.User.Id).FirstOrDefault(); var user = db.User.AsQueryable().Where(usr => usr.UserId == Context.User.Id).FirstOrDefault(); if (user == null) { db.Add(new User { UserId = Context.User.Id, Name = Context.User.Username, Number = long.Parse(Context.User.Discriminator) }); } else { user.Name = Context.User.Username; user.Number = long.Parse(Context.User.Discriminator); } if (message == null) { db.Add(new Message { UserId = Context.User.Id, Message1 = mess }); } else { await ReplyAsync("Replacing old message:"); await ReplyAsync(message.Message1); message.Message1 = mess; } db.SaveChanges(); await ReplyAsync("Message Added!"); }
public async Task Commands() { var db = new BotBaseContext(); var commands = db.Command.AsQueryable().OrderBy(command => command.Category); var config = db.Configuration.AsQueryable().Where(cfg => cfg.Name == Program.configName).First(); var embed = new JifBotEmbedBuilder(); embed.Title = "All commands will begin with a " + config.Prefix + " , for more information on individual commands, use: " + config.Prefix + "help commandName"; embed.Description = "Contact Jif#3952 with any suggestions for more commands. To see all command defintions together, visit https://jifbot.com/commands.html"; string cat = commands.First().Category; string list = ""; foreach (Command command in commands) { if (command.Category != cat) { embed.AddField(cat, list.Remove(list.LastIndexOf(", "))); cat = command.Category; list = ""; } list += command.Name + ", "; } embed.AddField(cat, list.Remove(list.LastIndexOf(", "))); await ReplyAsync("", false, embed.Build()); }
public async Task Help([Remainder] string commandName) { var db = new BotBaseContext(); var command = db.Command.AsQueryable().Where(cmd => cmd.Name == commandName).FirstOrDefault(); var config = db.Configuration.AsQueryable().Where(cfg => cfg.Name == Program.configName).First(); if (command == null) { var cmdAlias = db.CommandAlias.AsQueryable().Where(cmd => cmd.Alias == commandName).FirstOrDefault(); if (cmdAlias == null) { await ReplyAsync($"{commandName} is not a command, make sure the spelling is correct."); return; } command = db.Command.AsQueryable().Where(cmd => cmd.Name == cmdAlias.Command).First(); } var alias = db.CommandAlias.AsQueryable().Where(als => als.Command == command.Name); string msg = $"{command.Description}\n**Usage**: {command.Usage}"; if (alias.Any()) { msg += "\nAlso works for: "; foreach (CommandAlias al in alias) { msg += $"{config.Prefix}{al.Alias} "; } } await ReplyAsync(msg); }
public async Task meanCount([Remainder] string useless = "") { var db = new BotBaseContext(); var count = db.Variable.AsQueryable().Where(v => v.Name == "meanCount").First(); await ReplyAsync("I mean, I've said it " + count.Value + " times since 12/13/18."); }
public async Task InviteLink() { var db = new BotBaseContext(); var config = db.Configuration.AsQueryable().Where(cfg => cfg.Name == Program.configName).First(); await ReplyAsync($"The following is a link to add me to another server. NOTE: You must have permissions on the server in order to add. Once on the server I must be given permission to send and delete messages, otherwise I will not work.\nhttps://discordapp.com/oauth2/authorize?client_id={config.Id}&scope=bot"); }
public async Task iMean([Remainder] string useless = "") { var db = new BotBaseContext(); var count = db.Variable.AsQueryable().AsQueryable().Where(v => v.Name == "meanCount").First(); await ReplyAsync($"Jif has said \"I mean\" {count.Value} times"); }
public async Task SendMessageReport(Cacheable <IMessage, ulong> cache, ISocketMessageChannel channel) { SocketGuildChannel socketChannel = (SocketGuildChannel)channel; var db = new BotBaseContext(); var config = db.ServerConfig.AsQueryable().Where(s => s.ServerId == socketChannel.Guild.Id).FirstOrDefault(); if (config != null && config.MessageId != 0) { IGuild server = bot.GetGuild(config.ServerId); ITextChannel sendChannel = await server.GetTextChannelAsync(config.MessageId); var message = await cache.GetOrDownloadAsync(); var embed = new JifBotEmbedBuilder(); embed.Title = "A message has been deleted"; if (message != null) { embed.Description = "\"" + message.Content + "\""; embed.AddField("in " + channel.Name, "sent by: " + message.Author); embed.ThumbnailUrl = message.Author.GetAvatarUrl(); } else { embed.AddField("in " + channel.Name, "message unknown"); } await sendChannel.SendMessageAsync("", false, embed.Build()); } }
public Embed BuildReactMessage(IGuild server) { var db = new BotBaseContext(); var embed = new JifBotEmbedBuilder(); embed.Title = "React with the following emojis to receive the corresponding role. Remove the reaction to remove the role."; embed.Description = ""; var roles = db.ReactRole.AsQueryable().Where(r => r.ServerId == server.Id).DefaultIfEmpty(); var config = db.Configuration.AsQueryable().Where(c => c.Name == Program.configName).First(); if (roles.First() == null) { embed.Description = $"No emotes currently set. Use {config.Prefix}reactrole to set roles"; } else { foreach (var role in roles) { var dRole = server.GetRole(role.RoleId); embed.Description += $"{role.Emote} -- {dRole.Mention}"; if (role.Description != "") { embed.Description += $"\n {role.Description}"; } embed.Description += "\n\n"; } } return(embed.Build()); }
public async Task Changelog() { var db = new BotBaseContext(); var embed = new JifBotEmbedBuilder(); var totalEntries = db.ChangeLog.AsQueryable().OrderByDescending(e => e.Date); var entriesToPrint = new Dictionary <string, string>(); foreach (ChangeLog entry in totalEntries) { if (!entriesToPrint.ContainsKey(entry.Date)) { if (entriesToPrint.Count >= 3) { break; } entriesToPrint.Add(entry.Date, $"\\> {entry.Change}"); } else { entriesToPrint[entry.Date] += $"\n\\> {entry.Change}"; } } embed.Title = "Last 3 Jif Bot updates"; embed.Description = "For a list of all updates, visit https://jifbot.com/changelog.html"; foreach (var entry in entriesToPrint) { var pieces = entry.Key.Split("-"); embed.AddField($"{pieces[1]}.{pieces[2]}.{pieces[0]}", entry.Value); } await ReplyAsync("", false, embed.Build()); }
public JifBotEmbedBuilder() { var db = new BotBaseContext(); var color = db.Variable.AsQueryable().Where(V => V.Name == "embedColor").FirstOrDefault(); WithColor(new Color(Convert.ToUInt32(color.Value, 16))); WithFooter("Made with love"); WithCurrentTimestamp(); }
public async Task Mastery(string region, [Remainder] string name) { var db = new BotBaseContext(); var embed = new JifBotEmbedBuilder(); { name = name.Replace(" ", string.Empty); System.Net.Http.HttpClient client = new System.Net.Http.HttpClient(); string html = ""; try { html = await client.GetStringAsync("https://championmasterylookup.derpthemeus.com/summoner?summoner=" + name + "®ion=" + region.ToUpper()); } catch { await ReplyAsync("That summoner does not exist"); return; } html = html.Remove(0, html.IndexOf("/img/profile")); embed.ThumbnailUrl = "https://championmasterylookup.derpthemeus.com" + html.Remove(html.IndexOf("\"")); html = html.Remove(0, html.IndexOf("userName="******"Top ten mastery scores for " + (html.Remove(html.IndexOf("\"")).Replace("%20", " ")); string champ = ""; string nums = ""; int count = 0; for (int i = 1; i <= 10; i++) { if (html.IndexOf("/champion?") == html.IndexOf("/champion?champion=-1")) { break; } html = html.Remove(0, html.IndexOf("/champion?")); html = html.Remove(0, html.IndexOf(">") + 1); champ = html.Remove(html.IndexOf("<")); champ = champ.Replace("'", "'"); html = html.Remove(0, html.IndexOf("\"") + 1); nums = html.Remove(html.IndexOf("\"")); count = count + Convert.ToInt32(nums); for (int j = nums.Length - 3; j > 0; j = j - 3) { nums = nums.Remove(j) + "," + nums.Remove(0, j); } embed.AddField(i + ". " + champ, nums + " points", inline: true); } nums = Convert.ToString(count); for (int j = nums.Length - 3; j > 0; j = j - 3) { nums = nums.Remove(j) + "," + nums.Remove(0, j); } embed.Description = "Total score across top ten: " + nums; await ReplyAsync("", false, embed.Build()); } }
public async Task Movie([Remainder] string word) { var db = new BotBaseContext(); var omdbKey = db.Variable.AsQueryable().Where(v => v.Name == "omdbKey").First(); HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://www.omdbapi.com"); HttpResponseMessage response = await client.GetAsync($"?t={word}&plot=full&apikey={omdbKey.Value}"); HttpContent content = response.Content; string stuff = await content.ReadAsStringAsync(); var json = JObject.Parse(stuff); if ((string)json.SelectToken("Response") == "False") { await ReplyAsync("Movie not found"); return; } var embed = new JifBotEmbedBuilder(); string rt = (string)json.SelectToken("Ratings[1].Value"); string imdb = (string)json.SelectToken("Ratings[0].Value"); string plot = (string)json.SelectToken("Plot"); if (plot.Length > 1024) { int excess = plot.Length - 1024; plot = plot.Remove(plot.Length - excess - 3); plot += "..."; } embed.Title = (string)json.SelectToken("Title"); embed.Description = (string)json.SelectToken("Genre"); if ((string)json.SelectToken("Poster") != "N/A") { embed.ThumbnailUrl = (string)json.SelectToken("Poster"); } if (rt != null) { embed.AddField($"Rotten Tomatoes: {rt}, IMDb: {imdb}", plot); } else { embed.AddField($"IMDb Rating: {imdb}", plot); } embed.AddField("Released", (string)json.SelectToken("Released"), inline: true); embed.AddField("Run Time", (string)json.SelectToken("Runtime"), inline: true); embed.AddField("Rating", (string)json.SelectToken("Rated"), inline: true); embed.AddField("Starring", (string)json.SelectToken("Actors")); embed.AddField("Directed By", (string)json.SelectToken("Director"), inline: true); embed.WithUrl("https://www.imdb.com/title/" + (string)json.SelectToken("imdbID")); await ReplyAsync("", false, embed.Build()); }
public async Task Timer([Remainder] string message = "") { int waitTime = 0; if (Regex.IsMatch(message, @"-(m *[0-9]+|[0-9]+m)")) { waitTime += Convert.ToInt32(Regex.Match(message, @"-(m *[0-9]+|[0-9]+m)").Value.Replace("-", "").Replace("m", "")); } if (Regex.IsMatch(message, @"-(h *[0-9]+|[0-9]+h)")) { waitTime += (Convert.ToInt32(Regex.Match(message, @"-(h *[0-9]+|[0-9]+h)").Value.Replace("-", "").Replace("h", "")) * 60); } if (Regex.IsMatch(message, @"-(d *[0-9]+|[0-9]+d)")) { waitTime += (Convert.ToInt32(Regex.Match(message, @"-(d *[0-9]+|[0-9]+d)").Value.Replace("-", "").Replace("d", "")) * 1440); } if (Regex.IsMatch(message, @"-(w *[0-9]+|[0-9]+w)")) { waitTime += (Convert.ToInt32(Regex.Match(message, @"-(w *[0-9]+|[0-9]+w)").Value.Replace("-", "").Replace("w", "")) * 10080); } if (waitTime == 0) { if (Regex.IsMatch(message, @" *[0-9]+")) { waitTime = Convert.ToInt32(message.Split(" ")[0]); } else { var db = new BotBaseContext(); var config = db.Configuration.AsQueryable().Where(cfg => cfg.Name == Program.configName).First(); await ReplyAsync($"Please provide an amount of time to wait for. For assistance, use {config.Prefix}help."); return; } } message = Regex.Replace(message, @"-([m,h,d,w] *[0-9]+|[0-9]+[m,h,d,w])", ""); if (message.Replace(" ", "") == "") { message = "Times up!"; } Process proc = new System.Diagnostics.Process(); proc.StartInfo.FileName = "/bin/bash"; proc.StartInfo.Arguments = "../../../Scripts/sendmessage.sh " + Context.Channel.Id + " \"" + Context.User.Mention + " " + message + "\" " + waitTime; proc.StartInfo.UseShellExecute = false; proc.StartInfo.RedirectStandardOutput = true; proc.Start(); await ReplyAsync("Setting timer for " + formatMinutesToString(waitTime) + " from now."); }
private async Task CheckSignature(SocketUserMessage msg) { var db = new BotBaseContext(); var signature = db.Signature.AsQueryable().AsQueryable().Where(sig => sig.UserId == msg.Author.Id).FirstOrDefault(); if (signature != null) { Emoji react = new Emoji(signature.Signature1); await msg.AddReactionAsync(react); } }
public async Task honkBoard([Remainder] string msg = "") { int results = 5; var db = new BotBaseContext(); var honks = db.Honk.AsQueryable().OrderByDescending(honk => honk.Count); int count = 1; long total = 0; string message = ""; if (Regex.IsMatch(msg, @"[0-9]+")) { results = Convert.ToInt32(Regex.Match(msg, @"[0-9]+").Value); } if (Regex.IsMatch(msg, @"-a")) { results = honks.Count() + 1; } foreach (Honk honk in honks) { var user = db.User.AsQueryable().Where(user => user.UserId == honk.UserId).FirstOrDefault(); if (count <= results) { if (count == 1) { message += "🥇"; } else if (count == 2) { message += "🥈"; } else if (count == 3) { message += "🥉"; } else if (count <= results) { message += $" {count} "; } message += $" {user.Name}#{user.Number} - **{honk.Count}** honks\n"; } total += honk.Count; if (count == results) { message += $"**Top {count} honks:** {total}\n"; } count++; } message += $"**Total honks:** {total}"; await ReplyAsync(message); }
public async Task Poll([Remainder] string input) { if (input.Split("|").Length < 3) { await ReplyAsync("Please provide a question and at least two options in the format: Question | Option1 | Option2 etc."); return; } var db = new BotBaseContext(); string key = db.Variable.AsQueryable().Where(v => v.Name == "strawpollKey").First().Value; string stringToSend = "{ \"poll\": {\"title\": \""; int splitNum = 1; foreach (string substring in input.Split("|")) { if (splitNum == 1) { stringToSend += substring + "\",\"answers\": ["; } else { stringToSend += "\"" + substring + "\""; } if (splitNum == input.Split("|").Length) { stringToSend += "]}}"; } else if (splitNum != 1) { stringToSend += ","; } splitNum++; } var stringContent = new StringContent(stringToSend); HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("API-KEY", key); HttpResponseMessage response = await client.PostAsync("https://strawpoll.com/api/poll", stringContent); HttpContent content = response.Content; string stuff = await content.ReadAsStringAsync(); var json = JObject.Parse(stuff); await ReplyAsync("https://strawpoll.com/" + (string)json.SelectToken("content_id")); }
public async Task ToggleSignature([Remainder] string sig = "") { var db = new BotBaseContext(); var signature = db.Signature.AsQueryable().Where(s => s.UserId == Context.User.Id).FirstOrDefault(); var user = db.User.AsQueryable().Where(usr => usr.UserId == Context.User.Id).FirstOrDefault(); sig = sig.Replace("<", string.Empty); sig = sig.Replace(">", string.Empty); if (user == null) { db.Add(new User { UserId = Context.User.Id, Name = Context.User.Username, Number = long.Parse(Context.User.Discriminator) }); } else { user.Name = Context.User.Username; user.Number = long.Parse(Context.User.Discriminator); } if (sig == "") { if (signature == null) { await ReplyAsync("User does not have a signature to remove. Doing nothing."); return; } db.Signature.Remove(signature); } else { if (signature == null) { db.Add(new Signature { UserId = Context.User.Id, Signature1 = sig }); } else if (signature.Signature1 == sig) { db.Signature.Remove(signature); } else { signature.Signature1 = sig; } } db.SaveChanges(); await ReplyAsync("Signature updated."); }
public async Task Message() { var db = new BotBaseContext(); var message = db.Message.AsQueryable().Where(msg => msg.UserId == Context.User.Id).FirstOrDefault(); var config = db.Configuration.AsQueryable().Where(cfg => cfg.Name == Program.configName).First(); if (message == null) { await ReplyAsync($"User does not have a message yet! use {config.Prefix}setmessage to set a message."); } else { await ReplyAsync(message.Message1); } }
public async Task Start(string[] args) { var db = new BotBaseContext(); foreach (string arg in args) { if (arg == "--test") { configName = "Test"; } } client = new DiscordSocketClient(new DiscordSocketConfig { //WebSocketProvider = Discord.Net.Providers.WS4Net.WS4NetProvider.Instance MessageCacheSize = 500, LogLevel = LogSeverity.Verbose, AlwaysDownloadUsers = true }); client.Log += JifBot.EventHandler.WriteLog; client.Ready += OnReady; var config = db.Configuration.AsQueryable().Where(cfg => cfg.Name == configName).First(); await client.LoginAsync(TokenType.Bot, config.Token); await client.StartAsync(); map = ConfigureServices(); bot = map.GetService <DiscordSocketClient>(); commands = map.GetService <CommandService>(); eventHandler = new JifBot.EventHandler(map); bot.UserJoined += eventHandler.AnnounceUserJoined; bot.UserLeft += eventHandler.AnnounceLeftUser; bot.MessageDeleted += eventHandler.SendMessageReport; bot.MessageReceived += eventHandler.HandleMessage; bot.ReactionAdded += eventHandler.HandleReactionAdded; bot.ReactionRemoved += eventHandler.HandleReactionRemoved; await commands.AddModulesAsync(Assembly.GetEntryAssembly(), map); //Block this program untill it is closed await Task.Delay(-1); }
public async Task ToggleReactions([Remainder] string args = "") { var db = new BotBaseContext(); if (args.ToLower().Contains("all")) { var channels = db.ReactionBan.AsQueryable().Where(c => c.ServerId == Context.Guild.Id).ToList(); if (channels.Count == 0) { foreach (var c in await Context.Guild.GetTextChannelsAsync()) { db.Add(new ReactionBan { ChannelId = c.Id, ServerId = Context.Guild.Id, ChannelName = c.Name }); } await ReplyAsync("Reactions are now disabled for all currently available channels in the server"); } else { foreach (var c in channels) { db.Remove(c); } await ReplyAsync("Reactions are now enabled for all channels in this server"); } } else { var channel = db.ReactionBan.AsQueryable().Where(s => s.ChannelId == Context.Channel.Id).FirstOrDefault(); if (channel == null) { db.Add(new ReactionBan { ChannelId = Context.Channel.Id, ServerId = Context.Guild.Id, ChannelName = Context.Channel.Name }); await ReplyAsync($"Reactions are now disabled for {Context.Channel.Name}"); } else { db.ReactionBan.Remove(channel); await ReplyAsync($"Reactions are now enabled for {Context.Channel.Name}"); } } db.SaveChanges(); }
public async Task AnnounceLeftUser(SocketGuildUser user) { Console.WriteLine("User " + user.Username + " Left " + user.Guild.Name); var db = new BotBaseContext(); var config = db.ServerConfig.AsQueryable().Where(s => s.ServerId == user.Guild.Id).FirstOrDefault(); if (config != null && config.LeaveId != 0) { IGuild server = user.Guild; ITextChannel channel = await server.GetTextChannelAsync(config.LeaveId); var embed = new JifBotEmbedBuilder(); embed.ThumbnailUrl = user.GetAvatarUrl(); embed.Title = $"**{user.Username} Left The Server:**"; embed.Description = $"**User:**{user.Mention}"; await channel.SendMessageAsync("", false, embed.Build()); } }
public EmbedBuilder ConstructEmbedInfo(IGuildUser user) { var db = new BotBaseContext(); var embed = new JifBotEmbedBuilder(); embed.WithAuthor(user.Username + "#" + user.Discriminator, user.GetAvatarUrl()); embed.ThumbnailUrl = user.GetAvatarUrl(); embed.AddField("User ID", user.Id); if (user.Nickname == null) { embed.AddField("Nickname", user.Username); } else { embed.AddField("Nickname", user.Nickname); } if (user.Activity == null) { embed.AddField("Currently Playing", "[nothing]"); } else { embed.AddField("Currently " + user.Activity.Type.ToString(), user.Activity.Name); } embed.AddField("Account Creation Date", FormatTime(user.CreatedAt)); embed.AddField("Server Join Date", FormatTime(user.JoinedAt.Value)); string roles = ""; foreach (ulong id in user.RoleIds) { if (roles != "") { roles = roles + ", "; } if (Context.Guild.GetRole(id).Name != "@everyone") { roles = roles + Context.Guild.GetRole(id).Name; } } embed.AddField("Roles", roles); return(embed); }
private async Task handleCommand(SocketUserMessage message) { var db = new BotBaseContext(); var context = new SocketCommandContext(bot, message); //Mark where the prefix ends and the command begins int argPos = 0; var config = db.Configuration.AsQueryable().Where(cfg => cfg.Name == Program.configName).First(); //Determine if the message has a valid prefix, adjust argPos if (message.HasStringPrefix(config.Prefix, ref argPos)) { //Execute the command, store the result var result = await commands.ExecuteAsync(context, argPos, map); //If the command failed, notify the user if (!result.IsSuccess && result.ErrorReason != "Unknown command.") { await message.Channel.SendMessageAsync($"**Error:** {result.ErrorReason}"); } } }
public async Task HandleReactionRemoved(Cacheable <IUserMessage, ulong> cache, ISocketMessageChannel channel, SocketReaction reaction) { var db = new BotBaseContext(); var config = db.ServerConfig.AsQueryable().Where(s => s.ReactMessageId == cache.Id).FirstOrDefault(); if (config != null) { var role = db.ReactRole.AsQueryable().Where(s => s.ServerId == config.ServerId && s.Emote == reaction.Emote.ToString()).FirstOrDefault(); if (role != null) { var server = bot.GetGuild(config.ServerId); var serverRole = server.GetRole(role.RoleId); var user = server.GetUser(reaction.UserId); if (serverRole != null) { await user.RemoveRoleAsync((IRole)serverRole); } } } }
public async Task SetMessageReport([Remainder] string args = "") { var db = new BotBaseContext(); var config = db.ServerConfig.AsQueryable().Where(s => s.ServerId == Context.Guild.Id).FirstOrDefault(); if (config != null) { if (config.MessageId == Context.Channel.Id) { config.MessageId = 0; await ReplyAsync($"Message deletion reports will no longer be sent in {Context.Channel.Name}"); } else { var old = await Context.Guild.GetTextChannelAsync(config.MessageId); config.MessageId = Context.Channel.Id; if (old != null) { await ReplyAsync($"Message deletion reports will no longer be sent in {old.Name}, will now be sent in {Context.Channel.Name}"); } else { await ReplyAsync($"Message deletion reports will now be sent in {Context.Channel.Name}"); } } } else { db.Add(new ServerConfig { ServerId = Context.Guild.Id, MessageId = Context.Channel.Id }); await ReplyAsync($"Message deletion reports will now be sent in {Context.Channel.Name}"); } db.SaveChanges(); }
private Task OnReady() { var db = new BotBaseContext(); var config = db.Configuration.AsQueryable().Where(cfg => cfg.Name == configName).First(); client.SetGameAsync(config.Prefix + "commands"); db.Command.RemoveRange(db.Command); db.CommandAlias.RemoveRange(db.CommandAlias); foreach (Discord.Commands.CommandInfo c in this.commands.Commands) { if (c.Module.Name != "Hidden") { if (c.Aliases.Count > 1) { foreach (string alias in c.Aliases) { if (alias != c.Name) { db.Add(new CommandAlias { Alias = alias, Command = c.Name }); } } } db.Add(new Command { Name = c.Name, Category = c.Module.Name, Usage = c.Remarks.Replace("-c-", $"{config.Prefix}{c.Name}"), Description = c.Summary.Replace("-p-", config.Prefix) }); } } var update = db.Variable.AsQueryable().Where(V => V.Name == "lastCmdUpdateTime").FirstOrDefault(); update.Value = DateTime.Now.ToLocalTime().ToString(); db.SaveChanges(); return(Task.CompletedTask); }
public async Task honkCount([Remainder] string msg = "") { var db = new BotBaseContext(); Honk honk = new Honk(); if (Regex.IsMatch(msg, @"[0-9]+")) { var id = Convert.ToUInt64(Regex.Match(msg, @"[0-9]+").Value); honk = db.Honk.AsQueryable().Where(user => user.UserId == id).FirstOrDefault(); } else { honk = db.Honk.AsQueryable().Where(user => user.UserId == Context.Message.Author.Id).FirstOrDefault(); } if (honk != null) { await ReplyAsync($"Honked {honk.Count} times!"); } else { await ReplyAsync("This user has never honked! For shame!"); } }
public async Task Dice([Remainder] string message = "") { Match dice = Regex.Match(message, @"[0-9]+d[0-9]+ *(?:a|d)?( *(?:\+|-) *[0-9]+)*"); if (!dice.Success && message != "") { BotBaseContext db = new BotBaseContext(); var config = db.Configuration.AsQueryable().Where(cfg => cfg.Name == Program.configName).First(); await ReplyAsync($"Invalid syntax, use {config.Prefix}help roll for more info"); return; } Random rnd = new Random(); int numDice = 1; int diceSides = 6; int modifier = 0; bool advantage = false; int numRolls = 1; string[] rolls = new string[] { "", "" }; int[] totals = new int[] { 0, 0 }; int printRoll = 0; string msg = ""; if (message != "") { // Get values from Regex message = dice.Value; MatchCollection vals = Regex.Matches(message, @"[0-9]+"); MatchCollection mods = Regex.Matches(message, @"( *(?:\+|-) *[0-9]+)"); numDice = Convert.ToInt32(vals[0].Value); diceSides = Convert.ToInt32(vals[1].Value); foreach (Match mod in mods) { string val = Regex.Match(mod.Value, @"[0-9]+").Value; if (mod.Value.Contains("+")) { modifier += Convert.ToInt32(val); } else { modifier -= Convert.ToInt32(val); } } // advantage if (message.Contains("a")) { advantage = true; numRolls = 2; } // disadvantage if (message.Count(d => d == 'd') == 2) { numRolls = 2; } } if (numDice == 0 || diceSides == 0) { await ReplyAsync("Cannot be 0"); return; } if (numDice > 200 || diceSides > 200 || modifier > 1000 || modifier < -1000) { await Context.Channel.SendFileAsync("Media/joke.jpg"); return; } for (int i = 0; i < numRolls; i++) { for (int j = 0; j < numDice; j++) { int num = rnd.Next(diceSides) + 1; totals[i] += num; rolls[i] += $"{num}, "; } totals[i] += modifier; rolls[i] = rolls[i].Remove(rolls[i].LastIndexOf(", ")); } if (numRolls > 1) { int high = 0; msg = $"1st Roll: {rolls[0]}\n2nd Roll: {rolls[1]}"; if (totals[1] > totals[0]) { high = 1; } //advantage if (advantage && high == 1) { printRoll = 1; } //disadvantage else if (!advantage && high == 0) { printRoll = 1; } if (printRoll == 0) { msg = msg.Replace("1st Roll", "**1st Roll**"); } else { msg = msg.Replace("2nd Roll", "**2nd Roll**"); } } else { msg = "Rolled: " + rolls[0]; } if (numDice == 1 && numRolls == 1 && modifier == 0) { await ReplyAsync($"{totals[0]}"); } else if (modifier == 0 && numDice == 1) { await ReplyAsync($"{msg}"); } else { await ReplyAsync($"{msg}\nTotal: **{totals[printRoll]}**"); } }
public async Task PlaceReactMessage([Remainder] string command = "") { var db = new BotBaseContext(); var config = db.ServerConfig.AsQueryable().Where(s => s.ServerId == Context.Guild.Id).FirstOrDefault(); if (command == "-d") { if (config != null && config.ReactMessageId != 0 && config.ReactChannelId != 0) { var channel = await Context.Guild.GetTextChannelAsync(config.ReactChannelId); var msg = await channel.GetMessageAsync(config.ReactMessageId); await msg.DeleteAsync(); config.ReactChannelId = 0; config.ReactMessageId = 0; db.SaveChanges(); await ReplyAsync("Message removed. Any withstanding roles will remain."); return; } await ReplyAsync("Message does not exist, or cannot be found. Not deleting"); return; } var message = await ReplyAsync("", false, BuildReactMessage(Context.Guild)); if (config == null) { db.Add(new ServerConfig { ServerId = Context.Guild.Id, ReactMessageId = message.Id, ReactChannelId = message.Channel.Id }); } else { if (config.ReactChannelId != 0) { var channel = await Context.Guild.GetTextChannelAsync(config.ReactChannelId); var msg = await channel.GetMessageAsync(config.ReactMessageId); await msg.DeleteAsync(); } config.ReactMessageId = message.Id; config.ReactChannelId = message.Channel.Id; } db.SaveChanges(); var roles = db.ReactRole.AsQueryable().Where(r => r.ServerId == Context.Guild.Id).DefaultIfEmpty(); foreach (var role in roles) { var botConfig = db.Configuration.AsQueryable().Where(b => b.Name == Program.configName).First(); var bot = await Context.Guild.GetUserAsync(botConfig.Id); // Emojis and Discord Emotes are handled differently if (Regex.IsMatch(role.Emote, @"(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])")) { Emoji dEmoji = new Emoji(role.Emote); await message.AddReactionAsync(dEmoji); } else { Emote dEmote = Emote.Parse(role.Emote); await message.AddReactionAsync(dEmote); } } }
public async Task ReactRole(string role, string emote, [Remainder] string description = "") { // Check to ensure the role is valid var db = new BotBaseContext(); Emote dEmote; if (!Regex.IsMatch(role, @"[0-9]+")) { await ReplyAsync("Not a valid role"); return; } ulong roleId = Convert.ToUInt64(Regex.Match(role, @"[0-9]+").Value); if (Context.Guild.Roles.Where(r => r.Id == roleId).FirstOrDefault() == null) { await ReplyAsync("Not a valid role"); return; } var react = db.ReactRole.AsQueryable().Where(s => s.RoleId == roleId).FirstOrDefault(); // specified to delete the react role if (emote == "-d") { if (react != null) { db.Remove(react); db.SaveChanges(); await ReplyAsync("Role removed"); } else { await ReplyAsync("Role does not exist. Not removing"); return; } } else { // Check to ensure the emote is in a valid format if (!Regex.IsMatch(emote, @"(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])") && !Emote.TryParse(emote, out dEmote)) { await ReplyAsync("Not a valid reaction emote"); return; } var rRole = db.ReactRole.AsQueryable().Where(r => r.Emote == emote && r.ServerId == Context.Guild.Id).FirstOrDefault(); // if there exists an entry in this server with the specified emote that is not the specified role if (rRole != null && rRole.RoleId != roleId) { await ReplyAsync("Emote already being used"); return; } // if there is no entry for this role else if (react == null) { db.Add(new ReactRole { RoleId = roleId, Emote = emote, Description = description, ServerId = Context.Guild.Id }); db.SaveChanges(); await ReplyAsync("Role Added"); react = db.ReactRole.AsQueryable().Where(s => s.RoleId == roleId).FirstOrDefault(); } // update emote and description else { react.Emote = emote; react.Description = description; db.SaveChanges(); await ReplyAsync($"Updated entry for <@&{react.RoleId}>"); } } var config = db.ServerConfig.AsQueryable().Where(s => s.ServerId == Context.Guild.Id).FirstOrDefault(); var channel = await Context.Guild.GetTextChannelAsync(config.ReactChannelId); var msg = (IUserMessage)await channel.GetMessageAsync(config.ReactMessageId); await msg.ModifyAsync(m => m.Embed = BuildReactMessage(Context.Guild)); var botConfig = db.Configuration.AsQueryable().Where(b => b.Name == Program.configName).First(); var bot = await Context.Guild.GetUserAsync(botConfig.Id); // Emojis and Discord Emotes are handled differently if (Regex.IsMatch(react.Emote, @"(\u00a9|\u00ae|[\u2000-\u3300]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff])")) { Emoji dEmoji = new Emoji(react.Emote); if (emote == "-d") { await msg.RemoveReactionAsync(dEmoji, bot); } else { await msg.AddReactionAsync(dEmoji); } } else { dEmote = Emote.Parse(react.Emote); if (emote == "-d") { await msg.RemoveReactionAsync(dEmote, bot); } else { await msg.AddReactionAsync(dEmote); } } }