private void UpdateChannel(ulong voiceChannel, bool isLocked) { if (GuildHandler.Plugins.IsPluginActive(_autoVoiceNamePluginName)) { SendMessage(_autoVoiceNamePluginName, "UpdateChannel", voiceChannel); } else { DisablePluginIfPermissionMissing(Discord.GuildPermission.ManageChannels, true); SocketVoiceChannel channel = GuildHandler.FindVoiceChannel(voiceChannel); if (channel != null) { if (isLocked) { if (!channel.Name.StartsWith(_lockEmoji)) { channel.ModifyAsync(x => x.Name = _lockEmoji + x.Name).ConfigureAwait(false); } } else { if (channel.Name.StartsWith(_lockEmoji)) { channel.ModifyAsync(x => x.Name = x.Name.Value.Substring(_lockEmoji.Length)).ConfigureAwait(false); } } } } }
public async Task ServerStats() { int memberCount = Context.Guild.MemberCount; DateTimeOffset date = Context.Guild.CreatedAt; string name = Context.Guild.Name; string owner = Context.Guild.Owner.Username; ServerConfig serverConfig = ServerConfigs.GetConfig(Context.Guild); bool reqV = serverConfig.RequiresVerification; string verification = string.Format("\nRequires Verification: **{0}**", reqV); if (reqV) { SocketRole vRole = Context.Guild.GetRole(serverConfig.VerificationRoleID); verification += string.Format("\nVerified Role: **{0}**", vRole.Name); } string configs = "\nBot Prefix: **" + serverConfig.Prefix + "**" + verification + "\nAFK Channel: **" + Context.Guild.GetVoiceChannel(serverConfig.AFKChannelID).Name + "**\nAFK Timeout: **" + serverConfig.AFKTimeout + "**\nAntispam Mute Time: **" + serverConfig.AntiSpamTime + "**\nAntispam Warn Ban: **" + serverConfig.AntiSpamWarn; string msg = "Server Name: **" + name + "**\nOwner: **" + owner + "**\nMember Count: **" + memberCount + "**\nDate Created: **" + date.ToString("MM/dd/yyyy hh:mm:ss") + "**" + configs + "**\n\n__Roles__\n**" + getAllRoles((SocketGuildUser)Context.User) + "**"; var result = from s in Context.Guild.VoiceChannels where s.Name.Contains("Member Count") select s; await PrintEmbedMessage("Server Stats", msg, iconUrl : Context.Guild.IconUrl); SocketVoiceChannel memberChan = result.FirstOrDefault(); await memberChan.ModifyAsync(m => { m.Name = "Member Count: " + Context.Guild.MemberCount; }); DataStorage.AddPairToStorage(memberChan.Guild.Name + " MemberChannel", memberChan.Id.ToString()); }
/// <summary> /// Updates the membercount channel if present. /// </summary> /// <param name="arg">The user who left or joined the guild.</param> public async Task HandleUserCount(SocketGuildUser arg) { try { ulong MemberCountChannel = Convert.ToUInt64(GetUserCountChannel(arg.Guild).Result); if (MemberCountChannel == 0) { return; } else { SocketVoiceChannel channel = arg.Guild.GetVoiceChannel(MemberCountChannel); SocketGuild guild = (channel as SocketGuildChannel)?.Guild; string msg = $"Total Users: {guild.MemberCount}"; if (channel.Name != msg) { await channel.ModifyAsync(x => x.Name = msg); } } } catch (Exception ex) { Global.ConsoleLog(ex.Message); return; } }
private async Task <bool> TryRenameChannel(SocketVoiceChannel voiceChannel) { if (voiceChannel.Users.Count == 0 && !voiceChannel.Name.Equals(DEFAULT_DYNAMIC_CHANNEL_NAME)) { string oldName = voiceChannel.Name; await voiceChannel.ModifyAsync(x => x.Name = DEFAULT_DYNAMIC_CHANNEL_NAME); log.Debug("Reverted channel: " + voiceChannel.Id + " - \"" + oldName + "\""); return(true); } else if (voiceChannel.Users.Count == 1) { if (!await TryUpdateToTopGame(voiceChannel)) { await TryRenameVoiceChannelToUser(voiceChannel, voiceChannel.Users.First()); } return(true); } else if (!await TryUpdateToTopGame(voiceChannel) && !voiceChannel.Name.Equals(DEFAULT_DYNAMIC_CHANNEL_NAME) && voiceChannel.Users.Any(x => voiceChannel.Name.Contains(x.Username) || voiceChannel.Name.Contains(x.Nickname))) { var user = voiceChannel.Users.First(); log.Debug("No top game in channel: " + voiceChannel.Id + " - \"" + voiceChannel.Name + "\""); await TryRenameVoiceChannelToUser(voiceChannel, user); return(true); } else { return(false); } }
private async Task <bool> TryRenameVoiceChannelToUser(SocketVoiceChannel voiceChannel, SocketGuildUser user) { // TODO: This is probably garbage way if (user.Nickname != null && (!voiceChannel.Name.Contains(user.Nickname) || !voiceChannel.Name.Contains(user.Username))) { await voiceChannel.ModifyAsync(x => x.Name = user.Nickname + "'s Domain"); log.Debug("Renamed channel: " + voiceChannel.Id + " - \"" + voiceChannel.Name + "\" to \"" + user.Nickname + "'s Domain\""); return(true); } else if (!voiceChannel.Name.Contains(user.Username)) { await voiceChannel.ModifyAsync(x => x.Name = user.Username + "'s Domain"); log.Debug("Renamed channel: " + voiceChannel.Id + " - \"" + voiceChannel.Name + "\" to \"" + user.Username + "'s Domain\""); return(true); } return(false); }
public static async Task updMemberChan(SocketGuild guild) { bool updateChan = false; SocketVoiceChannel MemberChan = null; SocketVoiceChannel UserChan = null; SocketVoiceChannel BotChan = null; foreach (SocketVoiceChannel chan in guild.VoiceChannels) { if (chan.Name.Contains("User Count")) { UserChan = chan; } else if (chan.Name.Contains("Bot Count")) { BotChan = chan; } else if (chan.Name.Contains("Member Count")) { MemberChan = chan; int members = int.Parse(chan.Name.Split(':')[1]); if (members != chan.Guild.Users.Count) { updateChan = true; } if (!updateChan) { break; } } } if (!updateChan) { return; } int botcount = 0; IReadOnlyCollection <SocketGuildUser> users = guild.Users; foreach (SocketGuildUser u in users) { if (u.IsBot) { botcount++; } } int memberCount = MemberChan.Guild.MemberCount; await MemberChan.ModifyAsync(m => { m.Name = "Member Count: " + memberCount; }); await UserChan.ModifyAsync(m => { m.Name = "User Count: " + (memberCount - botcount); }); await BotChan.ModifyAsync(m => { m.Name = "Bot Count: " + botcount; }); }
private async Task <bool> TryUpdateToTopGame(SocketVoiceChannel channel) { var topGame = TryGetTopGameInChannel(channel); if (topGame != null && (!channel.Name.Equals(topGame.Value.Name) || !channel.Name.Equals(gamesRepo.GetFriendlyName(topGame.Value.Name)))) { var oldChannelName = channel.Name; await channel.ModifyAsync(x => x.Name = gamesRepo.GetFriendlyName(topGame.Value.Name)); return(true); } else // Already top game set or game not being played. { return(false); } }
private async Task UpdateSingleUserChannel(SocketVoiceChannel voiceChannel) { if (voiceChannel.Users.First().Game != null) { // Set name to user's game string gameName = gamesRepo.GetFriendlyName(voiceChannel.Users.First().Game.Value.Name); await voiceChannel.ModifyAsync(x => x.Name = gameName); log.Debug("Renamed channel: " + voiceChannel.Id + " - \"" + voiceChannel.Name + "\" to \"" + gameName + "\""); } else { var user = voiceChannel.Users.First(); await TryRenameVoiceChannelToUser(voiceChannel, user); } }
public async Task UpdateChannel(SocketVoiceChannel channel) { string highestGame = ""; DisablePluginIfPermissionMissing(GuildPermission.ManageChannels, true); if (channel != null) { string name = _channelNames.GetValue().GetValueOrDefault(channel.Id); if (GuildHandler.GetChannel(channel.Id) == null) { return; } if (_toIgnore.GetValue().Contains(channel.Id)) { return; } if (string.IsNullOrEmpty(name)) // If the channel is unknown, then add it and retry through OnChannelCreated. { await OnChannelCreated(channel); return; } List <SocketGuildUser> users = channel.Users.ToList(); Dictionary <string, int> numPlayers = new Dictionary <string, int> (); foreach (SocketGuildUser user in users) { if (user.Activity == null) { continue; } int unknowns = 0; if (!user.IsBot) { if (user.Activity.Type == ActivityType.Playing) { string activity = user.Activity.ToString(); if (!numPlayers.ContainsKey(activity)) { numPlayers.Add(activity, 0); } numPlayers[activity]++; } else { unknowns++; } } // Temporary solution to the bot not being able to see game being played, if the user has a custom status. // In this case, if the user is not a bot, it is assumed they are playing all games currently being played by others. for (int i = 0; i < numPlayers.Count; i++) { numPlayers[numPlayers.ElementAt(i).Key] += unknowns; } } int highest = int.MinValue; for (int i = 0; i < numPlayers.Count; i++) { KeyValuePair <string, int> value = numPlayers.ElementAt(i); if (value.Value > highest) { highest = value.Value; highestGame = value.Key; } } string [] splitVoice = name.Split(':'); string possibleShorten = splitVoice.Length > 1 ? splitVoice [1] : splitVoice [0]; string tags = GetTags(channel); string newName = splitVoice[0]; if (!string.IsNullOrWhiteSpace(highestGame)) { newName = FormatName(_nameFormat.GetValue(), possibleShorten, highestGame, highest); } newName = tags + " " + newName; if (channel.Users.Count == 0) { _customNames.Remove(channel.Id); } if (_customNames.ContainsKey(channel.Id)) { newName = FormatName(_nameFormat.GetValue(), possibleShorten, _customNames[channel.Id], 0); } // Trying to optimize API calls here, just to spare those poor souls at the Discord API HQ stuff if (channel.Name != newName) { try { _pendingNameChanges.Add(channel.Id, newName); await channel.ModifyAsync(x => x.Name = newName); }catch (Exception e) { Core.Log.Exception(e); } } } }
public static async Task UpdateVoiceChannel(SocketVoiceChannel voice) { Game highestGame = new Game("", "", StreamType.NotStreaming); if (voice != null && allVoiceChannels.ContainsKey(voice.Id)) { VoiceChannel voiceChannel = allVoiceChannels [voice.Id]; List <SocketGuildUser> users = Utility.ForceGetUsers(voice.Id); if (voiceChannel.ignore) { return; } if (voice.Users.Count() == 0) { voiceChannel.Reset(); } else { if (voiceChannel.desiredMembers > 0) { if (users.Count >= voiceChannel.desiredMembers) { voiceChannel.SetStatus(VoiceChannel.VoiceChannelStatus.Full, false); } else { voiceChannel.SetStatus(VoiceChannel.VoiceChannelStatus.Looking, false); } } } Dictionary <Game, int> numPlayers = new Dictionary <Game, int> (); foreach (SocketGuildUser user in users) { if (UserConfiguration.GetSetting <bool> (user.Id, "AutoLooking") && users.Count == 1) { voiceChannel.SetStatus(VoiceChannel.VoiceChannelStatus.Looking, false); } if (user.Game.HasValue && user.IsBot == false) { if (numPlayers.ContainsKey(user.Game.Value)) { numPlayers [user.Game.Value]++; } else { numPlayers.Add(user.Game.Value, 1); } } } int highest = int.MinValue; for (int i = 0; i < numPlayers.Count; i++) { KeyValuePair <Game, int> value = numPlayers.ElementAt(i); if (value.Value > highest) { highest = value.Value; highestGame = value.Key; } } if (enableVoiceChannelTags) { GetTags(voiceChannel); } string tagsString = ""; foreach (VoiceChannelTag tag in voiceChannel.currentTags) { tagsString += tag.tagEmoji; } tagsString += tagsString.Length > 0 ? " " : ""; string [] splitVoice = voiceChannel.name.Split(';'); string possibleShorten = shortenChannelNames && splitVoice.Length > 1 ? splitVoice [1] : splitVoice [0]; int mixedLimit = highest >= 2 ? 2 : Utility.ForceGetUsers(voice.Id).Count == 1 ? int.MaxValue : 1; // Nested compact if statements? What could go wrong! string gameName = numPlayers.Where(x => x.Value >= mixedLimit).Count() > mixedLimit ? "Mixed Games" : gameNameReplacements.ContainsKey(highestGame.Name) ? gameNameReplacements[highestGame.Name] : highestGame.Name; // What even is this string newName; if (autoRenameChannels) { newName = gameName != "" ? tagsString + possibleShorten + " - " + gameName : tagsString + splitVoice [0]; } else { newName = tagsString + splitVoice [0]; } if (voiceChannel.customName != "") { newName = tagsString + possibleShorten + " - " + voiceChannel.customName; } // Trying to optimize API calls here, just to spare those poor souls at the Discord API HQ stuff if (voice.Name != newName) { Logging.Log(Logging.LogType.BOT, "Channel name updated: " + newName); await voice.ModifyAsync((delegate(VoiceChannelProperties properties) { properties.Name = newName; })); } voiceChannel.CheckLocker(); } }
public async Task UpdateChannel(SocketVoiceChannel channel) { string highestGame = ""; if (channel != null) { string name = _channelNames.GetValue().GetValueOrDefault(channel.Id); if (GuildHandler.GetChannel(channel.Id) == null) { return; } if (_toIgnore.GetValue().Contains(channel.Id)) { return; } if (string.IsNullOrEmpty(name)) // If the channel is unknown, then add it and retry through OnChannelCreated. { await OnChannelCreated(channel); return; } List <SocketGuildUser> users = channel.Users.ToList(); Dictionary <string, int> numPlayers = new Dictionary <string, int> (); foreach (SocketGuildUser user in users) { if (user.Activity == null) { continue; } if (user.Activity.Type == ActivityType.Playing && user.IsBot == false) { if (numPlayers.ContainsKey(user.Activity.Name)) { numPlayers [user.Activity.Name]++; } else { numPlayers.Add(user.Activity.Name, 1); } } } int highest = int.MinValue; for (int i = 0; i < numPlayers.Count; i++) { KeyValuePair <string, int> value = numPlayers.ElementAt(i); if (value.Value > highest) { highest = value.Value; highestGame = value.Key; } } string [] splitVoice = name.Split(':'); string possibleShorten = splitVoice.Length > 1 ? splitVoice [1] : splitVoice [0]; string tags = GetTags(channel); string newName = highestGame != "" ? possibleShorten + " - " + highestGame : splitVoice [0]; newName = tags + " " + newName; if (channel.Users.Count == 0) { _customNames.Remove(channel.Id); } if (_customNames.ContainsKey(channel.Id)) { newName = possibleShorten + " - " + _customNames [channel.Id]; } // Trying to optimize API calls here, just to spare those poor souls at the Discord API HQ stuff if (channel.Name != newName) { try { await channel.ModifyAsync(x => x.Name = newName); }catch (Exception e) { Core.Log.Write(e); } } } }
private static async void OnTimerTicked(object sender, ElapsedEventArgs e) { //GGWP string[] Activities = new[] { "!pomoc - aby uzyskać pomoc", $"Graczy na serwerze: {Global.Client.GetGuild(448884032391086090).Users.Count()}", "\"!\" to domyślny prefix" }; var kanalStaty = Global.Client.GetGuild(448884032391086090).GetTextChannel(521725645592723468); // Zmiana aktywności if (Global.NextActivity == Activities.Count()) { Global.NextActivity = 0; } await Global.Client.SetGameAsync(Activities[Global.NextActivity]); Global.NextActivity++; ////Gui //godzina string time = DateTime.Now.ToString("HH:mm"); var channelTime = Global.Client.GetGuild(448884032391086090).GetVoiceChannel(482943719742505001); await channelTime.ModifyAsync(y => y.Name = $"🕒 Godzina: {time}"); //data string date = DateTime.Now.ToString("dd.MM.yyyy"); var channelDate = Global.Client.GetGuild(448884032391086090).GetVoiceChannel(561613046305259531); await channelDate.ModifyAsync(y => y.Name = $"📅 Data: {date}"); //użytkownicy int howManyUsers = Global.Client.GetGuild(448884032391086090).Users.Count(); var channelUsers = Global.Client.GetGuild(448884032391086090).GetVoiceChannel(482933282745483284); await channelUsers.ModifyAsync(y => y.Name = $"👪 Graczy: {howManyUsers}"); //bany var getBans = await Global.Client.GetGuild(448884032391086090).GetBansAsync(); int countBans = getBans.Count(); var channelBans = Global.Client.GetGuild(448884032391086090).GetVoiceChannel(482933297362763776); await channelBans.ModifyAsync(y => y.Name = $"🚫 Bany: {countBans}"); //staty var msgExp = await kanalStaty.GetMessageAsync(Global.MsgStatyExp); var msgExpR = msgExp as RestUserMessage; var msgKasa = await kanalStaty.GetMessageAsync(Global.MsgStatyKasa); var msgKasaR = msgKasa as RestUserMessage; var orderedUsers = UserAccounts.UserAccounts.GetAllAccounts().OrderByDescending(acc => acc.XP).ToList().Take(8); EmbedBuilder eb = new EmbedBuilder(); eb.WithTitle("Top 8 graczy - LVL"); foreach (var userAccount in orderedUsers) { uint level = (uint)Math.Sqrt(userAccount.XP / 50); var user = Global.Client.GetUser(userAccount.ID); eb.AddField("Gracz: ", user == null ? "Nie znaleziono" : user.Username, true); eb.AddField("Exp: ", userAccount.XP, true); eb.AddField("Poziom: ", level, true); } eb.WithColor(Color.Gold); await msgExpR.ModifyAsync(message => { message.Content = ""; message.Embed = null; message.Embed = eb.Build(); }); var orderedUserss = UserAccounts.UserAccounts.GetAllAccounts().OrderByDescending(acc => acc.MoneyWallet).ToList().Take(8); EmbedBuilder ebb = new EmbedBuilder(); ebb.WithTitle("Top 8 graczy - KASA"); foreach (var userAccount in orderedUserss) { uint level = (uint)Math.Sqrt(userAccount.XP / 50); var userr = Global.Client.GetUser(userAccount.ID); ebb.AddField("Gracz: ", userr == null ? "Nie znaleziono" : userr.Username, true); ebb.AddField("Kasa: ", userAccount.MoneyWallet, true); ebb.AddField("Poziom: ", level, true); } ebb.WithColor(Color.Green); await msgKasaR.ModifyAsync(message => { message.Content = ""; message.Embed = null; message.Embed = ebb.Build(); }); //pogoda string weatherID = "433f32924ecebe72d3ff2b702ac1e498"; string weatherString = "❌ Błąd Pogody"; try { string response = ""; using (var http = new HttpClient()) { response = await http.GetStringAsync($"http://api.openweathermap.org/data/2.5/weather?q=warsaw&appid=" + weatherID + "&units=metric").ConfigureAwait(false); } if (response.Contains("\"main\":\"Rain\"")) { weatherString = "🌧️ Pogoda: Deszczowo"; } if (response.Contains("\"main\":\"Clouds\"")) { weatherString = "☁️ Pogoda: Pochmurnie"; } if (response.Contains("\"main\":\"Snow\"")) { weatherString = "🌨️ Pogoda: Śnieg"; } if (response.Contains("\"main\":\"Clear\"")) { weatherString = "☀️ Pogoda: Słonecznie"; } if (response.Contains("\"main\":\"Thunderstorm\"")) { weatherString = "⛈️ Pogoda: Burza"; } if (response.Contains("\"main\":\"Extreme\"")) { weatherString = "⛈️ Pogoda: Apokalipsa"; } if (response.Contains("\"main\":\"Drizzle\"")) { weatherString = "🌦️ Pogoda: Lekki deszcz"; } if (response.Contains("\"main\":\"Mist\"")) { weatherString = "🌫️ Pogoda: Mgliście"; } await weatherchannel.ModifyAsync(y => y.Name = $"{weatherString}"); } catch (Exception f) { Console.WriteLine(f); } }
private async Task ResetVoiceChannel(SocketVoiceChannel chnl, int userCount) { await chnl.ModifyAsync(x => x.UserLimit = userCount); await chnl.SyncPermissionsAsync(); }
public virtual Task ModifyAsync(Action <VoiceChannelProperties> func, RequestOptions?options = null) { return(_socketVoiceChannel.ModifyAsync(func, options)); }
public async Task SetMembercountChannel([Remainder] SocketChannel parsedChannel) { SocketGuildUser GuildUser = Context.Guild.GetUser(Context.User.Id); if (GuildUser.GuildPermissions.ManageChannels || Global.DevUIDs.Contains(Context.Message.Author.Id)) { if (parsedChannel.GetType() != typeof(SocketVoiceChannel)) { EmbedBuilder eb = new EmbedBuilder(); eb.WithTitle("Error setting membercount channel"); eb.WithDescription($"You must set the membercount channel to a voice channel!"); eb.WithColor(Color.Red); eb.WithAuthor(Context.Message.Author); eb.WithCurrentTimestamp(); await Context.Message.ReplyAsync("", false, eb.Build()); return; } SocketVoiceChannel channel = (SocketVoiceChannel)parsedChannel; MongoClient mongoClient = new MongoClient(Global.Mongoconnstr); IMongoDatabase database = mongoClient.GetDatabase("finlay"); IMongoCollection <BsonDocument> collection = database.GetCollection <BsonDocument>("guilds"); ulong _id = Context.Guild.Id; BsonDocument guildDocument = await MongoHandler.FindById(collection, _id); if (guildDocument == null) { MongoHandler.InsertGuild(_id); } BsonDocument guild = await collection.Find(Builders <BsonDocument> .Filter.Eq("_id", _id)).FirstOrDefaultAsync(); ulong _chanId = channel.Id; if (guild == null) { BsonDocument document = new BsonDocument { { "_id", (decimal)_id }, { "membercountchannel", (decimal)_chanId } }; collection.InsertOne(document); } else { collection.UpdateOne(Builders <BsonDocument> .Filter.Eq("_id", _id), Builders <BsonDocument> .Update.Set("membercountchannel", _chanId)); } EmbedBuilder embed = new EmbedBuilder(); embed.WithTitle("Success"); embed.WithDescription($"Successfully set the membercount channel to <#{_chanId}>!"); embed.WithColor(Color.Green); embed.WithAuthor(Context.Message.Author); embed.WithCurrentTimestamp(); await Context.Message.ReplyAsync("", false, embed.Build()); string msg = $"Total Users: {Context.Guild.MemberCount}"; if (channel.Name != msg) { await channel.ModifyAsync(x => x.Name = msg); } } else { await Context.Channel.TriggerTypingAsync(); await Context.Message.Channel.SendMessageAsync("", false, new EmbedBuilder() { Color = Color.LightOrange, Title = "You don't have Permission!", Description = $"Sorry, {Context.Message.Author.Mention} but you do not have permission to use this command.", Footer = new EmbedFooterBuilder() { IconUrl = Context.User.GetAvatarUrl() ?? Context.User.GetDefaultAvatarUrl(), Text = $"{Context.User}" }, }.Build()); } }