public async Task React(ulong msgid, string emotestring) { Console.WriteLine(emotestring); IMessage msg = Context.Channel.GetMessageAsync(msgid).Result; if (msg != null) { if (Emote.TryParse(emotestring, out Emote emote)) { await msg.AddReactionAsync(emote); await ReplyAndDeleteAsync("Done!"); } else { try { await msg.AddReactionAsync(new Emoji(emotestring)); await ReplyAndDeleteAsync("Done!"); } catch (Exception) { await ReplyAndDeleteAsync("Failed to get emoji"); } } } else { await ReplyAndDeleteAsync("Failed to get message."); } }
public async Task AddQueueReactions(IMessage msg) { await msg.AddReactionAsync(new Emoji("\U000023EE")); await msg.AddReactionAsync(new Emoji("\U000025C0")); await msg.AddReactionAsync(new Emoji("\U000025B6")); await msg.AddReactionAsync(new Emoji("\U000023ED")); }
public static async Task DenyMessage(IMessage message) { if (Emote.TryParse("<:frogthumbsdown:733751715098001509>", out var emote)) { await message.AddReactionAsync(emote); } else { await message.AddReactionAsync(new Emoji(char.ConvertFromUtf32(0x1F44E))); } }
private async Task AddVoteEmotes(IMessage msg) { await msg.AddReactionAsync(Emote.Parse(_pairs.GetString("YES_EMOTE"))); await msg.AddReactionAsync(Emote.Parse(_pairs.GetString("NO_EMOTE"))); await msg.AddReactionAsync(Emote.Parse(_pairs.GetString("ABSTAIN_EMOTE"))); // I swear to god, since when are there 2 different eye emojis? // await msg.AddReactionAsync(new Emoji("👁️")); This one doesn't work, I think await msg.AddReactionAsync(new Emoji("👁")); }
/// <summary> /// Adds multiple reactions to a message. /// </summary> /// <param name="message">The message to add reactions to</param> /// <param name="reactions">The reactions to add</param> /// <returns>A Task when all reactions have been added.</returns> public static async Task AddReactionsAsync(this IMessage message, IEnumerable <IEmote> reactions) { foreach (var reaction in reactions) { await message.AddReactionAsync(reaction); } }
private async Task AddReactionIfMissing(IMessage msg, string emoji) { foreach (var existingEmoji in msg.Reactions.Keys) { if (existingEmoji.Name == emoji) { return; } } IEmote e = null; if (!emoji.Contains(":")) { e = new Emoji(emoji); } else { if (Emote.TryParse(emoji, out Emote e2)) { e = e2; } else { Console.WriteLine("Cannot add reaction " + emoji); return; } } if (e != null) { await msg.AddReactionAsync(e); } }
public static async Task CreateReactions(IMessage message) { foreach (var item in emojis) { await message.AddReactionAsync(item); } }
private async Task InitializeTrigger(IMessage message) { if (!message.Content.StartsWith("`")) { await message.AddReactionAsync(subscribeEmoji); await UpdateMessageRoles(message); } }
public async Task <string> AddReactRole(SocketGuild guild, IMessage message, Emote emote, Emoji emoji, SocketRole role, string group = "") { if (emote != null) { await message.AddReactionAsync(emote); } else { await message.AddReactionAsync(emoji); } if (!guildsDefinition.reactRoles.ContainsKey(guild.Id)) { guildsDefinition.reactRoles.Add(guild.Id, new Dictionary <string, List <ReactRolesDefinition> >()); } if (!guildsDefinition.reactRoles[guild.Id].ContainsKey(group)) { guildsDefinition.reactRoles[guild.Id].Add(group, new List <ReactRolesDefinition>()); } if (guildsDefinition.reactRoles[guild.Id][group].FirstOrDefault(x => x.messageID == message.Id && x.role == role.Name && (x.emoji == emote.ToString() || x.emoji == emoji.ToString())) != null) { return("Role assignment already exist on that message for that emote."); } guildsDefinition.reactRoles[guild.Id][group].Add(new ReactRolesDefinition(message.Id, emote != null ? emote.ToString() : emoji.ToString(), role.Name)); if (emote != null) { return($"Got it! {emote.ToString()} will assign to role {role.Name}."); } else { return($"Got it! {emoji.ToString()} will assign to role {role.Name}."); } }
private async Task ReactWithSentiment(IMessage message, SentimentResult?score = null) { var result = score ?? await _sentiment.Predict(message.Content); if (result.ClassificationScore < _config.CertaintyThreshold) { await message.AddReactionAsync(new Emoji(EmojiLookup.Confused)); } var emoji = result.Classification switch { Moe.Services.Sentiment.Sentiment.Positive => EmojiLookup.ThumbsUp, Moe.Services.Sentiment.Sentiment.Neutral => EmojiLookup.Expressionless, Moe.Services.Sentiment.Sentiment.Negative => EmojiLookup.ThumbsDown, _ => null }; if (emoji != null) { await message.AddReactionAsync(new Emoji(emoji)); } }
public static async Task ReactionAdd(DiscordChannelMessage dMessage, string emoteName) { if (Program.DiscordClient.ConnectionState != ConnectionState.Connected) { return; } IMessage message = await(Program.DiscordClient.GetChannel(dMessage.ChannelID) as ISocketMessageChannel).GetMessageAsync(dMessage.MessageID); GuildEmote emote; // Check if emote is unicode if (Char.IsSurrogate(emoteName, 0)) { // Resolve Unicode to emote object Emoji heartEmoji = new Emoji(emoteName); await message.AddReactionAsync(heartEmoji); } else { // resolve custom emote string[] parts = emoteName.Split(':'); emote = (message.Channel as SocketGuildChannel).Guild.Emotes.FirstOrDefault(x => x.Name == parts[1]); await message.AddReactionAsync(emote); } }
public async Task GetEmbeds(IMessage message, int index) { if (!Enabled) { return; } byte i = 0; var react = false; var tasks = new Task[message.Embeds.Count]; foreach (var embed in message.Embeds) { var uri = new Uri(embed.Url); var info = new FileInfo(uri.LocalPath); switch (info.Extension.ToLower()) { case ".jpg": case ".jpeg": case ".gif": case ".png": logger.LogInformation($"Downloaded {uri} from {message.Author.Username} <#{message.Author.Id}>"); tasks[i++] = Get(uri, index); react = true; break; default: tasks[i++] = Task.FromResult <object>(null); break; } } Task.WaitAll(tasks); try { if (react) { await message.AddReactionAsync(Check); } } catch (Exception e) { logger.LogError(e, e.Message); } }
static public async Task <DisposableReaction> CreateAsync(IMessage message, IEmote emote, IUser botUser) { if (message == null) { throw new ArgumentNullException(nameof(message)); } if (emote == null) { throw new ArgumentNullException(nameof(emote)); } if (botUser == null) { throw new ArgumentNullException(nameof(botUser)); } await message.AddReactionAsync(emote); return(new DisposableReaction(message, emote, botUser)); }
private async Task sendErrorMessage(string problem, IMessage userMessage = null) { if (userMessage != null) { try { await userMessage.AddReactionAsync(new Emoji("❌")); } catch (Exception) { /* Oh well, what can you do. */ } } if (client.GetChannel(client.config.errorChannelId) is IMessageChannel errorChannel) { try { await errorChannel.SendMessageAsync(problem); return; } catch (Exception) { /* Go back! */ } } await Console.Error.WriteLineAsync(problem); }
public async Task AddReactAsync(ulong channelId, ulong messageId, string emoji) { IMessage msg = await Context.Bot.GetMessageAsync(channelId, messageId); if (msg == null) { await Response("Message not found"); return; } try { await msg.AddReactionAsync(ReactService.ParseEmojiString(emoji)); await Response("React added"); } catch { await Response("Failed adding react to message"); } }
public static async Task AddReactionsAsync(this IMessage message, CancellationToken cancellationToken, params Emotes[] emotes) { var errorCount = 0; for (int i = 0; i < emotes.Length;) { var emote = emotes[i]; try { await message.AddReactionAsync( EmotesHelper.GetEmoji(emote), new RequestOptions() { CancelToken = cancellationToken, RetryMode = RetryMode.AlwaysRetry } ).ConfigureAwait(false); i++; errorCount = 0; } catch (Exception ex) { if (errorCount > 2) { Log.Warn($"AddReactionsAsync: Skipping {i}:{emote}"); i++; } else { if (!(ex is RateLimitedException)) { Log.Error($"AddReactionsAsync, {i}:{emote} | {ex}"); errorCount++; } } } } }
public async Task OnReactionAdded( Cacheable <IUserMessage, ulong> cacheable, ISocketMessageChannel socketMessageChannel, SocketReaction socketReaction) { ObservedVoiceChannelOptions observedVoiceChannelOptions = _observedVoiceChannelOptionsMonitor.CurrentValue; string emoteName = socketReaction.Emote.Name; bool emoteIsMutedEmoji = emoteName == observedVoiceChannelOptions.MutedEmoji; bool emoteIsUnMutedEmoji = emoteName == observedVoiceChannelOptions.UnMutedEmoji; if (emoteIsMutedEmoji || emoteIsUnMutedEmoji) { ObservedVoiceChannel observedVoiceChannel = _observedVoiceChannelsCache.Values.FirstOrDefault(currentObservedVoiceChannel => currentObservedVoiceChannel.MessageId == socketReaction.MessageId); if (observedVoiceChannel != null) { IMessage message = await socketMessageChannel.GetMessageAsync(cacheable.Id); if (message.Reactions[socketReaction.Emote].ReactionCount > 1) { SocketGuildChannel socketGuildChannel = socketMessageChannel as SocketGuildChannel; SocketVoiceChannel socketVoiceChannel = socketGuildChannel.Guild.GetVoiceChannel(observedVoiceChannel.VoiceChannelId); IVoiceChannel voiceChannel = socketVoiceChannel as IVoiceChannel; IEnumerable <IGuildUser> voiceChannelUsers = await voiceChannel .GetUsersAsync() .FlattenAsync(); Emoji mutedEmoji = new Emoji(observedVoiceChannelOptions.MutedEmoji); Emoji unMutedEmoji = new Emoji(observedVoiceChannelOptions.UnMutedEmoji); if (observedVoiceChannel.IsMuted && emoteIsUnMutedEmoji) { List <Task> tasks = voiceChannelUsers .Where(voiceChannelUser => { SocketGuildUser socketGuildUser = voiceChannelUser as SocketGuildUser; bool userIsMuted = socketGuildUser.VoiceState?.IsMuted == true; bool userNotOffline = socketGuildUser.Status != UserStatus.Offline; return(userIsMuted && userNotOffline); }) .Select(voiceChannelUser => voiceChannelUser.ModifyAsync(guildUserProperties => guildUserProperties.Mute = false)) .ToList(); tasks.Add(message.RemoveAllReactionsForEmoteAsync(unMutedEmoji)); tasks.Add(message.AddReactionAsync(mutedEmoji)); await Task.WhenAll(tasks); observedVoiceChannel.IsMuted = false; } else if (!observedVoiceChannel.IsMuted && emoteIsMutedEmoji) { List <Task> tasks = voiceChannelUsers .Where(voiceChannelUser => { SocketGuildUser socketGuildUser = voiceChannelUser as SocketGuildUser; bool userNotMuted = socketGuildUser.VoiceState?.IsMuted == false; bool userNotOffline = socketGuildUser.Status != UserStatus.Offline; return(userNotMuted && userNotOffline); }) .Select(voiceChannelUser => voiceChannelUser.ModifyAsync(guildUserProperties => guildUserProperties.Mute = true)) .ToList(); tasks.Add(message.RemoveAllReactionsForEmoteAsync(mutedEmoji)); tasks.Add(message.AddReactionAsync(unMutedEmoji)); await Task.WhenAll(tasks); observedVoiceChannel.IsMuted = true; } } } } }
public static async Task ConfirmMessage(IMessage message) { await message.AddReactionAsync(new Emoji(char.ConvertFromUtf32(0x1F44D))); }
public async Task <int> WaitForMove(IMessage msg) // return StPos, -1 if no reply { var emo_up = new Emoji(Puzzle.ArrowUp); var emo_down = new Emoji(Puzzle.ArrowDown); var emo_left = new Emoji(Puzzle.ArrowLeft); var emo_right = new Emoji(Puzzle.ArrowRight); var emo_pause = new Emoji("\u23F8\uFE0F"); Puzzle puzzle = Load(); int EnPos = puzzle.EmptySqrPos; //up if (puzzle.IsValidMove(EnPos + Puzzle.Size, EnPos)) { await msg.AddReactionAsync(emo_up); } //down if (puzzle.IsValidMove(EnPos - Puzzle.Size, EnPos)) { await msg.AddReactionAsync(emo_down); } //left if (puzzle.IsValidMove(EnPos + 1, EnPos)) { await msg.AddReactionAsync(emo_left); } //right if (puzzle.IsValidMove(EnPos - 1, EnPos)) { await msg.AddReactionAsync(emo_right); } //pause await msg.AddReactionAsync(emo_pause); Stopwatch s = new Stopwatch(); s.Start(); while (s.Elapsed < TimeSpan.FromMinutes(3)) { //up var reactedUsers = await msg.GetReactionUsersAsync(emo_up, 5).FlattenAsync(); foreach (var user in reactedUsers) { if (user.Id == puzzle.PlayerId) { return(puzzle.EmptySqrPos + Puzzle.Size); } } //down reactedUsers = await msg.GetReactionUsersAsync(emo_down, 5).FlattenAsync(); foreach (var user in reactedUsers) { if (user.Id == puzzle.PlayerId) { return(puzzle.EmptySqrPos - Puzzle.Size); } } //left reactedUsers = await msg.GetReactionUsersAsync(emo_left, 5).FlattenAsync(); foreach (var user in reactedUsers) { if (user.Id == puzzle.PlayerId) { return(puzzle.EmptySqrPos + 1); } } //right reactedUsers = await msg.GetReactionUsersAsync(emo_right, 5).FlattenAsync(); foreach (var user in reactedUsers) { if (user.Id == puzzle.PlayerId) { return(puzzle.EmptySqrPos - 1); } } //pause reactedUsers = await msg.GetReactionUsersAsync(emo_pause, 5).FlattenAsync(); foreach (var user in reactedUsers) { if (user.Id == puzzle.PlayerId) { return(-1); } } //await Task.Delay(TimeSpan.FromMilliseconds(70)); } s.Stop(); return(-1); }
public async Task Command(ulong messageId, ITextChannel channel, string emote, IRole role, params string[] args) { IMessage message = await channel.GetMessageAsync(messageId); IEmote emoteRes; if (Emote.TryParse(emote, out Emote result)) { emoteRes = result; } else { emoteRes = new Emoji(emote); } var emoteRolePair = new Dictionary <IEmote, IRole> { { emoteRes, role } }; if (args.Any()) { // If there aren't an even amount of args, we know the user messed up. if ((args.Length % 2) != 0) { throw new KaguyaSupportException("There were an invalid amount of additional arguments provided. " + "Note that for each additional entry, there must be an " + "emote followed by a role."); } var emoteRolePairs = new string[args.Length / 2][]; int count = 0; for (int i = 0; i < args.Length; i += 2) { var rolePair = new string[2]; rolePair[0] = args[i]; rolePair[1] = args[i + 1]; emoteRolePairs[count] = rolePair; count++; } foreach (string[] pair in emoteRolePairs) { string emoteText = pair[0]; string roleText = pair[1]; bool validEmote = false; bool validRole = false; if (Emote.TryParse(emoteText, out Emote emoteResult) || pair[1].GetType() == typeof(Emoji)) { validEmote = true; } IRole roleResult = Context.Guild.Roles.FirstOrDefault(x => x.Name.ToLower() == roleText.ToLower()); if (roleResult != null) { validRole = true; } if (validEmote == false) { throw new KaguyaSupportException("Failed to parse a valid emote from the provided " + $"input: Emote: '{emoteText}'\n\n" + $"Note that the emote must be from this server only and " + $"cannot be a standard emoji."); } if (validRole == false) { throw new KaguyaSupportException("Failed to parse a valid role from the provided " + $"input: Role: '{roleText}'"); } emoteRolePair.Add(emoteResult, Context.Guild.GetRole(roleResult.Id)); } } if (message == null) { throw new KaguyaSupportException("The message with this ID could not be found in the specified channel. " + "You must specify the 'channel' argument for this command if you are " + "executing the command from another channel. \n\n" + $"Example: '{{prefix}}crr {messageId} {{#some-channel}} ...'"); } var cacheToSend = new List <ReactionRole>(emoteRolePair.Count); int cacheListIndex = 0; var respSb = new StringBuilder(); foreach (KeyValuePair <IEmote, IRole> pair in emoteRolePair) { bool isEmoji = false; IEmote pEmote = pair.Key; IRole pRole = pair.Value; ReactionRole rr; if (pEmote is Emote customEmote) { rr = new ReactionRole { EmoteNameorId = customEmote.Id.ToString(), MessageId = message.Id, RoleId = pRole.Id, ServerId = Context.Guild.Id }; } else if (pEmote is Emoji standardEmoji) { rr = new ReactionRole { EmoteNameorId = standardEmoji.Name, MessageId = message.Id, RoleId = pRole.Id, ServerId = Context.Guild.Id }; isEmoji = true; } else { throw new KaguyaSupportException("The reaction role isn't an Emoji or Emote!!"); } if (pRole.IsManaged) { throw new KaguyaSupportException($"Role '{pRole.Name}' is managed by an integration or a bot. It may not be " + "assigned to users. Therefore, they may not be assigned to " + "reaction roles either."); } ReactionRole possibleMatch; if (isEmoji) { possibleMatch = await DatabaseQueries.GetFirstMatchAsync <ReactionRole>(x => x.EmoteNameorId == pEmote.Name && x.RoleId == pRole.Id && x.MessageId == rr.MessageId); } else { possibleMatch = await DatabaseQueries.GetFirstMatchAsync <ReactionRole>(x => x.EmoteNameorId == (pEmote as Emote).Id.ToString() && x.RoleId == pRole.Id && x.MessageId == rr.MessageId); } IReadOnlyDictionary <IEmote, ReactionMetadata> messageReactions = message.Reactions; // If the reaction is in the database, and Kaguya has a emote-role pair for this emote, throw an error. if (possibleMatch != null && messageReactions.Keys.Contains(pEmote) && messageReactions.GetValueOrDefault(pEmote).IsMe) { throw new KaguyaSupportException($"The emote '{emote}' has already been assigned to role {role} " + "as a reaction role."); } try { await message.AddReactionAsync(pEmote); await DatabaseQueries.InsertAsync(rr); cacheToSend.Insert(cacheListIndex, rr); respSb.AppendLine($"Successfully linked {pEmote} to {pRole.Mention}"); } catch (Discord.Net.HttpException e) { if (e.HttpCode == HttpStatusCode.BadRequest) { throw new KaguyaSupportException($"An error occurred when attempting to make the reaction role " + $"for the '{pEmote.Name}' emote. This error occurs when Discord " + $"doesn't know how to process an emote. This can happen if you " + $"copy/paste the emote into the Discord text box instead of " + $"manually typing out the emote yourself. Discord is really " + $"finnicky when it comes to emotes."); } throw new KaguyaSupportException($"An unknown error occurred.\n\n" + $"Exception Message: {e.Message}\nInner Exception: {e.InnerException}"); } catch (Exception) { throw new KaguyaSupportException("An error occurred when inserting the reaction role " + "into the database.\n\n" + $"Emote: {pEmote}\n" + $"Role: {pRole}"); } } var embed = new KaguyaEmbedBuilder(EmbedColor.YELLOW) { Title = "Kaguya Reaction Roles", Description = respSb.ToString() }; UpdatedCache?.Invoke(cacheToSend); await SendEmbedAsync(embed); }