void InitializeFields() { DateTime time = DateTime.Now; if (guild == null) { var dbEntry = Database.Guilds.FindOne(); if (dbEntry == null) { Console.WriteLine("Couldnt get a guild"); return; } guild = Client.GetGuild(dbEntry.GuildId); } if (supporterRole == null && guild != null) { supporterRole = guild.GetRole(547202953505800233); supporterChannel = guild.GetTextChannel(547204432144891907); generalChannel = guild.GetChannel(334933825383563266) as SocketTextChannel; } }
public async Task UpdateAll(bool isForced = false) { DateTime time = DateTime.Now; if (guild == null) { guild = Client.GetGuild(Database.Guilds.FindOne(item => true).GuildId); } if (supporterRole == null) { supporterRole = guild.GetRole(547202953505800233); supporterChannel = guild.GetTextChannel(547204432144891907); generalChannel = guild.GetChannel(334933825383563266) as SocketTextChannel; } foreach (TownUser user in Database.Users.Find(item => item.AltaInfo != null && (isForced || (item.AltaInfo.IsSupporter && item.AltaInfo.SupporterExpiry < time)))) { await UpdateAsync(user, null); await Task.Delay(20); } }
public WebhookUpdated GetFilledModel(SocketGuild guild) { if (ChannelId == null) { return(this); } var oldChannel = guild.GetChannel(ChannelId.Before); var newChannel = guild.GetChannel(ChannelId.After); Channel = new DiffData <IChannel>(oldChannel, newChannel); return(this); }
async Task GrantUserRoleBasedOnReaction(IEmote emote, IUserMessage message, SocketGuild guild, TownGuild guildSettings, IGuildUser guildUser) { GrantingRoleSettings roleSettings = guildSettings.RoleGrantingSettings.MessagesMap[message.Id].ReactionsToRoles[emote.Name]; SocketRole role = guild.GetRole(roleSettings.RoleToGrant); Console.WriteLine($"{guildUser} reacted with: {emote.Name} and is being given role: " + role); await guildUser.AddRoleAsync(role); if (guildSettings.RoleGrantingSettings.RemoveReactOnSuccess) { await message.RemoveReactionAsync(emote, guildUser); } string welcomeMessage = guildSettings.FormatMessage(roleSettings.GrantedMessage, guildUser, client); await(guild.GetChannel(roleSettings.MessageChannel) as SocketTextChannel).SendMessageAsync(welcomeMessage); if (roleSettings.DirectMessageOnGrant) { string directMessage = guildSettings.FormatMessage(roleSettings.DirectMessage, guildUser, client); await guildUser.SendMessageAsync(roleSettings.DirectMessage); } }
private async Task OnReady() { // This means that the bot updated last time, so send a message and delete the file if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt"))) { string [] contents = (await File.ReadAllTextAsync(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt"))).Split('\n'); SocketGuild guild = _client.GetGuild(ulong.Parse(contents [0])); SocketGuildChannel channel = guild.GetChannel(ulong.Parse(contents [1])); await((IMessageChannel)channel).SendMessageAsync("Successfully updated!"); File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt")); } // Intialize the audit log if (Data.Settings.Has("server-id") && Data.Settings.Has("log-channel-id")) { ulong guildId = ulong.Parse(Data.Settings["server-id"]); ulong logChannelId = ulong.Parse(Data.Settings["log-channel-id"]); IGuild mainGuild = _client.GetGuild(guildId); IMessageChannel auditLogChannel = await mainGuild.GetTextChannelAsync(logChannelId); _auditLog.Channel = auditLogChannel; } else { Log.WriteLine("Can't initialize the video settings handler: Either the server ID or the log channel ID has not been assigned."); } _ = PeriodicCheckMute(new TimeSpan(TimeSpan.TicksPerHour * 1), CancellationToken.None); _ = PeriodicCheckBan(new TimeSpan(TimeSpan.TicksPerHour * 1), CancellationToken.None); _ = PeriodicCheckVideoSuggestions(new TimeSpan(TimeSpan.TicksPerHour * 4), CancellationToken.None); }
public async Task <AuditMessagePinInfo> GetFilledModelAsync(SocketGuild guild, IMessageCache cache) { Message = await cache.GetAsync(ChannelId, MessageId); Channel = guild.GetChannel(ChannelId); return(this); }
private async Task HandleMessage(IUserMessage msg, IEmote reaction) { Message mes = _messageRepo.GetMessage(msg.Id); _messageRepo.RemoveMessage(mes.MessageID); _messages.Remove(_messages.FirstOrDefault(m => m.MessageID == msg.Id)); Embed embeds = (Embed)msg.Embeds.First(); if (reaction.Name.Equals(cross.Name)) { var changed = embeds.ToEmbedBuilder(); changed.Color = Color.Red; await msg.RemoveAllReactionsAsync(); await msg.ModifyAsync(m => m.Embed = changed.Build()); return; } await msg.DeleteAsync(); Channel chan = _channelRepo.GetChannelByTypeInGuild(mes.Channel.GuildID, Models.Domain.ChannelType.publicfeed); SocketGuild guild = _client.Guilds.FirstOrDefault(g => g.Id == chan.GuildID); IMessageChannel channel = (IMessageChannel)guild.GetChannel(chan.ChanelID); await channel.SendMessageAsync(embed : embeds); }
public async Task transferTask(string name) { string transferPath = Path.Combine(mainDir, trasferDir); SocketGuild Guild = Context.Guild as SocketGuild; SocketTextChannel channel = Guild.GetChannel(466373989854347264) as SocketTextChannel; SocketGuildUser user = Context.User as SocketGuildUser; string username = ""; if (user.Nickname == null) { username = user.Username; } else { username = user.Nickname; } string userFile = Path.Combine(transferPath, username); if (!File.Exists(userFile)) { File.Create(userFile).Close(); File.WriteAllText(userFile, user.Id.ToString()); } await channel.SendMessageAsync("Transfer " + name + " - Requested by " + username); }
public void Restore(SocketGuild guild) { ulong id = Convert.ToUInt64(ChannelId, 16); if (guild == null) { throw new ArgumentNullException("guild"); } SocketGuildChannel channel = guild.GetChannel(id); if (!(channel is ISocketMessageChannel)) { throw new ArgumentException(); } Channel = guild.GetChannel(id) as ISocketMessageChannel; }
/* * This method is used to track the xp gained from users that are active in voice chat, * active meaning that they are not muted and that they are not alone in a voice chat * If a user is active, then add a random amount of xp to them for every message sent in a channel, * and if they leveled up, send the level up message in the pre-chosen channel. */ internal static async void UserSentMessage(SocketGuildUser user, SocketGuild guild) { foreach (var channel in guild.VoiceChannels) { foreach (var usa in channel.Users) { if (usa.IsDeafened || usa.IsMuted || usa.IsSelfDeafened || usa.IsSelfMuted || channel.Users.Count <= 1) { continue; } else { Random r = new Random(); uint x = (uint)r.Next(5, 20); var User = UserAccounts.UserAccounts.GetAccount(usa); uint oldLevel = User.Lvl; User.XP += x; if (oldLevel != User.Lvl) { var embed = new EmbedBuilder(); embed.WithColor(Color.Magenta) .WithTitle("LVL UP!") .WithCurrentTimestamp() .WithFooter(usa.Username, usa.GetAvatarUrl()) .AddInlineField("Current XP:", User.XP) .WithDescription($"{usa.Mention} lvled up to {User.Lvl} from {oldLevel}"); await(guild.GetChannel(667577129348628491) as SocketTextChannel).SendMessageAsync("", false, embed.Build()); } } } } }
/// <summary> /// Updates the assignment message with any potential changes to the assignable roles. /// </summary> /// <param name="discordGuild">The guild that is being operated on</param> /// <returns>The assignment message</returns> private async Task <IMessage> UpdateAssignerMessage(SocketGuild discordGuild) { var guild = GuildRepo.Get(discordGuild.Id); var assignerChannel = discordGuild.GetChannel(guild.Settings.RoleAssignment.ChannelId.Value) as SocketTextChannel; IUserMessage assignerMessage = assignerChannel.GetCachedMessage(guild.Settings.RoleAssignment.MessageId.Value) as SocketUserMessage; if (assignerMessage == null) { assignerMessage = await assignerChannel.GetMessageAsync(guild.Settings.RoleAssignment.MessageId.Value) as RestUserMessage; } // Search for any roles that may have been deleted without WhiffBot's knowledge // and delete those rows from the database. foreach (var role in guild.Settings.RoleAssignment.Roles) { if (discordGuild.GetRole(role.RoleId) == null) { GuildRepo.RemoveAssignableRole(guild.Id, role.RoleId); await assignerMessage.RemoveAllReactionsForEmoteAsync(role.Reaction.ToEmojiOrEmote()); guild = GuildRepo.Get(discordGuild.Id); } } var newContent = CreateAssignerMessage(discordGuild, guild.Settings.RoleAssignment); await assignerMessage.ModifyAsync(m => m.Content = newContent); return(assignerMessage); }
public DiscordUser(SocketGuild guild, SocketGuildUser user, DBDiscordUser dbUser, List <UserUnverifyHistoryItem> unverifyHistory) { Guild = guild; User = user; ID = dbUser.ID; Points = dbUser.Points; GivenReactionsCount = dbUser.GivenReactionsCount; ObtainedReactionsCount = dbUser.ObtainedReactionsCount; WebAdminAccess = !string.IsNullOrEmpty(dbUser.WebAdminPassword); ApiAccess = !string.IsNullOrEmpty(dbUser.ApiToken); Birthday = dbUser.Birthday == null ? null : new UserBirthday(dbUser.Birthday); Channels = dbUser.Channels .Select(o => new ChannelStatItem(guild.GetChannel(o.ChannelIDSnowflake), o)) .Where(o => o.Channel != null) .OrderByDescending(o => o.Count) .ToList(); UnverifyHistory = unverifyHistory; MathAuditItems = dbUser.MathAudit.Select(o => new MathAuditItem(o, guild)).ToList(); if (dbUser.Statistics != null) { Statistics = new StatisticItem(dbUser.Statistics); } }
static async void LoadDatabase() { while (guild == null) { guild = Program.GetGuild(); } await guild.DownloadUsersAsync(); supporterRole = guild.GetRole(547202953505800233); supporterChannel = guild.GetTextChannel(547204432144891907); generalChannel = guild.GetChannel(334933825383563266) as SocketTextChannel; try { database = FileDatabase.Read <AccountDatabase>("Accounts/accounts"); Console.WriteLine("Loaded database!"); foreach (AccountInfo account in database.accounts.Values) { await UpdateAsync(account, null); } Console.WriteLine(database.accounts.Count); Console.WriteLine(database.expiryAccounts.Count); } catch (Exception e) { Console.WriteLine("Account database not found! " + e.Message); database = new AccountDatabase(); } }
private Task ReadyAsync() { //Console.WriteLine($"{_client.CurrentUser} is connected!"); bool msgFound = false; SocketGuild guild = _client.GetGuild(Convert.ToUInt64(_config.discordGuildID)); IMessageChannel channel = guild.GetChannel(Convert.ToUInt64(_config.discordChannelID)) as IMessageChannel; if (_config.discordMessageID != null) { Task <IMessage> msg = channel.GetMessageAsync(Convert.ToUInt64(_config.discordMessageID)); msg.Wait(); IUserMessage mesg = msg.Result as IUserMessage; if (mesg != null) { msgFound = true; mesg.ModifyAsync(x => x.Content = _message); } } if (_config.discordMessageID == null || !msgFound) { Task <IUserMessage> msg = channel.SendMessageAsync(_message); msg.Wait(); IUserMessage mesg = msg.Result; _config.setDiscordMessageNumber(Convert.ToString(mesg.Id)); _config.saveData(); } Environment.Exit(0); return(Task.CompletedTask); }
private async Task BuildLeaderboardAsync(Leaderboard leaderboard, SocketGuild guild) { LeaderboardData data = null; try { data = await GetLeaderboardDataAsync(leaderboard.Console, leaderboard.Variant); var channel = guild.GetChannel(leaderboard.ChannelId) as SocketTextChannel; foreach (var msg in await channel.GetMessagesAsync().FlattenAsync()) { await msg.DeleteAsync(); await Task.Delay(1000); } await channel.SendMessageAsync(embed : BuildTopClassEmbed(data, leaderboard.Variant)); await channel.SendMessageAsync(embed : BuildFirstTopAscendancyEmbed(data)); await channel.SendMessageAsync(embed : BuildSecondTopAscendancyEmbed(data)); await channel.SendMessageAsync(embed : BuildDiscordOnlyEmbed(data, leaderboard.Variant)); await Task.Delay(15000); } catch (Exception ex) { await _log.LogMessage(new LogMessage(LogSeverity.Error, "Leaderboard", string.Empty, ex)); return; } }
public async Task ServerLookup(ulong id) { // Get the GuildSettings GuildSettings guildSettings = Configuration.LoadedConfiguration.DiscordConfig.GuildSettings.Where(settings => settings.GuildId == id).FirstOrDefault(); // Get the SocketGuild and SocketGuildChannel SocketGuild guild = DiscordBot.GetGuild(id); // Build an embed EmbedBuilder embedBuilder = new EmbedBuilder() .WithTitle("Lookup") .AddField("Guild", $"{guild.Name} ({guild.Id}, {(guildSettings != null ? "registered" : "unregistered")})"); // Check if this guild is registered if (guildSettings != null) { // Get the registered channel SocketGuildChannel channel = guild.GetChannel(guildSettings.TargetChannelId); // Add additional lookup details embedBuilder .AddField("Channel", $"#{channel.Name} ({channel.Id})") .AddField("Language", guildSettings.DefaultLanguage.ToString()); } // Complete the embed embedBuilder .AddField("Owner", $"{guild.Owner.Username}#{guild.Owner.Discriminator} ({guild.Owner.Id})") .AddField("User Count", guild.MemberCount) .WithColor(Color.Blue); await Context.Channel.SendMessageAsync(embed : embedBuilder.Build()); }
async Task LogEdit(Cacheable <IMessage, ulong> cachedMessage, SocketMessage newMessage, ISocketMessageChannel channel) { try { //Just makes sure that it's not logged when it shouldn't be if (!(channel is SocketGuildChannel)) { return; } SocketGuild guild = (channel as SocketGuildChannel).Guild; IMessage oldMessage = cachedMessage.GetOrDownloadAsync().Result; if (oldMessage.Content == newMessage.Content || newMessage.Author.IsBot || guild == null) { return; } LogSettings settings = guild.LoadFromFile <LogSettings>(); if (settings == null || !settings.logEdits) { return; } SocketTextChannel logChannel = guild.GetChannel(settings.logChannel) as SocketTextChannel; if (logChannel == null) { return; } var embed = new EmbedBuilder(); if (oldMessage.Content == null || oldMessage.Content == "") { embed.AddField($"Message was edited in #{newMessage.Channel.Name} from", "`This message had no text`"); } else { embed.AddField($"Message was edited in #{newMessage.Channel.Name} from", oldMessage.Content.Truncate(1020)); } if (newMessage.Content == null || newMessage.Content == "") { embed.AddField($"Message was edited in #{newMessage.Channel.Name} to", "`This message had no text`"); } else { embed.AddField($"Message was edited in #{newMessage.Channel.Name} to", newMessage.Content.Truncate(1020)); } embed.AddField("Message Link", "[Click Here](" + newMessage.GetJumpUrl() + ")", false); embed.WithFooter("ID: " + newMessage.Id) .WithAuthor(newMessage.Author) .WithColor(Color.Teal) .WithCurrentTimestamp(); logChannel.SendMessageAsync(embed: embed.Build()).Result.GetJumpUrl(); } catch (Exception exception) { _ = new LogMessage(LogSeverity.Error, "Logging", exception.Message, exception).Log(); } }
public ISocketMessageChannel GetLogChannel( SocketGuild guild) { if (this.VerifyGetServer(guild.Id, out GuildData data)) { return(guild.GetChannel(data.LogChannelId) as ISocketMessageChannel); } return(null); }
public static void LogDeleted(string reason, IMessage message, SocketGuild guild = null) { try { if (deletedMessagesCache == null) { deletedMessagesCache = new List <ulong>(); } if (deletedMessagesCache.Contains(message.Id)) { return; } if (deletedMessagesCache.Count == 5) { deletedMessagesCache.RemoveAt(4); } deletedMessagesCache.Insert(0, message.Id); if (guild == null) { Utilities.GetGuild(message.Channel as SocketGuildChannel); if (guild == null) { return; } } LogSettings settings = SettingFunctions.LoadLogSettings(guild); SocketTextChannel logChannel = guild.GetChannel(settings.logChannel) as SocketTextChannel; if (settings == null || logChannel == null || !settings.logDeletes) { return; } var embed = new EmbedBuilder(); SocketTextChannel channel = message.Channel as SocketTextChannel; if (message.Embeds.Count == 0) { embed.AddField(reason + " in #" + message.Channel.Name, message.Content, true); } else { embed.AddField(reason + " in #" + channel.Name, "`Embed cannot be displayed`", true); } embed.WithFooter("ID: " + message.Id) .WithAuthor(message.Author) .WithColor(Color.Blue) .WithCurrentTimestamp(); _ = logChannel.SendMessageAsync(embed: embed.Build()); } catch (Exception exception) { Console.WriteLine(new LogMessage(LogSeverity.Error, "Logging", "Error: ", exception)); } }
public async Task MemberUnbanned(SocketUser user, SocketGuild guild) { var log = guild.GetChannel(logchannel) as IMessageChannel; var embed4 = new EmbedBuilder() .WithColor(new Color(65280)) .AddField("User Unbanned", $"**{user.Mention}** has been unbanned!") .WithThumbnailUrl(user.GetAvatarUrl()); await log.SendMessageAsync("", embed : embed4); }
/// <summary> /// Upload the Clip into the discord channel /// </summary> /// <param name="filepath"></param> /// <param name="clip"></param> /// <returns></returns> public async Task UploadClipToDiscord(string filepath, ClipInfo clip) { // Get Server to send clips to SocketGuild server = client.GetGuild(ServerId) as SocketGuild; // Get Channel to send clips to SocketTextChannel channel = server.GetChannel(ChannelId) as SocketTextChannel; IDisposable typing = channel.EnterTypingState(); await channel.SendFileAsync(filepath, "", false, CreateEmbed(clip)); typing.Dispose(); }
private string BuildChannelOverrideList(List <ChannelOverride> overrides, SocketGuild guild) { if (overrides.Count == 0) { return("-"); } var builder = overrides.Select(o => guild.GetChannel(o.ChannelIdSnowflake)?.Name).Where(o => o != null); return(string.Join(", ", builder)); }
public async Task AnnounceNewUser(ulong userID, SocketRole role, string message) { try { SocketGuild gld = _client.GetGuild(257984126718574592) as SocketGuild; SocketGuildUser user = gld.GetUser(userID); ITextChannel channel = gld.GetChannel(755443198192648362) as ITextChannel; SocketTextChannel general = gld.GetChannel(257984126718574592) as SocketTextChannel; SocketTextChannel welcome = gld.GetChannel(311530747657715712) as SocketTextChannel; await channel.SendMessageAsync(user.Mention); await channel.SendMessageAsync("", false, new EmbedBuilder { Title = $"{user.Username} has infiltrated PC Pilots Air Space", Color = new Color(0, 170, 230), ThumbnailUrl = "https://i0.wp.com/pcpilotscrew.com/wp-content/uploads/2018/03/pcpi2_ytlogo512.png?resize=120%2C120&ssl=1", Description = $"{user.Mention} please read {welcome.Mention}.\nYou have been given the role of {role.Mention}\nPlease say Hello in {general.Mention}.\n{message}" }.Build()); } catch (Exception e) { Console.WriteLine(e.ToString()); } }
public static bool InitContext(DiscordSocketClient client) { bool successful = false; _client = client; _meleeSlasherGuild = _client.GetGuild(Global.Config.MeleeSlasherGuild); if (_client != null && _meleeSlasherGuild != null) { _logChannel = _meleeSlasherGuild.GetChannel(Global.Config.AuditChannel) as ITextChannel; _mainChannel = _meleeSlasherGuild.GetChannel(Global.Config.MeleeSlasherMainChannel) as ITextChannel; if (_logChannel != null && _mainChannel != null) { successful = true; } } return(successful); }
private async Task <(bool, IMessageChannel)> TryGetLogChannel(SocketGuild guild) { var logChannelId = await configRepo.GetLogChannel(guild.Id); if (logChannelId == null) { return(false, null); } var logChannel = guild.GetChannel(logChannelId.Value) as IMessageChannel; return(logChannel != null, logChannel); }
public Task LogUserUnbanned(SocketUser user, SocketGuild guild) { var logChannel = guild.GetChannel(833948793821069362) as SocketTextChannel; if (logChannel != null) { var message = $"{user.Mention} unbanned."; DevelopmentLog(logChannel, DateTime.Now, Action.Delete, Entity.Member, message); } return(Task.CompletedTask); }
private async Task OnReady() { // This means that the bot updated last time, so send a message and delete the file if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt"))) { string [] contents = (await File.ReadAllTextAsync(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt"))).Split('\n'); SocketGuild guild = _client.GetGuild(ulong.Parse(contents [0])); SocketGuildChannel channel = guild.GetChannel(ulong.Parse(contents [1])); await((IMessageChannel)channel).SendMessageAsync("Successfully updated!"); File.Delete(Path.Combine(Directory.GetCurrentDirectory(), "updated.txt")); } }
private async Task LogUserJoined(ulong userId, SocketGuild gld, SocketRole role) { SocketTextChannel log = gld.GetChannel(423526041143738368) as SocketTextChannel; SocketGuildUser user = gld.GetUser(userId); await log.SendMessageAsync("", false, new EmbedBuilder { Title = $"{user.Username} joined the server", Color = new Color(0, 170, 230), ThumbnailUrl = "https://i0.wp.com/pcpilotscrew.com/wp-content/uploads/2018/03/pcpi2_ytlogo512.png?resize=120%2C120&ssl=1", Description = $"{user.Username} assigned themselves as a {role.Mention} with the nickname of: **{user.Nickname}**", Timestamp = DateTime.Now, }.Build()); }
private async Task WelcomeAsync(SocketGuild guild) { if (_botStarted) { return; } _botStarted = true; if (guild.GetChannel(_config.CreateMissionChannel) is SocketTextChannel signupsChannel) { await signupsChannel.SendMessageAsync("Bot stoi! 🍆"); } }
private async Task UpdatePublicChannels() { await GetPublicChannels(); if (freepublicchannels.Count < 2) { var message = await _guild.CreateVoiceChannelAsync("Public " + (publicchannels.Capacity + 1)); } if (freepublicchannels.Count > 2 & publicchannels.Count > 6) { await _guild.GetChannel(publicchannels.Last().Id).DeleteAsync(); } }