public List <Reaction> GetAll() { using (var db = new ReactionContext()) { return(db.Reactions.ToList()); } }
public async Task ReactionAdded(ReactionContext context, SocketReaction reactionAdded) { if (!(await ValidateAsync(context, reactionAdded)) || // do we have everything we need !Game.AddVote(UserReacted.Id, PlayerVoted.Id)) { if (!UserReacted.IsBot) // we don't need to remove messages we ourselves put there { await UserReacted.SendMessageAsync($"Vote is invalid and will be ignored. You can not vote for yourself and you can only vote {Game.Mafia.Count} time{(Game.Mafia.Count > 1 ? "s" : "")}."); if (!PrivateVoting) { try { await context.Message.RemoveReactionAsync(reactionAdded.Emote, reactionAdded.User.Value); } catch (Discord.Net.HttpException) { await context.Channel.SendMessageAsync($"Vote is invalid and will be ignored. You can not vote for yourself and you can only vote {Game.Mafia.Count} time{(Game.Mafia.Count > 1 ? "s" : "")}."); await context.Channel.SendMessageAsync($"This bot needs manage message permissions to remove the reaction from above. Until this permission is given the user must remove it themselves."); } } } return; } Games.Update(Game); if (Game.Score()) { Games.Update(Game); await Output.Score(Game, Context.Channel); } }
/// <summary> /// コンストラクタ /// </summary> public ReactionsController() { using (var db = new ReactionContext()) { db.Initialize(); } }
public async Task ReactionAdded(ReactionContext context, SocketReaction reactionAdded) { if (!(await ValidateAsync(context, reactionAdded)) || // do we have everything we need !Game.AddVote(UserReacted.Id, PlayerVoted.Id)) { if (!UserReacted.IsBot) // we don't need to remove messages we ourselves put there { if (PrivateVoting) { await context.Channel.SendMessageAsync($"Vote is invalid and will be ignored. You can not vote for yourself and you can only vote {Game.Mafia.Count} times."); } else { await context.Message.RemoveReactionAsync(reactionAdded.Emote, reactionAdded.User.Value); } } return; } Games.Update(Game); if (Game.Score()) { Games.Update(Game); await Output.Score(Game, Context.Channel); } }
private async Task <bool> Validate(ReactionContext context, SocketReaction reaction) { if (context == null || reaction == null || !reaction.User.IsSpecified) { return(false); } Context = context; UserReacted = reaction.User.Value; if (UserReacted.IsBot || UserReacted.IsWebhook) { return(false); } Games = Context.Database.GetCollection <Game>(); ReactionHandlers = context.Database.GetCollection <IReactionHandler>(); Game = await Game.GetGameAsync(this.GameId, Context.Client, Games); if (UserReacted.Id != Game.HostId) { return(false); } return(true); }
public async Task ClearEmoji(CommandContext c) { if (c.Guild == null) { throw new InvalidOperationException("You cannot modify emojis in a DM."); } InteractivityModule i = c.Client.GetInteractivityModule(); IReadOnlyList <DiscordGuildEmoji> emojis = await c.Guild.GetEmojisAsync(); if (!emojis.Any()) { await c.RespondAsync("You have no emoji on this server to remove."); return; } DiscordMessage m = await c.RespondAsync("Are you sure that you want to clear all emoji from this server?"); await m.CreateReactionAsync(Reactions.YES); await m.CreateReactionAsync(Reactions.NO); ReactionContext react = await i.WaitForReactionAsync(x => x == Reactions.YES || x == Reactions.NO, c.User, TimeSpan.FromSeconds(30)); await m.DeleteAsync(); if (react != null) { if (react.Message == m) { DiscordMessage clear = await c.RespondAsync("Alright, I'm clearing all of the emojis on this server... This will take a couple of minutes due to Discord's ratelimits."); foreach (DiscordGuildEmoji e in emojis) { try { await c.Guild.DeleteEmojiAsync(e); } catch (BadRequestException) { await c.RespondAsync("I failed to delete the emoji. Discord gave me a bad response."); return; } } await clear.ModifyAsync("I've cleared all of the emojis on this server."); } else { await c.RespondAsync("You did not react to the original message. Aborting."); return; } } else { await c.RespondAsync("No response was given. Aborting."); } }
public async Task <Reaction> Post([FromBody] Reaction reaction) { using (var db = new ReactionContext()) { db.Reactions.Add(reaction); await db.SaveChangesAsync(); return(reaction); } }
public async Task ReactionAdded(ReactionContext context, SocketReaction reaction) { if (!(await Validate(context, reaction))) { if (!UserReacted.IsBot) // we don't need to remove messages we ourselves put there { await Context.Message.RemoveReactionAsync(new Emoji(reaction.Emote.Name), reaction.User.Value); } return; } switch (reaction.Emote.Name) // Which reaction was clicked? { case Output.OrangeEmoji: await SelectWinningTeamAsync(Team.Orange); break; case Output.BlueEmoji: await SelectWinningTeamAsync(Team.Blue); break; case Output.OvertimeEmoji: Game.OvertimeReached = true; Games.Update(Game); break; case Output.EndedEmoji: if (Game.WinningTeam == null) // if we don't have a winner remove emoji and return { await Context.Message.RemoveReactionAsync(new Emoji(Output.EndedEmoji), UserReacted); return; } // Un-register this message for receiving new reactions ReactionHandlers.Delete(u => u.MsgId == this.MsgId); // Output voting notification message var votingMessages = await Output.StartVoting(Game, Context.Channel, VotingHandler.PrivateVoting); Games.Update(Game); // Update so we store emojis on user // Register new message for receiving reactions foreach (var votingMessage in votingMessages) { ReactionHandlers.Insert(new VotingHandler() { MsgId = votingMessage.Id, GameId = Game.Id }); } break; } }
Task HandleReactionAsync(IMessageChannel channel, SocketReaction reaction, ReactionEvent eventType) { if (reaction.UserId != _discord.CurrentUser.Id) { _ = Task.Run(async() => { // retrieve message if (!(await channel.GetMessageAsync(reaction.MessageId) is IUserMessage message)) { return; } // retrieve user if (!(await channel.GetUserAsync(reaction.UserId) is IUser user)) { return; } // create context var context = new ReactionContext { Client = _discord, Message = message, User = user, GuildSettings = _guildSettingsCache[message.Channel], Reaction = reaction, Event = eventType }; try { foreach (var handler in _reactionHandlers) { if (await handler.TryHandleAsync(context)) { HandledReactions.Increment(); break; } } } catch (Exception e) { await _errorReporter.ReportAsync(e, context, false); } finally { ReceivedReactions.Increment(); } }); } return(Task.CompletedTask); }
public async Task <Reaction> Update(int id, [FromBody] Reaction newReaction) { using (var db = new ReactionContext()) { var oldReaction = db.Reactions.Single(reaction => reaction.Id == id); oldReaction.Word = newReaction.Word; oldReaction.Emoji = newReaction.Emoji; await db.SaveChangesAsync(); return(oldReaction); } }
public async Task ReactionRemoved(ReactionContext context, SocketReaction reactionRemoved) { if (!(await ValidateAsync(context, reactionRemoved))) { return; } Game.RemoveVote(reactionRemoved.UserId, PlayerVoted.Id); Games.Update(Game); return; }
private async Task ReactionAction ( Cacheable <IUserMessage, ulong> userMessage, ISocketMessageChannel messageChannel, SocketReaction reaction, ReactionType reactionType ) { using (var scope = _services.CreateScope()) { var registry = scope.ServiceProvider.GetService <ReactionModuleRegistry>(); if (registry == null) { _logger.LogWarning($"{nameof(ReactionModuleRegistry)} ist nicht konfiguriert"); return; } var types = registry.GetRegisteredTypes(reaction.Emote.Name); if (!types.Any()) { return; } var context = new ReactionContext(userMessage, messageChannel, reaction, reactionType); foreach (var type in types) { if (!(scope.ServiceProvider.GetService(type) is ReactionModuleBase module)) { _logger.LogWarning($"Ungültiger Typ in {nameof(ReactionModuleRegistry)} gefunden: '{type.FullName}'."); continue; } module.Context = context; try { if (await module.ExecuteAsync()) { return; } } catch (Exception e) { _logger.LogCritical(e, $"ReactionHandler '{module.GetType().FullName}' hat eine Exception zurückgegeben."); throw; } } } }
public async Task <IActionResult> Delete(int id) { using (var db = new ReactionContext()) { var deleteReaction = db.Reactions.FirstOrDefault(reaction => reaction.Id == id); if (deleteReaction != null) { db.Reactions.Remove(deleteReaction); await db.SaveChangesAsync(); return(Ok()); } else { return(NotFound()); } } }
private async Task Comandos_CommandErrored(CommandErrorEventArgs e) { try { DiscordEmoji emoji; bool rota = false; //ReactionsController<CommandContext> controller = new ReactionsController<CommandContext>(e.Context); if (e.Exception is CommandNotFoundException) { emoji = DiscordEmoji.FromUnicode("❓"); await e.Context.Message.CreateReactionAsync(emoji); rota = true; //controller.AddReactionEvent(e.Context.Message, controller.ConvertToMethodInfo(CallHelpNofing), emoji, e.Context.User); } else { emoji = DiscordEmoji.FromUnicode("❌"); await e.Context.Message.CreateReactionAsync(emoji); //controller.AddReactionEvent(e.Context.Message, controller.ConvertToMethodInfo<string>(CallHelp), emoji, e.Context.User, e.Command.QualifiedName); e.Context.Client.DebugLogger.LogMessage(LogLevel.Error, "Kurosawa Dia - Handler", e.Exception.ToString(), DateTime.Now); } ReactionContext recebimento = await e.Context.Client.GetInteractivityModule().WaitForMessageReactionAsync(predicate: x => x == emoji, user: e.Context.User, message: e.Context.Message); if (recebimento != null) { if (rota) { await new Ajuda().AjudaCmd(e.Context); } else { await e.Context.Client.GetCommandsNext().DefaultHelpAsync(e.Context, e.Command.QualifiedName); } } } catch (Exception ex) { e.Context.Client.DebugLogger.LogMessage(LogLevel.Error, "Kurosawa Dia - Handler", ex.ToString(), DateTime.Now); } }
private async Task <bool> ValidateAsync(ReactionContext context, SocketReaction reaction) { if (context == null || reaction == null || !reaction.User.IsSpecified) { return(false); } Context = context; UserReacted = reaction.User.Value; if (UserReacted.IsBot || UserReacted.IsWebhook) { return(false); } Games = Context.Database.GetCollection <Game>(); Game = await Game.GetGameAsync(this.GameId, Context.Client, Games); PlayerVoted = Game.Players.Where(p => p.Value.Emoji == reaction.Emote.Name).First().Value; return(true); }
public async Task ReactionRemoved(ReactionContext context, SocketReaction reaction) { if (!(await Validate(context, reaction))) { return; } var blueCount = Context.Message.Reactions.Where(e => e.Key.Name == Output.BlueEmoji).First().Value.ReactionCount; var orangeCount = Context.Message.Reactions.Where(e => e.Key.Name == Output.OrangeEmoji).First().Value.ReactionCount; if (blueCount + orangeCount == 2) { Game.WinningTeam = null; } if (reaction.Emote.Name == Output.OvertimeEmoji) { Game.OvertimeReached = false; } Games.Update(Game); return; }
public async Task CheckReaction(Cacheable <IUserMessage, ulong> cachedMessage, ISocketMessageChannel channel, SocketReaction reaction) { if ((reaction.User.IsSpecified && reaction.User.Value.IsBot) || !(channel is IGuildChannel)) { return; //Makes sure it's not logging a message from a bot and that it's in a discord server } SocketGuildChannel chnl = channel as SocketGuildChannel; SocketGuild guild = chnl?.Guild; if (guild == null) { return; } try { //Needed to do our own get instead of cachedMessage.GetOrDownloadAsync() because this can be ISystenMessage and not just IUserMessage IMessage message = await channel.GetMessageAsync(cachedMessage.Id); ReactionContext context = new ReactionContext(client, message); var settings = guild.LoadFromFile <FilterSettings>(false); SocketGuildUser gUser = guild.GetUser(reaction.UserId); if (settings?.badUEmojis?.Count == null || settings.badUEmojis.Count == 0 || (reaction.User.Value as SocketGuildUser).HasAdmin() || reaction.User.Value.IsBot) { return; } if (settings.badUEmojis.Contains(reaction.Emote.Name)) { await message.RemoveAllReactionsForEmoteAsync(reaction.Emote); await context.FilterPunish(gUser, $"bad reaction used ({reaction.Emote.Name})", guild.LoadFromFile <ModerationSettings>(), settings, null, delete : false, warnSize : 1); } } catch (Exception e) { await e.LogFilterError("reaction", guild); } }
public async Task Post() { var form = await Request.ReadFormAsync(); if (form["token"].Equals(webhookToken)) { using (var db = new ReactionContext()) { var text = form["text"].ToString(); foreach (var reaction in db.Reactions.Where(reaction => text.Contains(reaction.Word))) { var client = new HttpClient(); var content = new FormUrlEncodedContent(new Dictionary <string, string>() { { "token", xoxpToken }, { "name", reaction.Emoji }, { "channel", form["channel_id"] }, { "timestamp", form["timestamp"] } }); await client.PostAsync("https://slack.com/api/reactions.add", content); } } } }
private async Task ReactionAdded(Cacheable <IUserMessage, ulong> userMessage, ISocketMessageChannel messageChannel, SocketReaction reaction) { using (var scope = _services.CreateScope()) { var registry = scope.ServiceProvider.GetService <ReactionModuleRegistry>(); if (registry == null) { _logger.LogWarning($"The {nameof(ReactionModuleRegistry)} is unconfigured"); return; } var types = registry.GetRegisteredTypes(reaction.Emote.Name); if (!types.Any()) { return; } var context = new ReactionContext(userMessage, messageChannel, reaction); foreach (var type in types) { if (!(scope.ServiceProvider.GetService(type) is ReactionModuleBase module)) { _logger.LogWarning($"Invalid type in {nameof(ReactionModuleRegistry)} found: '{type.FullName}'"); continue; } module.Context = context; if (await module.ExecuteAsync()) { return; } } } }
public async Task AddEmoji(CommandContext c, [Description("Name of the emoji to add")] string name, [Description("Optional name override")] string nameOverride = null) { if (c.Guild == null) { throw new InvalidOperationException("You cannot modify emojis in a DM."); } InteractivityModule i = c.Client.GetInteractivityModule(); Emoji emoji = Emoji.FromName(name); if (emoji == null) { await c.RespondAsync("No emoji by that name was found on DiscordEmoji." + "\nPlease select a valid emoji from the catalog at https://discordemoji.com" + "\n\n(The emoji name is case sensitive. Don't include the colons in your command!)" + "\n\n If you're too lazy to go on the website, you can use the ``emojis`` command to list emojis." + $"\n``{EmojiButler.Configuration.Prefix}emojis <category> <page (Optional)>``"); return; } if (!c.Channel.IsNSFW && emoji.GetCategoryName() == "NSFW") { await c.RespondAsync("Woah, that's an NSFW emoji. Use this command in an NSFW channel."); return; } string addedName = nameOverride ?? emoji.Title; var allEmoji = await c.Guild.GetEmojisAsync(); if (allEmoji.Count(x => !x.IsAnimated) >= 50 && emoji.GetCategoryName() != "Animated") { await c.RespondAsync("It seems like you already have 50 emojis. That's the limit. Remove some before adding more."); return; } if (allEmoji.Count(x => x.IsAnimated) >= 50 && emoji.GetCategoryName() == "Animated") { await c.RespondAsync("It seems like you already have 50 *animated* emojis. That's the limit. Remove some before adding more."); return; } DiscordGuildEmoji conflictingEmoji = (allEmoji.FirstOrDefault(x => x.Name == addedName)); if (conflictingEmoji != null) { DiscordEmbedBuilder overwrite = new DiscordEmbedBuilder { Title = "Overwrite Confirmation", Description = $"An emoji that currently exists on this server that" + " has a conflicting name with the emoji that you are attempting to add.\nOverwrite? This will delete the emoji. React in less than 30 seconds to confirm.", ThumbnailUrl = $"https://cdn.discordapp.com/emojis/{conflictingEmoji.Id}.png" }; overwrite.AddField("Name", conflictingEmoji.Name); DiscordMessage overwriteConfirm = await c.RespondAsync(embed : overwrite); await overwriteConfirm.CreateReactionAsync(Reactions.YES); await overwriteConfirm.CreateReactionAsync(Reactions.NO); ReactionContext overwriteReact = await i.WaitForReactionAsync(x => x == Reactions.YES || x == Reactions.NO, c.User, TimeSpan.FromSeconds(30)); await overwriteConfirm.DeleteAsync(); if (overwriteReact != null) { if (overwriteReact.Message == overwriteConfirm) { if (overwriteReact.Emoji == Reactions.NO) { await c.RespondAsync("Alright, I won't add the emoji."); return; } try { await c.Guild.DeleteEmojiAsync(conflictingEmoji); } catch (Exception e) { if (e is RatelimitTooHighException exr) { await c.RespondAsync($"I couldn't process the request due to the extreme ratelimits Discord has placed on emoji management. Try again in {(int)exr.RemainingTime.TotalMinutes} minute(s)."); return; } else if (e is NotFoundException) /*Emoji doesn't exist anymore, ignore.*/ } { } } else { await c.RespondAsync("You did not react to the original message. Aborting."); return; } } else { await c.RespondAsync("No response was given. Aborting."); return; } } DiscordEmbedBuilder embed = new DiscordEmbedBuilder { Title = "Confirmation", Description = "Are you sure that you want to add this emoji to your server?" + "\nReact in less than 30 seconds to confirm.", ThumbnailUrl = emoji.Image }; embed.AddField("Name", emoji.Title); if (nameOverride != null) { embed.AddField("Name Override", addedName); } embed.AddField("Author", emoji.Author); DiscordMessage m = await c.RespondAsync(embed : embed); await m.CreateReactionAsync(Reactions.YES); await m.CreateReactionAsync(Reactions.NO); ReactionContext react = await i.WaitForReactionAsync(x => x == Reactions.YES || x == Reactions.NO, c.User, TimeSpan.FromSeconds(30)); await m.DeleteAsync(); if (react != null) { if (react.Message == m) { if (react.Emoji == Reactions.YES) { DiscordMessage resp = await c.RespondAsync("Adding emoji..."); try { using (Stream s = await emoji.GetImageAsync()) await c.Guild.CreateEmojiAsync(addedName, s, null, $"Added by {c.User.Username}"); } catch (Exception e) { if (e is BadRequestException) { await resp.ModifyAsync("I failed to upload the requested emoji to Discord. It was probably too big, or you selected an invalid name override."); return; } else if (e is RatelimitTooHighException exr) { await c.RespondAsync($"I couldn't process the request due to the extreme ratelimits Discord has placed on emoji management. Try again in {(int)exr.RemainingTime.TotalMinutes} minute(s)."); return; } } await resp.ModifyAsync("", new DiscordEmbedBuilder { Title = "Success!", Description = $"You've added :{addedName}: to your server.", ThumbnailUrl = emoji.Image }); } else if (react.Emoji == Reactions.NO) { await c.RespondAsync("Okay then, I won't be adding that emoji."); } } else { await c.RespondAsync("You did not react to the original message. Aborting."); return; } } else { await c.RespondAsync("No response was given. Aborting."); } }
public Task ReactionsCleared(ReactionContext context) { return(Task.CompletedTask); }
public Task ReactionsCleared(ReactionContext context) // Should we do anything here? { return(Task.CompletedTask); }