private async Task UserJoined(SocketGuildUser socketGuildUser) { await this._log.Info($"{socketGuildUser.Username} entrou no servidor {socketGuildUser.Guild.Name}"); var guild = socketGuildUser.Guild; var jsonNode = await JsonCache.LoadValueAsync($"GuildSettings/{guild.Id}", "joinChannelId"); if (jsonNode == null) { return; } var channelId = jsonNode.Value; if (string.IsNullOrEmpty(channelId)) { return; } var channel = guild.GetTextChannel(ulong.Parse(channelId)); if (channel == null) { return; } await channel.SendMessageAsync($"Temos uma nova pessoinha no servidor, digam **oi** para {socketGuildUser.Mention}!"); }
private async Task LogOnDiscordChannel(LogMessage msg) { //if (msg.Severity > LogSeverity.Error) return; if (msg.Severity > LogSeverity.Warning) { return; } foreach (var guild in this._discord.Guilds) { var id = await JsonCache.LoadValueAsync($"GuildSettings/{guild.Id.ToString()}", "channel-bot-logs-id"); if (id == null) { continue; } var textChannel = guild.GetTextChannel(Convert.ToUInt64(id.Value)); if (textChannel == null) { continue; } var embed = new EmbedBuilder(); embed.Color = this.GetColorByLogSeverity(msg.Severity); embed.Title = msg.Severity.ToString(); embed.Description = msg.ToString().SubstringSafe(1024); await textChannel.SendMessageAsync("", false, embed.Build()); } }
private async Task SetStatusAsync() { var statusText = Program.VERSION; try { var activitiesJsonArray = (await JsonCache.LoadValueAsync("BotStatus", "activity")).AsArray; var index = this._rand.Next(0, activitiesJsonArray.Count); var statusTextArray = activitiesJsonArray[index]["answers"].AsArray; var selectedStatus = statusTextArray[this._rand.Next(0, statusTextArray.Count)].Value; await this._discord.SetGameAsync( selectedStatus, (ActivityType)index == ActivityType.Streaming? "https://twitch.tv/chrisdbhr" : null, (ActivityType)index ); } catch (Exception e) { await this._log.Error(e.ToString()); if (this._discord == null) { return; } await this._discord.SetGameAsync(statusText, null, ActivityType.Watching); } }
private async Task UserLeavedGuild(SocketUser socketUser, SocketGuild socketGuild, string sufixMsg) { var jsonNode = await JsonCache.LoadValueAsync($"GuildSettings/{socketGuild.Id}", "leaveChannelId"); if (jsonNode == null) { return; } var channelId = jsonNode.Value; if (string.IsNullOrEmpty(channelId)) { return; } var channel = socketGuild.GetTextChannel(ulong.Parse(channelId)); if (channel == null) { return; } var jsonArray = (await JsonCache.LoadValueAsync("Answers/UserLeave", "data")).AsArray; string customAnswer = null; if (jsonArray != null) { customAnswer = jsonArray[this._rand.Next(0, jsonArray.Count)].Value; } var embed = new EmbedBuilder { Description = $"Temos {socketGuild.MemberCount} membros agora.", Color = Color.Red }; var title = new StringBuilder(); title.Append($"{socketUser.Username}#{socketUser.DiscriminatorValue:0000}"); title.Append($"{sufixMsg}"); embed.Title = title.ToString(); var sendMsg = await channel.SendMessageAsync(customAnswer, false, embed.Build()); // just leaved guild if (socketUser is SocketGuildUser socketGuildUser) { title.Append($"{(socketGuildUser.Nickname != null ? $" ({socketGuildUser.Nickname})" : null)}"); if (socketGuildUser.JoinedAt.HasValue) { embed.Footer = new EmbedFooterBuilder { Text = $"Membro desde {socketGuildUser.JoinedAt.Value.ToString("dd/MM/yy hh tt")}" }; } } else { // was banned var guildOwner = socketGuild.Owner; await guildOwner.SendMessageAsync($"Banido do servidor {socketGuild.Name}", false, embed.Build()); } await sendMsg.AddReactionAsync(new Emoji(":regional_indicator_f:")); }
private async Task HourlyMessage() { var time = DateTime.UtcNow.AddHours(-3); if (time.Minute != 0) { return; } if (time.Hour == 0) { this._audioService.PlaySoundByNameOnAllMostPopulatedAudioChannels("meianoite").CAwait(); return; } foreach (var guild in this._discord.Guilds) { try { string title = time.ToString("h tt", CultureInfo.InvariantCulture); string msg = null; switch (time.Hour) { case 0: title = "Meia noite, vão dormi"; msg = $"Horário oficial do óleo de macaco"; break; case 12: title = "Meio dia"; msg = $"Hora de comer *nhon nhon nhon*"; break; } var json = await JsonCache.LoadValueAsync($"GuildSettings/{guild.Id}", "channelHourlyMessage"); if (json == null) { continue; } var channel = guild.GetTextChannel(Convert.ToUInt64(json.Value)); if (channel == null) { continue; } if (channel.CachedMessages.Count <= 0) { return; } var lastUserMsg = channel.CachedMessages.OrderBy(m => m.Timestamp).Last() as IUserMessage; bool lastMsgIsFromThisBot = lastUserMsg != null && lastUserMsg.Author.Id == this._discord.CurrentUser.Id; // motivation phrase if (string.IsNullOrEmpty(msg)) { msg = await this.GetRandomMotivationPhrase(); } msg = string.IsNullOrEmpty(msg) ? "Hora agora" : $"*\"{msg}\"*"; var embed = new EmbedBuilder { Title = title, Description = msg }; RestUserMessage msgSend = null; if (lastMsgIsFromThisBot) { if (lastUserMsg.MentionedUserIds.Count <= 0) { await lastUserMsg.ModifyAsync(p => p.Embed = embed.Build() ); } } else { msgSend = await channel.SendMessageAsync(string.Empty, false, embed.Build()); } // get random photo try { var client = new RestClient("https://picsum.photos/96"); var request = new RestRequest(Method.GET); var timeline = await client.ExecuteAsync(request); if (!string.IsNullOrEmpty(timeline.ResponseUri.OriginalString)) { embed.ThumbnailUrl = timeline.ResponseUri.OriginalString; await msgSend.ModifyAsync(p => p.Embed = embed.Build()); } } catch (Exception e) { await this._log.Error(e.ToString()); } } catch (Exception e) { await this._log.Error(e.ToString()); continue; } } }
private async Task UserMessageReceivedAsync(SocketUserMessage userMessage) { // save this as last message this._lastsSocketMessageOnChannels[userMessage.Channel.Id] = userMessage; if (string.IsNullOrEmpty(userMessage.Content)) { return; } // Parameters bool userSaidHerName = false; bool isQuestion = false; #region <<---------- Setup message string to read ---------->> // Content of the message in lower case string. string messageString = userMessage.Content.ToLower(); messageString = RemoveDiacritics(messageString); messageString = messageString.Trim(); // if the message is a question if (messageString.Contains('?')) { messageString = messageString.Replace("?", string.Empty); isQuestion = true; } // if user said her name if (HasAtLeastOneWord(messageString, new[] { "nyu", "nuy" })) { userSaidHerName = true; messageString = RemoveBotNameFromMessage(messageString); } else if (userMessage.MentionedUsers.Contains(this._discord.CurrentUser)) { // remove the mention string from text messageString = messageString.Replace(this._discord.CurrentUser.Mention, ""); userSaidHerName = true; } // remove double and tripple spaces messageString = messageString.Replace(" ", " ").Replace(" ", " "); // See if message is empty now if (messageString.Length <= 0) { return; } #endregion <<---------- Setup message string to read ---------->> #region <<---------- New Users Anti Spam ---------->> try { if (messageString.Length > 140) { if (userMessage.Author is SocketGuildUser guildUser) { var json = await JsonCache.LoadValueAsync($"GuildSettings/{guildUser.Guild}", "enableNewUserAntiSpam"); if (json != null) { bool antiSpamEnabled = json.AsBool; if (antiSpamEnabled && !guildUser.IsBot && guildUser.JoinedAt.HasValue && DateTimeOffset.UtcNow < guildUser.JoinedAt.Value.AddDays(7)) { await this._log.Warning($"Deleting {guildUser.GetNameSafe()} message because this user is new on this guild."); await userMessage.DeleteAsync(); return; } } } } } catch (Exception e) { await this._log.Error(e.ToString()); } #endregion <<---------- New Users Anti Spam ---------->> #region <<---------- User Specific ---------->> // babies try { var jsonArray = (await JsonCache.LoadValueAsync("UsersBabies", "data")).AsArray; for (int i = 0; i < jsonArray.Count; i++) { var userId = jsonArray[i].Value; if (string.IsNullOrEmpty(userId)) { continue; } if (userMessage.Author.Id != Convert.ToUInt64(userId)) { continue; } await userMessage.AddReactionAsync(new Emoji("😭")); break; } } catch (Exception e) { await this._log.Error($"Exception trying to process babies answer: {e.ToString()}"); } #endregion <<---------- User Specific ---------->> #region Fast Answers if (messageString == ("ping")) { await userMessage.Channel.SendMessageAsync("pong"); return; } if (messageString == ("pong")) { await userMessage.Channel.SendMessageAsync("ping"); return; } if (messageString == ("marco")) { await userMessage.Channel.SendMessageAsync("polo"); return; } if (messageString == ("polo")) { await userMessage.Channel.SendMessageAsync("marco"); return; } if (messageString == ("dotto")) { await userMessage.Channel.SendMessageAsync("Dotto. :musical_note:"); return; } if (messageString == "❤" || messageString == ":heart:") { await userMessage.Channel.SendMessageAsync("❤"); return; } if (messageString == ":broken_heart:" || messageString == "💔") { await userMessage.Channel.SendMessageAsync("❤"); await userMessage.AddReactionAsync(new Emoji("😥")); return; } if (messageString == ("ne") || messageString == ("neh")) { await userMessage.Channel.SendMessageAsync(ChooseAnAnswer(new[] { "Isso ai.", "Pode crê.", "Boto fé." })); return; } if (messageString == ("vlw") || messageString == ("valeu") || messageString == ("valew")) { await userMessage.AddReactionAsync(new Emoji("😉")); return; } // see if message is an Hi if (messageString == "oi" || messageString == "ola" || messageString == "hi" || messageString == "hello" || messageString == "coe" || messageString == "ola pessoas" || messageString == "coe rapaziada" || messageString == "dae" || messageString == "oi galera" || messageString == "dae galera" || messageString == "opa" ) { await userMessage.Channel.SendMessageAsync(ChooseAnAnswer(new[] { "oi", "olá", "hello", "coé", "oin", "aoba", "fala tu", "manda a braba", "opa" })); return; } // see if message has an BYE if (messageString == "tchau" || messageString == "xau" || messageString == "tiau" || messageString == "thau" || messageString == "xau" || messageString == "flw" || messageString == "flws" || messageString == "falou" || messageString == "falous" || messageString.Contains(" flw") ) { await userMessage.Channel.SendMessageAsync(ChooseAnAnswer(new[] { "tchau", "xiau", "bye bye", "flw" })); return; } #endregion #region Nyu // check if user said nyu / nuy if (userSaidHerName) { if (HasAtLeastOneWord(messageString, new[] { "serve", "faz" })) { if (isQuestion) { await userMessage.Channel.SendMessageAsync("Sou um bot que responde diversas perguntas sobre assuntos comuns aqui no servidor. Com o tempo o Chris me atualiza com mais respostas e reações."); return; } } // Zueras if (messageString == ("vo ti cume") || messageString == ("vo ti come") || messageString == ("vou te come") || messageString == ("quero te come") || messageString == ("quero te pega") ) { await userMessage.AddReactionAsync(new Emoji("😠")); // angry return; } // Praises if (messageString.Contains("gata") || messageString.Contains("cremosa") || messageString.Contains("gostosa") || messageString.Contains("gatinha") || messageString.Contains("linda") || messageString.Contains("delicia") || messageString.Contains("dlicia") || messageString.Contains("dlcia") || messageString == ("amo te") || messageString == ("ti amu") || messageString == ("ti amo") || messageString == ("ti adoro") || messageString == ("te adoro") || messageString == ("te amo") || messageString == ("obrigado") || messageString == ("obrigada") ) { await userMessage.AddReactionAsync(new Emoji("❤")); return; } } #endregion #region Animes // Check for `Boku no picu` if (messageString.Contains("boku no picu") || messageString.Contains("boku no pico") || messageString.Contains("boku no piku") || messageString.Contains("boku no piku") ) { await userMessage.AddReactionAsync(new Emoji("😶")); return; } #endregion #region Memes // Ahhh agora eu entendi if (messageString.EndsWith("agora eu entendi")) { await userMessage.Channel.SendMessageAsync(ChooseAnAnswer(new[] { "Agora eu saqueeeeei!", "Agora tudo faz sentido!", "Eu estava cego agora estou enchergaaaando!", "Agora tudo vai mudar!", "Agora eu vou ficar de olhos abertos!" })); return; } #endregion #region General if (messageString == "alguem ai") { await userMessage.Channel.SendMessageAsync("Eu"); return; } if (messageString.Contains("que horas sao") || messageString.Contains("que horas e") || messageString.Contains("que horas que e") || messageString.Contains("que horas q e") ) { if (isQuestion) { await userMessage.Channel.SendMessageAsync("É hora de acertar as contas..."); return; } } #endregion #region Insults // Answer to insults if (messageString.Contains("bot lixo") || messageString.Contains("suamaeeminha") ) { await userMessage.AddReactionAsync(new Emoji("👀")); return; } #endregion #region <<---------- Anti trava discord ---------->> if (messageString.Length > 16 && ( messageString.StartsWith("𒀱") || messageString.StartsWith("⬛") || messageString.StartsWith("◼") || messageString.StartsWith("\\ðŸ¤") || messageString.StartsWith("¡ê") || messageString.StartsWith("◻◾") )) { await userMessage.DeleteAsync(); if (userMessage.Channel is SocketGuildChannel guildChannel) { var guild = this._discord.GetGuild(guildChannel.Guild.Id); // quarantine role if (userMessage.Author is SocketGuildUser guildUser) { var roleToAdd = guild.GetRole(474627963221049344); if (roleToAdd != null) { await guildUser.AddRoleAsync(roleToAdd); } } var msg = $"{MentionUtils.MentionUser(guild.OwnerId)} o {MentionUtils.MentionUser(userMessage.Author.Id)} enviou uma mensagem suspeita..."; await userMessage.Channel.SendMessageAsync(msg); } return; // return because spam message is delete and not any more threatment is required } #endregion <<---------- Anti trava discord ---------->> //!!! THIS PART OF THE CODE BELOW MUST BE AS THE LAST BECAUSE: // TODO bot log unknown commands on file // see if user sayd only bot name on message with some other things and she has no answer yet // if (userSaidHerName) { // string unknownCommandsFileName = "Lists/unknownCommands.txt"; // string textToWrite = messageString + $" ({userMessage.Author.Username})"; // // // first, compare if the text to save its not to big // if (textToWrite.Length > 48) { // // ignore the message because it can be spam // return; // } // // // check if the txt its not biggen then 10mb // await using (var ss = new StreamWriter(unknownCommandsFileName)) { // // } // var fileInfo = new FileInfo(unknownCommandsFileName); // if (fileInfo.Length > 10 * 1000000) { // await userMessage.Channel.SendMessageAsync("<@203373041063821313> eu tentei adicionar o texto que o " + userMessage.Author.Username + " digitou mas o arquivo de lista de comandos alcançou o tamanho limite. :sob:"); // return; // } // // // get text in string // string fileContent = File.ReadAllText(unknownCommandsFileName); // if (fileContent != null) { // // only write if the unknown text is NOT already on the file // if (!fileContent.Contains(messageString)) { // File.AppendAllText(unknownCommandsFileName, textToWrite + Environment.NewLine); // await userMessage.AddReactionAsync(new Emoji("❔")); // return; // } // } // else { // File.AppendAllText(unknownCommandsFileName, textToWrite + Environment.NewLine); // await userMessage.AddReactionAsync(new Emoji("❔")); // return; // } // // // return "Ainda não tenho resposta para isso:\n" + "`" + messageString + "`"; // return; // } // if arrived here, the message has no answer. }