public async Task <IDiscordMessage> WaitForNextMessage(CommandSession session, int timeOutInMilliseconds = 10000) { IDiscordMessage nextMessage = null; if (sessionCache.TryAdd(session, (msg) => { nextMessage = msg; })) { while (nextMessage == null) { await Task.Delay(100); timeOutInMilliseconds -= 100; if (timeOutInMilliseconds <= 0) { throw new TimeoutException(); } } sessionCache.TryRemove(session, out var x); } return(nextMessage); }
public async ValueTask CheckAsync(IDiscordMessage data, IMutableContext e, Func <ValueTask> next) { if (e.Executable == null) { Log.Warning("No command was selected, discontinue the flow."); return; } if (!(e.Executable is Node node)) { Log.Warning("Executable was not made from a default Node."); return; } var scopesRequired = node.Attributes .OfType <RequiresScopeAttribute>() .Select(x => x.ScopeId) .ToList(); var scopesGranted = await service.HasScopeAsync( (long)e.GetMessage().Author.Id, scopesRequired) .ConfigureAwait(false); if (!scopesGranted) { Log.Warning("User tried to access scoped command, failed scope check."); return; } await next().ConfigureAwait(false); }
private async Task Module_MessageReceived(IDiscordMessage message) { if (await IsEnabled(message.Guild.Id)) { await MessageRecieved(message); } }
public async Task SetProfileBackColorAsync(EventContext e) { using (var context = new MikiContext()) { User user = await User.GetAsync(context, e.Author); new EmbedBuilder() .SetTitle("Hold on!") .SetDescription("Changing your background color costs 250 mekos. type a hex to purchase") .ToEmbed().QueueToChannel(e.Channel); IDiscordMessage msg = await e.EventSystem.GetCommandHandler <MessageListener>().WaitForNextMessage(e.CreateSession()); var x = Regex.Matches(msg.Content.ToUpper(), "(#)?([A-F0-9]{6})"); if (x.Count > 0) { ProfileVisuals visuals = await ProfileVisuals.GetAsync(e.Author.Id, context); var hex = x.First().Groups.Last().Value; visuals.BackgroundColor = hex; await user.AddCurrencyAsync(-250, e.Channel); await context.SaveChangesAsync(); e.SuccessEmbed($"Your background color has been successfully changed to `{hex}`") .QueueToChannel(e.Channel); } else { throw new ArgumentException("Argument was not a hex color"); } } }
public async Task OnMention(IDiscordMessage e) { foreach (RuntimeCommandEvent ev in events.MentionEvents.Values) { await ev.Check(e); } }
public static HttpStatusCode PostToDiscord(IDiscordMessage notification) { Message request = notification.GetDiscordMessage(); string urlKey = ConfigurationManager.AppSettings["DiscordHookToUse"]; string url = ConfigurationManager.AppSettings[urlKey]; RestClient client = new RestClient(url); RestRequest rr = new RestRequest(); rr.JsonSerializer = new NonSuckyJsonSerializer(); rr.AddJsonBody(request); rr.Method = Method.POST; try { IRestResponse response = client.Execute(rr); if (response.StatusCode == HttpStatusCode.OK) { log.Info($"Message posted to discord successfully: {response.Content}"); } else { log.Error($"Non-OK code posting message to discord. {Environment.NewLine}Content: {response.Content} {Environment.NewLine}Error Message: {response.ErrorMessage}"); } return(response.StatusCode); } catch (Exception ex) { log.Error("Exception posting message to discord.", ex); } return(HttpStatusCode.InternalServerError); }
private async Task OnBlackjackWin(EventContext e, BlackjackManager bm, IDiscordMessage instanceMessage, int bet) { e.EventSystem.GetCommandHandler <SessionBasedCommandHandler>() .RemoveSession(e.Author.Id, e.Channel.Id); User user; using (var context = new MikiContext()) { user = await context.Users.FindAsync(e.Author.Id.ToDbLong()); if (user != null) { await user.AddCurrencyAsync(bet * 2, e.Channel); await context.SaveChangesAsync(); } } await instanceMessage.EditAsync(new EditMessageArgs { embed = bm.CreateEmbed(e) .SetAuthor(e.GetResource("miki_blackjack_win_title") + " | " + e.Author.Username, e.Author.GetAvatarUrl(), "https://patreon.com/mikibot") .SetDescription(e.GetResource("miki_blackjack_win_description", bet * 2) + "\n" + e.GetResource("miki_blackjack_new_balance", user.Currency)) .ToEmbed() }); }
public async ValueTask CheckAsync(IDiscordMessage data, IMutableContext e, Func <ValueTask> next) { if (e.Executable == null) { Log.Warning("Command not found, state check cancelling current pipeline instance."); return; } string commandId = e.Executable.ToString(); if (string.IsNullOrWhiteSpace(commandId)) { throw new Exception("command ID not set."); } var dbContext = e.GetService <DbContext>(); if (dbContext == null) { throw new Exception("No Entity database set."); } var state = await GetCommandStateAsync( dbContext, commandId, (long)data.ChannelId); if (!state.State) { throw new Exception("State was denied"); } await next(); }
public async Task Service_MessageReceived(IDiscordMessage m) { if (await IsEnabled(m.Channel.Id)) { await AccountManager.Instance.CheckAsync(m); } }
public CommandHandlerBuilder SetOwner(IDiscordMessage owner) { commandHandler.IsPrivate = true; commandHandler.Owner = owner.Author.Id; commandHandler.ChannelId = owner.Channel.Id; return(this); }
public async Task StartBlackjack(EventContext e, int bet) { using (var context = new MikiContext()) { User user = await context.Users.FindAsync(e.Author.Id.ToDbLong()); await user.AddCurrencyAsync(-bet, e.Channel); await context.SaveChangesAsync(); } BlackjackManager bm = new BlackjackManager(); IDiscordMessage message = await bm.CreateEmbed(e) .ToEmbed() .SendToChannel(e.Channel); Framework.Events.CommandMap map = new Framework.Events.CommandMap(); SimpleCommandHandler c = new SimpleCommandHandler(map); c.AddPrefix(""); c.AddCommand(new CommandEvent("hit") .Default(async(ec) => await OnBlackjackHit(ec, bm, message, bet))); c.AddCommand(new CommandEvent("stand") .SetAliases("knock", "stay", "stop") .Default(async(ec) => await OnBlackjackHold(ec, bm, message, bet))); e.EventSystem.GetCommandHandler <SessionBasedCommandHandler>().AddSession( new CommandSession() { UserId = e.Author.Id, ChannelId = e.Channel.Id }, c, new TimeSpan(1, 0, 0)); }
public async Task CheckAsync(IDiscordMessage msg) { if (IsPrivate) { if (msg.Author.Id == Owner) { foreach (PrefixInstance prefix in Prefixes.Values) { if (await TryRunCommandAsync(msg, prefix)) { break; } } } return; } foreach (PrefixInstance prefix in Prefixes.Values) { if (await TryRunCommandAsync(msg, prefix)) { break; } } }
public async Task Service_MessageReceived(IDiscordMessage m) { if (await IsEnabled(Global.RedisClient, m.GetChannelAsync().Result.Id)) { await AccountManager.Instance.CheckAsync(m); } }
public async ValueTask CheckAsync(IDiscordMessage data, IMutableContext e, Func <ValueTask> next) { if (e.Executable != null) { await next(); return; } if (e == null) { return; } if (e.GetMessage().Type != DiscordMessageType.DEFAULT) { await next(); return; } var service = e.GetService <ICustomCommandsService>(); var startIndex = e.GetPrefixMatch().Length; var message = e.GetMessage().Content; var endIndex = message.IndexOf(' ', startIndex); var commandName = endIndex == -1 ? message.Substring(startIndex) : message.Substring(startIndex, endIndex - startIndex); if (!await service.ExecuteAsync(e, commandName)) { await next(); } }
public async Task StartBlackjack(EventContext e, int bet) { using (var context = new MikiContext()) { User user = await context.Users.FindAsync(e.Author.Id.ToDbLong()); await user.RemoveCurrencyAsync(context, null, bet); } BlackjackManager bm = new BlackjackManager(); IDiscordMessage message = await bm.CreateEmbed(e).SendToChannel(e.Channel); CommandHandler c = new CommandHandlerBuilder(Bot.instance.Events) .AddPrefix("") .SetOwner(e.message) .AddCommand( new RuntimeCommandEvent("hit") .Default(async(ec) => await OnBlackjackHit(ec, bm, message, bet))) .AddCommand( new RuntimeCommandEvent("stand") .SetAliases("knock", "stay", "stop") .Default(async(ec) => await OnBlackjackHold(ec, bm, message, bet)) ).Build(); Bot.instance.Events.AddPrivateCommandHandler(e.message, c); }
private async Task OnMention(IDiscordMessage e) { foreach (RuntimeCommandEvent ev in Events.MentionEvents.Values) { await ev.Check(e, null); } }
private async Task <UserMarriedTo> SelectMarriageAsync(EventContext e, MikiContext context, List <UserMarriedTo> marriages) { EmbedBuilder embed = new EmbedBuilder() { Title = "💔 Select marriage to divorce", Description = "Please type in the number of which marriage you want to divorce.", Color = new Color(231, 90, 112) }; var m = marriages.OrderBy(x => x.Marriage.TimeOfMarriage); StringBuilder builder = new StringBuilder(); for (int i = 0; i < m.Count(); i++) { builder.AppendLine($"`{(i+1).ToString().PadLeft(2)}:` {await User.GetNameAsync(context, m.ElementAt(i).GetOther(e.Author.Id.ToDbLong()))}"); } embed.Description += "\n\n" + builder.ToString(); embed.ToEmbed().QueueToChannel(e.Channel); IDiscordMessage msg = await e.EventSystem.GetCommandHandler <MessageListener>().WaitForNextMessage(e.CreateSession()); if (int.TryParse(msg.Content, out int response)) { if (response > 0 && response <= marriages.Count) { return(m.ElementAt(response - 1)); } throw new Exception("This number is not listed, cancelling divorce."); } throw new Exception("This is not a number, cancelling divorce."); }
private async Task OnBlackjackHit(EventContext e, BlackjackManager bm, IDiscordMessage instanceMessage, int bet) { await e.message.DeleteAsync(); bm.player.AddToHand(bm.deck.DrawRandom()); if (bm.Worth(bm.player) > 21) { await OnBlackjackDead(e, bm, instanceMessage, bet); } else { if (bm.player.Hand.Count == 5) { await OnBlackjackHold(e, bm, instanceMessage, bet, true); return; } else if (bm.Worth(bm.player) == 21 && bm.Worth(bm.dealer) != 21) { await OnBlackjackWin(e, bm, instanceMessage, bet); return; } else if (bm.Worth(bm.dealer) == 21 && bm.Worth(bm.player) != 21) { await OnBlackjackDead(e, bm, instanceMessage, bet); return; } await bm.CreateEmbed(e).ModifyMessage(instanceMessage); } }
private async Task OnBlackjackDraw(EventContext e, BlackjackManager bm, IDiscordMessage instanceMessage, int bet) { await e.commandHandler.RequestDisposeAsync(); User user; using (var context = new MikiContext()) { user = await context.Users.FindAsync(e.Author.Id.ToDbLong()); if (user != null) { await user.AddCurrencyAsync(bet, e.Channel); await context.SaveChangesAsync(); } } await bm.CreateEmbed(e) .SetAuthor(e.GetResource("miki_blackjack_draw_title") + " | " + e.Author.Username, e.Author.AvatarUrl, "https://patreon.com/mikibot") .SetDescription(e.GetResource("blackjack_draw_description") + "\n" + e.GetResource("miki_blackjack_current_balance", user.Currency)) .ModifyMessage(instanceMessage); }
public static async Task <User> CreateAsync(IDiscordMessage e) { User user = new User() { Id = e.Author.Id.ToDbLong(), Currency = 0, AvatarUrl = "default", HeaderUrl = "default", DateCreated = DateTime.Now, LastDailyTime = Utils.MinDbValue, MarriageSlots = 5, Name = e.Author.Username, Title = "", Total_Commands = 0, Total_Experience = 0, Reputation = 0, LastReputationGiven = Utils.MinDbValue }; using (var context = new MikiContext()) { context.Users.Add(user); await context.SaveChangesAsync(); } return(user); }
public async Task PingAsync(EventContext e) { IDiscordMessage message = await e.CreateEmbedBuilder() .WithTitle(new StringResource("Ping")) .WithDescription("ping_placeholder") .Build() .SendToChannel(e.Channel); await Task.Delay(100); if (message != null) { float ping = (float)(message.Timestamp - e.message.Timestamp).TotalMilliseconds; DiscordEmbed embed = new EmbedBuilder() .SetTitle("Pong - " + Environment.MachineName) .SetColor(Color.Lerp(new Color(0.0f, 1.0f, 0.0f), new Color(1.0f, 0.0f, 0.0f), Math.Min(ping / 1000, 1f))) .AddInlineField("Miki", ping + "ms").ToEmbed(); await message.EditAsync(new EditMessageArgs { content = "", embed = embed }); } }
public async Task LevelUpGlobalAsync(IDiscordMessage e, int l) { if (OnGlobalLevelUp != null) { await OnGlobalLevelUp.Invoke(e.Author, await e.GetChannelAsync(), l); } }
private async Task <bool> CheckIdentifier(string message, string identifier, IDiscordMessage e) { if (message.StartsWith(identifier)) { string command = message.Substring(identifier.Length).Split(' ')[0].ToLower(); if (events.CommandEvents.ContainsKey(command)) { if (await events.CommandEvents[command].IsEnabled(e.Channel.Id)) { if (GetUserAccessibility(e) >= events.CommandEvents[command].Accessibility) { Task.Run(() => events.CommandEvents[command].Check(e, identifier)); return(true); } } } else if (aliases.ContainsKey(command)) { if (await events.CommandEvents[aliases[command]].IsEnabled(e.Channel.Id)) { if (GetUserAccessibility(e) >= events.CommandEvents[aliases[command]].Accessibility) { Task.Run(() => events.CommandEvents[aliases[command]].Check(e, identifier)); return(true); } } } return(false); } return(false); }
public async Task StartAsync(IDiscordChannel channel) { message = await Root.Build().SendToChannel(channel); (Root as BaseItem).SetMenu(this); (Root as BaseItem).SetParent(null); await Root.SelectAsync(); }
public MessageContext(string _prefix, IDiscordMessage _message) { Message = _message; var commandList = _message.Content.Substring(_prefix.Length, _message.Content.Length - 1).Split(" "); Command = commandList [0].ToLower(); Arg = commandList.Skip(1).ToArray(); }
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member 'MiddlewareStage.CheckAsync(IDiscordMessage, IMutableContext, Func<ValueTask>)' public ValueTask CheckAsync(IDiscordMessage data, IMutableContext e, Func <ValueTask> next) #pragma warning restore CS1591 // Missing XML comment for publicly visible type or member 'MiddlewareStage.CheckAsync(IDiscordMessage, IMutableContext, Func<ValueTask>)' { if (fn != null) { return(fn(data, e, next)); } return(default);
public async Task SetupNotificationsInteractive <T>(EventContext e, DatabaseSettingId settingId) { List <string> options = Enum.GetNames(typeof(T)) .Select(x => x.ToLower() .Replace('_', ' ')) .ToList(); string settingName = settingId.ToString().ToLower().Replace('_', ' '); var sEmbed = SettingsBaseEmbed; sEmbed.Description = ($"What kind of {settingName} do you want"); sEmbed.AddInlineField("Options", string.Join("\n", options)); var sMsg = await sEmbed.ToEmbed().SendToChannel(e.Channel); int newSetting; IDiscordMessage msg = null; while (true) { msg = await e.EventSystem.GetCommandHandler <MessageListener>().WaitForNextMessage(e.CreateSession()); if (Enum.TryParse <LevelNotificationsSetting>(msg.Content.Replace(" ", "_"), true, out var setting)) { newSetting = (int)setting; break; } await sMsg.EditAsync(new EditMessageArgs() { embed = e.ErrorEmbed("Oh, that didn't seem right! Try again") .AddInlineField("Options", string.Join("\n", options)) .ToEmbed() }); } sMsg = await SettingsBaseEmbed .SetDescription("Do you want this to apply for every channel? say `yes` if you do.") .ToEmbed().SendToChannel(e.Channel as IDiscordGuildChannel); msg = await e.EventSystem.GetCommandHandler <MessageListener>().WaitForNextMessage(e.CreateSession()); bool global = (msg.Content.ToLower()[0] == 'y'); await SettingsBaseEmbed .SetDescription($"Setting `{settingName}` Updated!") .ToEmbed().SendToChannel(e.Channel as IDiscordGuildChannel); if (!global) { await Setting.UpdateAsync(e.Channel.Id, settingId, newSetting); } else { await Setting.UpdateGuildAsync(e.Guild, settingId, newSetting); } }
private async Task OnBlackjackHold(EventContext e, BlackjackManager bm, IDiscordMessage instanceMessage, int bet, bool charlie = false) { bm.dealer.Hand.ForEach(x => x.isPublic = true); if (!charlie) { IDiscordGuildUser me = await e.Guild.GetSelfAsync(); //if (me.GetPermissions(e.Channel as IDiscordGuildUser).Has(ChannelPermission.ManageMessages)) //{ // await e.message.DeleteAsync(); //} } while (true) { if (bm.Worth(bm.dealer) >= Math.Max(bm.Worth(bm.player), 17)) { if (charlie) { if (bm.dealer.Hand.Count == 5) { if (bm.Worth(bm.dealer) == bm.Worth(bm.player)) { await OnBlackjackDraw(e, bm, instanceMessage, bet); return; } await OnBlackjackDead(e, bm, instanceMessage, bet); return; } } else { if (bm.Worth(bm.dealer) == bm.Worth(bm.player)) { await OnBlackjackDraw(e, bm, instanceMessage, bet); return; } await OnBlackjackDead(e, bm, instanceMessage, bet); return; } } bm.dealer.AddToHand(bm.deck.DrawRandom()); if (bm.Worth(bm.dealer) > 21) { await OnBlackjackWin(e, bm, instanceMessage, bet); return; } } }
static async Task OnMessageReceived(IDiscordMessage message) { if (message.Content == "ping") { var channel = await message.GetChannelAsync(); await channel.SendMessageAsync("pong!"); } }
private async Task Bot_MessageReceived(IDiscordMessage arg) { DogStatsd.Increment("messages.received"); if (arg.Content.StartsWith($"<@!{Global.CurrentUser.Id}>") || arg.Content.StartsWith($"<@{Global.CurrentUser.Id}>")) { string msg = (await Locale.GetLanguageInstanceAsync(arg.ChannelId)).GetString("miki_join_message"); (await arg.GetChannelAsync()).QueueMessageAsync(msg); } }