Here are the examples of the csharp api System.Collections.Concurrent.ConcurrentDictionary.ContainsKey(ulong) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
70 Examples
19
Source : LavalinkNodeConnection.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public async Task<LavalinkGuildConnection> ConnectAsync(DiscordChannel channel)
{
if (this._connectedGuilds.ContainsKey(channel.Guild.Id))
return this._connectedGuilds[channel.Guild.Id];
if (channel.Guild == null || (channel.Type != ChannelType.Voice && channel.Type != ChannelType.Stage))
throw new ArgumentException("Invalid channel specified.", nameof(channel));
var vstut = new TaskCompletionSource<VoiceStateUpdateEventArgs>();
var vsrut = new TaskCompletionSource<VoiceServerUpdateEventArgs>();
this.VoiceStateUpdates[channel.Guild.Id] = vstut;
this.VoiceServerUpdates[channel.Guild.Id] = vsrut;
var vsd = new VoiceDispatch
{
OpCode = 4,
Payload = new VoiceStateUpdatePayload
{
GuildId = channel.Guild.Id,
ChannelId = channel.Id,
Deafened = false,
Muted = false
}
};
var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);
await (channel.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
var vstu = await vstut.Task.ConfigureAwait(false);
var vsru = await vsrut.Task.ConfigureAwait(false);
await this.SendPayloadAsync(new LavalinkVoiceUpdate(vstu, vsru)).ConfigureAwait(false);
var con = new LavalinkGuildConnection(this, channel, vstu);
con.ChannelDisconnected += this.Con_ChannelDisconnected;
con.PlayerUpdated += (s, e) => this._playerUpdated.InvokeAsync(s, e);
con.PlaybackStarted += (s, e) => this._playbackStarted.InvokeAsync(s, e);
con.PlaybackFinished += (s, e) => this._playbackFinished.InvokeAsync(s, e);
con.TrackStuck += (s, e) => this._trackStuck.InvokeAsync(s, e);
con.TrackException += (s, e) => this._trackException.InvokeAsync(s, e);
this._connectedGuilds[channel.Guild.Id] = con;
return con;
}
19
Source : VoiceNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
private async Task Client_VoiceServerUpdate(DiscordClient client, VoiceServerUpdateEventArgs e)
{
var gld = e.Guild;
if (gld == null)
return;
if (this.ActiveConnections.TryGetValue(e.Guild.Id, out var vnc))
{
vnc.ServerData = new VoiceServerUpdatePayload
{
Endpoint = e.Endpoint,
GuildId = e.Guild.Id,
Token = e.VoiceToken
};
var eps = e.Endpoint;
var epi = eps.LastIndexOf(':');
var eph = string.Empty;
var epp = 443;
if (epi != -1)
{
eph = eps.Substring(0, epi);
epp = int.Parse(eps.Substring(epi + 1));
}
else
{
eph = eps;
}
vnc.WebSocketEndpoint = new ConnectionEndpoint { Hostname = eph, Port = epp };
vnc.Resume = false;
await vnc.ReconnectAsync().ConfigureAwait(false);
}
if (this.VoiceServerUpdates.ContainsKey(gld.Id))
{
this.VoiceServerUpdates.TryRemove(gld.Id, out var xe);
xe.SetResult(e);
}
}
19
Source : LavalinkNodeConnection.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
private Task Discord_VoiceStateUpdated(DiscordClient client, VoiceStateUpdateEventArgs e)
{
var gld = e.Guild;
if (gld == null)
return Task.CompletedTask;
if (e.User == null)
return Task.CompletedTask;
if (e.User.Id == this.Discord.CurrentUser.Id)
{
if (this._connectedGuilds.TryGetValue(e.Guild.Id, out var lvlgc))
lvlgc.VoiceStateUpdate = e;
if (e.After.Channel == null && this.IsConnected && this._connectedGuilds.ContainsKey(gld.Id))
{
_ = Task.Run(async () =>
{
var delayTask = Task.Delay(this.Configuration.WebSocketCloseTimeout);
var tcs = lvlgc.VoiceWsDisconnectTcs.Task;
_ = await Task.WhenAny(delayTask, tcs).ConfigureAwait(false);
await lvlgc.DisconnectInternalAsync(false, true).ConfigureAwait(false);
_ = this._connectedGuilds.TryRemove(gld.Id, out _);
});
}
if (!string.IsNullOrWhiteSpace(e.SessionId) && e.Channel != null && this.VoiceStateUpdates.TryRemove(gld.Id, out var xe))
xe.SetResult(e);
}
return Task.CompletedTask;
}
19
Source : VoiceNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public async Task<VoiceNextConnection> ConnectAsync(DiscordChannel channel)
{
if (channel.Type != ChannelType.Voice && channel.Type != ChannelType.Stage)
throw new ArgumentException(nameof(channel), "Invalid channel specified; needs to be voice or stage channel");
if (channel.Guild == null)
throw new ArgumentException(nameof(channel), "Invalid channel specified; needs to be guild channel");
if (!channel.PermissionsFor(channel.Guild.CurrentMember).HasPermission(Permissions.AccessChannels | Permissions.UseVoice))
throw new InvalidOperationException("You need AccessChannels and UseVoice permission to connect to this voice channel");
var gld = channel.Guild;
if (this.ActiveConnections.ContainsKey(gld.Id))
throw new InvalidOperationException("This guild already has a voice connection");
var vstut = new TaskCompletionSource<VoiceStateUpdateEventArgs>();
var vsrut = new TaskCompletionSource<VoiceServerUpdateEventArgs>();
this.VoiceStateUpdates[gld.Id] = vstut;
this.VoiceServerUpdates[gld.Id] = vsrut;
var vsd = new VoiceDispatch
{
OpCode = 4,
Payload = new VoiceStateUpdatePayload
{
GuildId = gld.Id,
ChannelId = channel.Id,
Deafened = false,
Muted = false
}
};
var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);
await (channel.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
var vstu = await vstut.Task.ConfigureAwait(false);
var vstup = new VoiceStateUpdatePayload
{
SessionId = vstu.SessionId,
UserId = vstu.User.Id
};
var vsru = await vsrut.Task.ConfigureAwait(false);
var vsrup = new VoiceServerUpdatePayload
{
Endpoint = vsru.Endpoint,
GuildId = vsru.Guild.Id,
Token = vsru.VoiceToken
};
var vnc = new VoiceNextConnection(this.Client, gld, channel, this.Configuration, vsrup, vstup);
vnc.VoiceDisconnected += this.Vnc_VoiceDisconnected;
await vnc.ConnectAsync().ConfigureAwait(false);
await vnc.WaitForReadyAsync().ConfigureAwait(false);
this.ActiveConnections[gld.Id] = vnc;
return vnc;
}
19
Source : VoiceNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
public VoiceNextConnection GetConnection(DiscordGuild guild) => this.ActiveConnections.ContainsKey(guild.Id) ? this.ActiveConnections[guild.Id] : null;
19
Source : VoiceNextExtension.cs
with MIT License
from Aiko-IT-Systems
with MIT License
from Aiko-IT-Systems
private async Task Vnc_VoiceDisconnected(DiscordGuild guild)
{
VoiceNextConnection vnc = null;
if (this.ActiveConnections.ContainsKey(guild.Id))
this.ActiveConnections.TryRemove(guild.Id, out vnc);
var vsd = new VoiceDispatch
{
OpCode = 4,
Payload = new VoiceStateUpdatePayload
{
GuildId = guild.Id,
ChannelId = null
}
};
var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);
await (guild.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
}
19
Source : SessionContainer.cs
with MIT License
from Azure
with MIT License
from Azure
private static void ClearTokenByResourceId(SessionContainerState self, string resourceId)
{
if (!string.IsNullOrEmpty(resourceId))
{
ResourceId resource = ResourceId.Parse(resourceId);
if (resource.DoreplacedentCollection != 0)
{
ulong rid = resource.UniqueDoreplacedentCollectionId;
self.rwlock.EnterWriteLock();
try
{
if (self.collectionResourceIdByName.ContainsKey(rid))
{
string collectionName = self.collectionResourceIdByName[rid];
_ = self.sessionTokensRIDBased.TryRemove(rid, out _);
_ = self.collectionResourceIdByName.TryRemove(rid, out _);
_ = self.collectionNameByResourceId.TryRemove(collectionName, out _);
}
}
finally
{
self.rwlock.ExitWriteLock();
}
}
}
}
19
Source : PrefixService.cs
with MIT License
from BrammyS
with MIT License
from BrammyS
public void StorePrefix(string prefix, ulong key)
{
if (ServerPrefixes.ContainsKey(key))
{
var oldPrefix = GetPrefix(key);
if (!ServerPrefixes.TryUpdate(key, prefix, oldPrefix)) Logger.Log($"Failed to update custom prefix {prefix} with the key: {key} from the dictionary");
return;
}
if (!ServerPrefixes.TryAdd(key, prefix)) Logger.Log($"Failed to add custom prefix {prefix} with the key: {key} from the dictionary");
}
19
Source : PrefixService.cs
with MIT License
from BrammyS
with MIT License
from BrammyS
public string GetPrefix(ulong key)
{
return !ServerPrefixes.ContainsKey(key) ? null : ServerPrefixes[key];
}
19
Source : PrefixService.cs
with MIT License
from BrammyS
with MIT License
from BrammyS
public void RemovePrefix(ulong key)
{
if (!ServerPrefixes.ContainsKey(key)) return;
if (!ServerPrefixes.TryRemove(key, out var removedPrefix)) Logger.Log($"Failed to remove custom prefix {removedPrefix} with the key: {key} from the dictionary");
}
19
Source : Spotter.cs
with MIT License
from curiosity-ai
with MIT License
from curiosity-ai
public void TrainWord2Sense(IEnumerable<IDoreplacedent> doreplacedents, ParallelOptions parallelOptions, int ngrams = 3, double tooRare = 1E-5, double tooCommon = 0.1, Word2SenseTrainingData trainingData = null)
{
var hashCount = new ConcurrentDictionary<ulong, int>(trainingData?.HashCount ?? new Dictionary<ulong, int>());
var senses = new ConcurrentDictionary<ulong, ulong[]>(trainingData?.Senses ?? new Dictionary<ulong, ulong[]>());
var words = new ConcurrentDictionary<ulong, string>(trainingData?.Words ?? new Dictionary<ulong, string>());
var shapes = new ConcurrentDictionary<string, ulong>(trainingData?.Shapes ?? new Dictionary<string, ulong>());
var shapeExamples = new ConcurrentDictionary<string, string[]>(trainingData?.ShapeExamples ?? new Dictionary<string, string[]>());
long totalDocCount = trainingData?.SeenDoreplacedents ?? 0;
long totalTokenCount = trainingData?.SeenTokens ?? 0;
bool ignoreCase = Data.IgnoreCase;
bool ignoreOnlyNumeric = Data.IgnoreOnlyNumeric;
var stopwords = new HashSet<ulong>(StopWords.Spacy.For(Language).Select(w => ignoreCase ? IgnoreCaseHash64(w.replacedpan()) : Hash64(w.replacedpan())).ToArray());
int docCount = 0, tkCount = 0;
var sw = Stopwatch.StartNew();
TrainLock.EnterWriteLock();
try
{
Parallel.ForEach(doreplacedents, parallelOptions, doc =>
{
try
{
var stack = new Queue<ulong>(ngrams);
if (doc.TokensCount < ngrams) { return; } //Ignore too small doreplacedents
Interlocked.Add(ref tkCount, doc.TokensCount);
foreach (var span in doc)
{
var tokens = span.GetCapturedTokens().ToArray();
for (int i = 0; i < tokens.Length; i++)
{
var tk = tokens[i];
if (!(tk is Tokens))
{
var shape = tk.Valuereplacedpan.Shape(compact: false);
shapes.AddOrUpdate(shape, 1, (k, v) => v + 1);
shapeExamples.AddOrUpdate(shape, (k) => new[] { tk.Value }, (k, v) =>
{
if (v.Length < 50)
{
v = v.Concat(new[] { tk.Value }).Distinct().ToArray();
}
return v;
});
}
var hash = ignoreCase ? IgnoreCaseHash64(tk.Valuereplacedpan) : Hash64(tk.Valuereplacedpan);
bool filterPartOfSpeech = !(tk.POS == PartOfSpeech.ADJ || tk.POS == PartOfSpeech.NOUN);
bool skipIfHasUpperCase = (!ignoreCase && !tk.Valuereplacedpan.IsAllLowerCase());
bool skipIfTooSmall = (tk.Length < 3);
bool skipIfNotAllLetterOrDigit = !(tk.Valuereplacedpan.IsAllLetterOrDigit());
bool skipIfStopWordOrEnreplacedy = stopwords.Contains(hash) || tk.EnreplacedyTypes.Any();
//Heuristic for ordinal numbers (i.e. 1st, 2nd, 33rd, etc)
bool skipIfMaybeOrdinal = (tk.Valuereplacedpan.IndexOfAny(new char[] { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' }, 0) >= 0 &&
tk.Valuereplacedpan.IndexOfAny(new char[] { 't', 'h', 's', 't', 'r', 'd' }, 0) >= 0 &&
tk.Valuereplacedpan.IndexOfAny(new char[] { 'a', 'b', 'c', 'e', 'f', 'g', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'u', 'v', 'w', 'x', 'y', 'z' }, 0) < 0);
bool skipIfOnlyNumeric = ignoreOnlyNumeric ? !tk.Valuereplacedpan.IsLetter() : false;
//Only filter for POS if language != any, as otherwise we won't have the POS information
bool skipThisToken = (filterPartOfSpeech && Language != Language.Any) || skipIfHasUpperCase || skipIfTooSmall || skipIfNotAllLetterOrDigit || skipIfStopWordOrEnreplacedy || skipIfMaybeOrdinal || skipIfOnlyNumeric;
if (skipThisToken)
{
stack.Clear();
continue;
}
if (!words.ContainsKey(hash)) { words[hash] = ignoreCase ? tk.Value.ToLowerInvariant() : tk.Value; }
stack.Enqueue(hash);
ulong combined = stack.ElementAt(0);
for (int j = 1; j < stack.Count; j++)
{
combined = HashCombine64(combined, stack.ElementAt(j));
if (hashCount.ContainsKey(combined))
{
hashCount[combined]++;
}
else
{
senses[combined] = stack.Take(j + 1).ToArray();
hashCount[combined] = 1;
}
}
if (stack.Count > ngrams) { stack.Dequeue(); }
}
}
int count = Interlocked.Increment(ref docCount);
if (count % 1000 == 0)
{
Logger.LogInformation("Training Word2Sense model - at {DOCCOUNT} doreplacedents, {TKCOUNT} tokens - elapsed {ELAPSED} seconds at {KTKS} kTk/s)", docCount, tkCount, sw.Elapsed.TotalSeconds, (tkCount / sw.ElapsedMilliseconds));
}
}
catch (Exception E)
{
Logger.LogError(E, "Error during training Word2Sense model");
}
});
}
catch (OperationCanceledException)
{
return;
}
finally
{
TrainLock.ExitWriteLock();
}
Logger.LogInformation("Finish parsing doreplacedents for Word2Sense model");
totalDocCount += docCount;
totalTokenCount += tkCount;
int thresholdRare = Math.Max(2, (int)Math.Floor(tooRare * totalTokenCount));
int thresholdCommon = (int)Math.Floor(tooCommon * totalTokenCount);
var toKeep = hashCount.Where(kv => kv.Value >= thresholdRare && kv.Value <= thresholdCommon).OrderByDescending(kv => kv.Value)
.Select(kv => kv.Key).ToArray();
foreach (var key in toKeep)
{
if (senses.TryGetValue(key, out var hashes) && hashCount.TryGetValue(key, out var count))
{
Data.Hashes.Add(key);
for (int i = 0; i < hashes.Length; i++)
{
if (Data.MultiGramHashes.Count <= i)
{
Data.MultiGramHashes.Add(new HashSet<ulong>());
}
Data.MultiGramHashes[i].Add(hashes[i]);
}
}
}
if(trainingData is object)
{
trainingData.HashCount = new Dictionary<ulong, int>(hashCount);
trainingData.Senses = new Dictionary<ulong, ulong[]>(senses);
trainingData.Words = new Dictionary<ulong, string>(words);
trainingData.SeenDoreplacedents = totalDocCount;
trainingData.SeenTokens = totalTokenCount;
trainingData.Shapes = new Dictionary<string, ulong>(shapes);
trainingData.ShapeExamples = new Dictionary<string, string[]>(shapeExamples);
}
Logger.LogInformation("Finish training Word2Sense model");
}
19
Source : LootItemStorage.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public void RemoveStoredMoneyForContainer(ulong containerId)
{
if (!_looreplacedemStorage.ContainsKey(containerId))
return;
_looreplacedemStorage[containerId].RemoveMoney();
}
19
Source : LootItemStorage.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public void RemoveStoredLooreplacedemForContainer(ulong containerId, uint itemId, uint count)
{
if (!_looreplacedemStorage.ContainsKey(containerId))
return;
_looreplacedemStorage[containerId].RemoveItem(itemId, count);
}
19
Source : LootItemStorage.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public void AddNewStoredLoot(Loot loot, Player player)
{
// Saves the money and item loot replacedociated with an openable item to the DB
if (loot.IsLooted()) // no money and no loot
return;
if (_looreplacedemStorage.ContainsKey(loot.containerID.GetCounter()))
{
Log.outError(LogFilter.Misc, $"Trying to store item loot by player: {player.GetGUID()} for container id: {loot.containerID.GetCounter()} that is already in storage!");
return;
}
StoredLootContainer container = new(loot.containerID.GetCounter());
SQLTransaction trans = new();
if (loot.gold != 0)
container.AddMoney(loot.gold, trans);
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.DEL_ITEMCONTAINER_ITEMS);
stmt.AddValue(0, loot.containerID.GetCounter());
trans.Append(stmt);
foreach (Looreplacedem li in loot.items)
{
// Conditions are not checked when loot is generated, it is checked when loot is sent to a player.
// For items that are lootable, loot is saved to the DB immediately, that means that loot can be
// saved to the DB that the player never should have gotten. This check prevents that, so that only
// items that the player should get in loot are in the DB.
// IE: Horde items are not saved to the DB for Ally players.
if (!li.AllowedForPlayer(player))
continue;
// Don't save currency tokens
ItemTemplate itemTemplate = Global.ObjectMgr.GereplacedemTemplate(li.itemid);
if (itemTemplate == null || itemTemplate.IsCurrencyToken())
continue;
container.AddLooreplacedem(li, trans);
}
DB.Characters.CommitTransaction(trans);
_looreplacedemStorage.TryAdd(loot.containerID.GetCounter(), container);
}
19
Source : LootItemStorage.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public bool LoadStoredLoot(Item item, Player player)
{
Loot loot = item.loot;
if (!_looreplacedemStorage.ContainsKey(loot.containerID.GetCounter()))
return false;
var container = _looreplacedemStorage[loot.containerID.GetCounter()];
loot.gold = container.GetMoney();
LootTemplate lt = LootStorage.Items.GetLootFor(item.GetEntry());
if (lt != null)
{
foreach (var storedItemPair in container.GetLooreplacedems())
{
Looreplacedem li = new();
li.itemid = storedItemPair.Key;
li.count = (byte)storedItemPair.Value.Count;
li.follow_loot_rules = storedItemPair.Value.FollowRules;
li.freeforall = storedItemPair.Value.FFA;
li.is_blocked = storedItemPair.Value.Blocked;
li.is_counted = storedItemPair.Value.Counted;
li.is_underthreshold = storedItemPair.Value.UnderThreshold;
li.needs_quest = storedItemPair.Value.NeedsQuest;
li.randomBonusListId = storedItemPair.Value.RandomBonusListId;
li.context = storedItemPair.Value.Context;
li.BonusListIDs = storedItemPair.Value.BonusListIDs;
// Copy the extra loot conditions from the item in the loot template
lt.CopyConditions(li);
// If container item is in a bag, add that player as an allowed looter
if (item.GetBagSlot() != 0)
li.AddAllowedLooter(player);
// Finally add the Looreplacedem to the container
loot.items.Add(li);
// Increment unlooted count
++loot.unlootedCount;
}
}
// Mark the item if it has loot so it won't be generated again on open
item.m_lootGenerated = true;
return true;
}
19
Source : LootItemStorage.cs
with GNU General Public License v3.0
from CypherCore
with GNU General Public License v3.0
from CypherCore
public void LoadStorageFromDB()
{
uint oldMSTime = Time.GetMSTime();
_looreplacedemStorage.Clear();
uint count = 0;
PreparedStatement stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_ITEMCONTAINER_ITEMS);
SQLResult result = DB.Characters.Query(stmt);
if (!result.IsEmpty())
{
do
{
ulong key = result.Read<ulong>(0);
if (!_looreplacedemStorage.ContainsKey(key))
_looreplacedemStorage[key] = new StoredLootContainer(key);
StoredLootContainer storedContainer = _looreplacedemStorage[key];
Looreplacedem looreplacedem = new();
looreplacedem.itemid = result.Read<uint>(1);
looreplacedem.count = result.Read<byte>(2);
looreplacedem.follow_loot_rules = result.Read<bool>(3);
looreplacedem.freeforall = result.Read<bool>(4);
looreplacedem.is_blocked = result.Read<bool>(5);
looreplacedem.is_counted = result.Read<bool>(6);
looreplacedem.is_underthreshold = result.Read<bool>(7);
looreplacedem.needs_quest = result.Read<bool>(8);
looreplacedem.randomBonusListId = result.Read<uint>(9);
looreplacedem.context = (ItemContext)result.Read<byte>(10);
StringArray bonusLists = new(result.Read<string>(11), ' ');
foreach (string str in bonusLists)
looreplacedem.BonusListIDs.Add(uint.Parse(str));
storedContainer.AddLooreplacedem(looreplacedem, null);
++count;
} while (result.NextRow());
Log.outInfo(LogFilter.ServerLoading, $"Loaded {count} stored item loots in {Time.GetMSTimeDiffToNow(oldMSTime)} ms");
}
else
Log.outInfo(LogFilter.ServerLoading, "Loaded 0 stored item loots");
stmt = DB.Characters.GetPreparedStatement(CharStatements.SEL_ITEMCONTAINER_MONEY);
result = DB.Characters.Query(stmt);
if (!result.IsEmpty())
{
count = 0;
do
{
ulong key = result.Read<ulong>(0);
if (!_looreplacedemStorage.ContainsKey(key))
_looreplacedemStorage.TryAdd(key, new StoredLootContainer(key));
StoredLootContainer storedContainer = _looreplacedemStorage[key];
storedContainer.AddMoney(result.Read<uint>(1), null);
++count;
} while (result.NextRow());
Log.outInfo(LogFilter.ServerLoading, $"Loaded {count} stored item money in {Time.GetMSTimeDiffToNow(oldMSTime)} ms");
}
else
Log.outInfo(LogFilter.ServerLoading, "Loaded 0 stored item money");
}
19
Source : CommandCacheService.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
public void Add(ulong key, ulong value)
{
if (_count >= _max)
{
int removeCount = _count - _max + 1;
// The left 42 bits represent the timestamp.
var orderedKeys = _cache.Keys.OrderBy(k => k >> 22).ToList();
// Remove items until we're under the maximum.
int successfulRemovals = 0;
foreach (var orderedKey in orderedKeys)
{
if (successfulRemovals >= removeCount) break;
var success = TryRemove(orderedKey);
if (success) successfulRemovals++;
}
// Reset _count to _cache.Count.
UpdateCount();
}
// TryAdd will return false if the key already exists, in which case we don't want to increment the count.
if (!_cache.ContainsKey(value))
{
Interlocked.Increment(ref _count);
}
_cache[key] = value;
}
19
Source : CommandCacheService.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
public bool ContainsKey(ulong key) => _cache.ContainsKey(key);
19
Source : MusicService.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
private async Task UserVoiceStateUpdatedAsync(SocketUser user, SocketVoiceState beforeState, SocketVoiceState afterState)
{
// Someone left a voice channel
if (user is SocketGuildUser guildUser
&& LavaNode.TryGetPlayer(guildUser.Guild, out var player)
&& player.VoiceChannel != null
&& afterState.VoiceChannel == null)
{
// Fergun left a voice channel that has a player
if (user.Id == _client.CurrentUser.Id)
{
if (_loopDict.ContainsKey(player.VoiceChannel.GuildId))
{
_loopDict.TryRemove(player.VoiceChannel.GuildId, out _);
}
await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Victoria", $"Left the voice channel \"{player.VoiceChannel.Name}\" in guild \"{player.VoiceChannel.Guild.Name}\" because I got kicked out."));
await LavaNode.LeaveAsync(player.VoiceChannel);
}
// There are no users (or only bots) in the voice channel
else if (((SocketVoiceChannel)player.VoiceChannel).Users.All(x => x.IsBot))
{
if (_loopDict.ContainsKey(player.VoiceChannel.GuildId))
{
_loopDict.TryRemove(player.VoiceChannel.GuildId, out _);
}
var builder = new EmbedBuilder()
.WithDescription("\u26A0 " + GuildUtils.Locate("LeftVCInactivity", player.TextChannel))
.WithColor(FergunClient.Config.EmbedColor);
await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Victoria", $"Left the voice channel \"{player.VoiceChannel.Name}\" in guild \"{player.VoiceChannel.Guild.Name}\" because there are no users."));
await player.TextChannel.SendMessageAsync(embed: builder.Build());
await LavaNode.LeaveAsync(player.VoiceChannel);
}
}
}
19
Source : MusicService.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
private async Task OnWebSocketClosedAsync(WebSocketClosedEventArgs args)
{
if (_loopDict.ContainsKey(args.GuildId))
{
_loopDict.TryRemove(args.GuildId, out _);
}
await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Victoria", $"Websocket closed the connection on guild ID {args.GuildId} with code {args.Code} and reason: {args.Reason}"));
}
19
Source : MusicService.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
private async Task OnTrackEndedAsync(TrackEndedEventArgs args)
{
if (!args.Reason.ShouldPlayNext())
return;
var builder = new EmbedBuilder();
ulong guildId = args.Player.TextChannel.GuildId;
if (_loopDict.ContainsKey(guildId))
{
if (_loopDict[guildId] == 0)
{
_loopDict.TryRemove(guildId, out _);
var builder2 = new EmbedBuilder()
.WithDescription(string.Format(GuildUtils.Locate("LoopEnded", args.Player.TextChannel), args.Track.ToTrackLink(false)))
.WithColor(FergunClient.Config.EmbedColor);
await args.Player.TextChannel.SendMessageAsync(null, false, builder2.Build());
await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Victoria", $"Loop for track {args.Track.replacedle} ({args.Track.Url}) ended in {args.Player.TextChannel.Guild.Name}/{args.Player.TextChannel.Name}"));
}
else
{
await args.Player.PlayAsync(args.Track);
_loopDict[guildId]--;
return;
}
}
if (!args.Player.Queue.TryDequeue(out var nextTrack))
{
builder.WithDescription(GuildUtils.Locate("NoTracks", args.Player.TextChannel))
.WithColor(FergunClient.Config.EmbedColor);
await args.Player.TextChannel.SendMessageAsync(embed: builder.Build());
await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Victoria", $"Queue now empty in {args.Player.TextChannel.Guild.Name}/{args.Player.TextChannel.Name}"));
return;
}
await args.Player.PlayAsync(nextTrack);
builder.Withreplacedle(GuildUtils.Locate("NowPlaying", args.Player.TextChannel))
.WithDescription(nextTrack.ToTrackLink())
.WithColor(FergunClient.Config.EmbedColor);
await args.Player.TextChannel.SendMessageAsync(embed: builder.Build());
await _logService.LogAsync(new LogMessage(LogSeverity.Info, "Victoria", $"Now playing: {nextTrack.replacedle} ({nextTrack.Url}) in {args.Player.TextChannel.Guild.Name}/{args.Player.TextChannel.Name}"));
}
19
Source : MusicService.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
public async Task<bool> LeaveAsync(IGuild guild, SocketVoiceChannel voiceChannel)
{
bool hasPlayer = LavaNode.HasPlayer(guild);
if (!hasPlayer) return false;
if (_loopDict.ContainsKey(guild.Id))
{
_loopDict.TryRemove(guild.Id, out _);
}
await LavaNode.LeaveAsync(voiceChannel);
return true;
}
19
Source : MusicService.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
public async Task<string> StopAsync(IGuild guild, ITextChannel textChannel)
{
bool hasPlayer = LavaNode.TryGetPlayer(guild, out var player);
if (!hasPlayer)
return GuildUtils.Locate("PlayerNotPlaying", textChannel);
if (player == null)
return GuildUtils.Locate("PlayerError", textChannel);
await player.StopAsync();
if (_loopDict.ContainsKey(guild.Id))
{
_loopDict.TryRemove(guild.Id, out _);
}
return GuildUtils.Locate("PlayerStopped", textChannel);
}
19
Source : MusicService.cs
with MIT License
from d4n3436
with MIT License
from d4n3436
public string Loop(uint? count, IGuild guild, ITextChannel textChannel)
{
bool hasPlayer = LavaNode.TryGetPlayer(guild, out var player);
if (!hasPlayer || player.PlayerState != PlayerState.Playing)
return GuildUtils.Locate("PlayerNotPlaying", textChannel);
if (!count.HasValue)
{
if (!_loopDict.ContainsKey(guild.Id))
return string.Format(GuildUtils.Locate("LoopNoValuePreplaceded", textChannel), GuildUtils.GetPrefix(textChannel));
_loopDict.TryRemove(guild.Id, out _);
return GuildUtils.Locate("LoopDisabled", textChannel);
}
uint countValue = count.Value;
if (countValue < 1)
{
return string.Format(GuildUtils.Locate("NumberOutOfIndex", textChannel), 1, Constants.MaxTrackLoops);
}
countValue = Math.Min(Constants.MaxTrackLoops, countValue);
if (_loopDict.ContainsKey(guild.Id))
{
_loopDict[guild.Id] = countValue;
return string.Format(GuildUtils.Locate("LoopUpdated", textChannel), countValue);
}
_loopDict.TryAdd(guild.Id, countValue);
return string.Format(GuildUtils.Locate("NowLooping", textChannel), countValue);
}
19
Source : CacheService.cs
with GNU Affero General Public License v3.0
from Daniele122898
with GNU Affero General Public License v3.0
from Daniele122898
public bool Contains(ulong id) => _discordCache.ContainsKey(id);
19
Source : CommandErrorHandler.cs
with MIT License
from discord-csharp
with MIT License
from discord-csharp
public async Task ReactionAdded(ICacheable<IUserMessage, ulong> cachedMessage, IISocketMessageChannel channel, ISocketReaction reaction)
{
//Don't trigger if the emoji is wrong, if the user is a bot, or if we've
//made an error message reply already
if (reaction.User.IsSpecified && reaction.User.Value.IsBot)
{
return;
}
if (reaction.Emote.Name != _emoji || ErrorReplies.ContainsKey(cachedMessage.Id))
{
return;
}
//If the message that was reacted to has an replacedociated error, reply in the same channel
//with the error message then add that to the replies collection
if (replacedociatedErrors.TryGetValue(cachedMessage.Id, out var value))
{
var msg = await channel.SendMessageAsync("", false, new EmbedBuilder()
{
Author = new EmbedAuthorBuilder
{
IconUrl = "https://raw.githubusercontent.com/twitter/twemoji/gh-pages/2/72x72/26a0.png",
Name = "That command had an error"
},
Description = value,
Footer = new EmbedFooterBuilder { Text = "Remove your reaction to delete this message" }
}.Build());
if (ErrorReplies.TryAdd(cachedMessage.Id, msg.Id) == false)
{
await msg.DeleteAsync();
}
}
}
19
Source : AudioClient.cs
with MIT License
from Discord-Net-Labs
with MIT License
from Discord-Net-Labs
internal async Task CreateInputStreamAsync(ulong userId)
{
//replacedume Thread-safe
if (!_streams.ContainsKey(userId))
{
var readerStream = new InputStream(); //Consumes header
var opusDecoder = new OpusDecodeStream(readerStream); //Preplacedes header
//var jitterBuffer = new JitterBuffer(opusDecoder, _audioLogger);
var rtpReader = new RTPReadStream(opusDecoder); //Generates header
var decryptStream = new SodiumDecryptStream(rtpReader, this); //No header
_streams.TryAdd(userId, new StreamPair(readerStream, decryptStream));
await _streamCreatedEvent.InvokeAsync(userId, readerStream);
}
}
19
Source : MusicPlayerService.cs
with GNU Lesser General Public License v3.0
from Energizers
with GNU Lesser General Public License v3.0
from Energizers
public async Task<IEnergizePlayer> ConnectAsync(IVoiceChannel vc, ITextChannel chan)
{
if (!SanitizeCheck(vc, chan)) return null;
try
{
IEnergizePlayer ply;
if (this.Players.ContainsKey(vc.GuildId))
{
ply = this.Players[vc.GuildId];
if (ply.Lavalink == null) // in case we lose the player object
ply.Lavalink = await this.LavaClient.ConnectAsync(vc, chan);
}
else
{
ply = new EnergizePlayer(await this.LavaClient.ConnectAsync(vc, chan));
this.Logger.Nice("MusicPlayer", ConsoleColor.Magenta, $"Connected to VC in guild <{vc.Guild}>");
if (this.Players.TryAdd(vc.GuildId, ply))
{
ply.BecameInactive += async () =>
{
this.Logger.Nice("MusicPlayer", ConsoleColor.Yellow, $"Connected player became inactive in guild <{ply.VoiceChannel.Guild}>");
await this.DisconnectAsync(vc);
};
}
}
this.LavaClient.UpdateTextChannel(vc.GuildId, chan);
if (vc.Id != ply.Lavalink.VoiceChannel.Id)
await this.LavaClient.MoveChannelsAsync(vc);
return ply;
}
catch(Exception ex)
{
if (ex is ObjectDisposedException)
this.Logger.Nice("MusicPlayer", ConsoleColor.Red, "Could not connect, threading issue from Discord.NET");
else
this.Logger.Danger(ex);
await this.DisconnectAsync(vc);
return null;
}
}
19
Source : VoteSenderService.cs
with GNU Lesser General Public License v3.0
from Energizers
with GNU Lesser General Public License v3.0
from Energizers
private bool IsValidReaction(Cacheable<IUserMessage, ulong> cache, SocketReaction reaction)
=> IsValidEmote(reaction) && this.Votes.ContainsKey(cache.Id);
19
Source : ChannelDisabledCommandService.cs
with GNU General Public License v3.0
from fmbot-discord
with GNU General Public License v3.0
from fmbot-discord
public string[] GetDisabledCommands(ulong? key)
{
if (!key.HasValue)
{
return null;
}
return !ChannelDisabledCommands.ContainsKey(key.Value) ? null : ChannelDisabledCommands[key.Value];
}
19
Source : ChannelDisabledCommandService.cs
with GNU General Public License v3.0
from fmbot-discord
with GNU General Public License v3.0
from fmbot-discord
public void RemoveDisabledCommands(ulong key)
{
if (!ChannelDisabledCommands.ContainsKey(key))
{
return;
}
if (!ChannelDisabledCommands.TryRemove(key, out var removedDisabledCommands))
{
Log.Information($"Failed to remove custom disabled channel commands {removedDisabledCommands} with the key: {key} from the dictionary");
}
}
19
Source : GuildDisabledCommandService.cs
with GNU General Public License v3.0
from fmbot-discord
with GNU General Public License v3.0
from fmbot-discord
public void StoreDisabledCommands(string[] commands, ulong key)
{
if (GuildDisabledCommands.ContainsKey(key))
{
if (commands == null)
{
RemoveDisabledCommands(key);
}
var oldDisabledCommands = GetDisabledCommands(key);
if (!GuildDisabledCommands.TryUpdate(key, commands, oldDisabledCommands))
{
Log.Information($"Failed to update disabled guild commands {commands} with the key: {key} from the dictionary");
}
return;
}
if (!GuildDisabledCommands.TryAdd(key, commands))
{
Log.Information($"Failed to add disabled guild commands {commands} with the key: {key} from the dictionary");
}
}
19
Source : GuildDisabledCommandService.cs
with GNU General Public License v3.0
from fmbot-discord
with GNU General Public License v3.0
from fmbot-discord
public string[] GetDisabledCommands(ulong? key)
{
if (!key.HasValue)
{
return null;
}
return !GuildDisabledCommands.ContainsKey(key.Value) ? null : GuildDisabledCommands[key.Value];
}
19
Source : GuildDisabledCommandService.cs
with GNU General Public License v3.0
from fmbot-discord
with GNU General Public License v3.0
from fmbot-discord
public void RemoveDisabledCommands(ulong key)
{
if (!GuildDisabledCommands.ContainsKey(key))
{
return;
}
if (!GuildDisabledCommands.TryRemove(key, out var removedDisabledCommands))
{
Log.Information($"Failed to remove custom disabled guild commands {removedDisabledCommands} with the key: {key} from the dictionary");
}
}
19
Source : ChannelDisabledCommandService.cs
with GNU General Public License v3.0
from fmbot-discord
with GNU General Public License v3.0
from fmbot-discord
public void StoreDisabledCommands(string[] commands, ulong key)
{
if (ChannelDisabledCommands.ContainsKey(key))
{
if (commands == null)
{
RemoveDisabledCommands(key);
}
var oldDisabledCommands = GetDisabledCommands(key);
if (!ChannelDisabledCommands.TryUpdate(key, commands, oldDisabledCommands))
{
Log.Information($"Failed to update disabled channel commands {commands} with the key: {key} from the dictionary");
}
return;
}
if (!ChannelDisabledCommands.TryAdd(key, commands))
{
Log.Information($"Failed to add disabled channel commands {commands} with the key: {key} from the dictionary");
}
}
19
Source : PrefixService.cs
with GNU General Public License v3.0
from fmbot-discord
with GNU General Public License v3.0
from fmbot-discord
public void StorePrefix(string prefix, ulong key)
{
if (ServerPrefixes.ContainsKey(key))
{
var oldPrefix = GetPrefix(key);
if (!ServerPrefixes.TryUpdate(key, prefix, oldPrefix))
{
Log.Warning($"Failed to update custom prefix {prefix} with the key: {key} from the dictionary");
}
return;
}
if (!ServerPrefixes.TryAdd(key, prefix))
{
Log.Warning($"Failed to add custom prefix {prefix} with the key: {key} from the dictionary");
}
}
19
Source : PrefixService.cs
with GNU General Public License v3.0
from fmbot-discord
with GNU General Public License v3.0
from fmbot-discord
public string GetPrefix(ulong? key)
{
if (!key.HasValue)
{
return this._botSettings.Bot.Prefix;
}
return !ServerPrefixes.ContainsKey(key.Value) ? this._botSettings.Bot.Prefix : ServerPrefixes[key.Value];
}
19
Source : PrefixService.cs
with GNU General Public License v3.0
from fmbot-discord
with GNU General Public License v3.0
from fmbot-discord
public void RemovePrefix(ulong key)
{
if (!ServerPrefixes.ContainsKey(key))
{
return;
}
if (!ServerPrefixes.TryRemove(key, out var removedPrefix))
{
Log.Warning($"Failed to remove custom prefix {removedPrefix} with the key: {key} from the dictionary");
}
}
19
Source : TunnelStorage.cs
with MIT License
from force-net
with MIT License
from force-net
public bool Hreplacedession(ulong key)
{
return _sessions.ContainsKey(key);
}
19
Source : FactHandler.cs
with GNU General Public License v3.0
from Headline
with GNU General Public License v3.0
from Headline
public async Task AddGuild(ulong guild)
{
if (facts.ContainsKey(guild)) // we must've disconnected briefly, but still have our data
return;
var path = Program.BuildPath(guild + "_facts.txt");
var list = new List<string>();
facts.TryAdd(guild, list);
if (!File.Exists(path))
{
File.CreateText(path); // guild non-existant. Make empty file and move on
return;
}
await LoadList(list, path);
}
19
Source : MarkovHandler.cs
with GNU General Public License v3.0
from Headline
with GNU General Public License v3.0
from Headline
public async Task AddGuild(ulong guild)
{
if (dict.ContainsKey(guild)) // we must've disconnected briefly, but still have our data
return;
var path = Program.BuildPath(guild + ".txt");
var markov = new MarkovChain<string>(1);
dict.TryAdd(guild, markov);
nextResponse.TryAdd(guild, "");
if (!File.Exists(path))
{
File.CreateText(path); // guild non-existant. Make empty file and move on
return;
}
await LoadGraph(markov, path, guild);
BuildNext(guild);
}
19
Source : ChannelPool.cs
with MIT License
from houseofcat
with MIT License
from houseofcat
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public async ValueTask<IChannelHost> GetChannelAsync()
{
if (Shutdown) throw new InvalidOperationException(ExceptionMessages.ChannelPoolValidationMessage);
if (!await _channels
.Reader
.WaitToReadAsync()
.ConfigureAwait(false))
{
throw new InvalidOperationException(ExceptionMessages.ChannelPoolGetChannelError);
}
var chanHost = await _channels
.Reader
.ReadAsync()
.ConfigureAwait(false);
var healthy = await chanHost.HealthyAsync().ConfigureAwait(false);
var flagged = _flaggedChannels.ContainsKey(chanHost.ChannelId) && _flaggedChannels[chanHost.ChannelId];
if (flagged || !healthy)
{
_logger.LogWarning(LogMessages.ChannelPools.DeadChannel, chanHost.ChannelId);
var success = false;
while (!success)
{
success = await chanHost.MakeChannelAsync().ConfigureAwait(false);
await Task.Delay(Options.PoolOptions.SleepOnErrorInterval).ConfigureAwait(false);
}
}
return chanHost;
}
19
Source : ChannelPool.cs
with MIT License
from houseofcat
with MIT License
from houseofcat
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public async ValueTask<IChannelHost> GetAckChannelAsync()
{
if (Shutdown) throw new InvalidOperationException(ExceptionMessages.ChannelPoolValidationMessage);
if (!await _ackChannels
.Reader
.WaitToReadAsync()
.ConfigureAwait(false))
{
throw new InvalidOperationException(ExceptionMessages.ChannelPoolGetChannelError);
}
var chanHost = await _ackChannels
.Reader
.ReadAsync()
.ConfigureAwait(false);
var healthy = await chanHost.HealthyAsync().ConfigureAwait(false);
var flagged = _flaggedChannels.ContainsKey(chanHost.ChannelId) && _flaggedChannels[chanHost.ChannelId];
if (flagged || !healthy)
{
_logger.LogWarning(LogMessages.ChannelPools.DeadChannel, chanHost.ChannelId);
var success = false;
while (!success)
{
await Task.Delay(Options.PoolOptions.SleepOnErrorInterval).ConfigureAwait(false);
success = await chanHost.MakeChannelAsync().ConfigureAwait(false);
}
}
return chanHost;
}
19
Source : LavalinkNodeConnection.cs
with MIT License
from IDoEverything
with MIT License
from IDoEverything
public async Task<LavalinkGuildConnection> ConnectAsync(DiscordChannel channel)
{
if (this._connectedGuilds.ContainsKey(channel.Guild.Id))
return this._connectedGuilds[channel.Guild.Id];
if (channel.Guild == null || channel.Type != ChannelType.Voice)
throw new ArgumentException("Invalid channel specified.", nameof(channel));
var vstut = new TaskCompletionSource<VoiceStateUpdateEventArgs>();
var vsrut = new TaskCompletionSource<VoiceServerUpdateEventArgs>();
this.VoiceStateUpdates[channel.Guild.Id] = vstut;
this.VoiceServerUpdates[channel.Guild.Id] = vsrut;
var vsd = new VoiceDispatch
{
OpCode = 4,
Payload = new VoiceStateUpdatePayload
{
GuildId = channel.Guild.Id,
ChannelId = channel.Id,
Deafened = false,
Muted = false
}
};
var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);
await (channel.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
var vstu = await vstut.Task.ConfigureAwait(false);
var vsru = await vsrut.Task.ConfigureAwait(false);
await this.SendPayloadAsync(new LavalinkVoiceUpdate(vstu, vsru)).ConfigureAwait(false);
var con = new LavalinkGuildConnection(this, channel, vstu);
con.ChannelDisconnected += this.Con_ChannelDisconnected;
con.PlayerUpdated += (s, e) => this._playerUpdated.InvokeAsync(s, e);
con.PlaybackStarted += (s, e) => this._playbackStarted.InvokeAsync(s, e);
con.PlaybackFinished += (s, e) => this._playbackFinished.InvokeAsync(s, e);
con.TrackStuck += (s, e) => this._trackStuck.InvokeAsync(s, e);
con.TrackException += (s, e) => this._trackException.InvokeAsync(s, e);
this._connectedGuilds[channel.Guild.Id] = con;
return con;
}
19
Source : VoiceNextExtension.cs
with MIT License
from IDoEverything
with MIT License
from IDoEverything
public async Task<VoiceNextConnection> ConnectAsync(DiscordChannel channel)
{
if (channel.Type != ChannelType.Voice)
throw new ArgumentException(nameof(channel), "Invalid channel specified; needs to be voice channel");
if (channel.Guild == null)
throw new ArgumentException(nameof(channel), "Invalid channel specified; needs to be guild channel");
if (!channel.PermissionsFor(channel.Guild.CurrentMember).HasPermission(Permissions.UseVoice))
throw new InvalidOperationException("You need UseVoice permission to connect to this voice channel");
var gld = channel.Guild;
if (ActiveConnections.ContainsKey(gld.Id))
throw new InvalidOperationException("This guild already has a voice connection");
var vstut = new TaskCompletionSource<VoiceStateUpdateEventArgs>();
var vsrut = new TaskCompletionSource<VoiceServerUpdateEventArgs>();
this.VoiceStateUpdates[gld.Id] = vstut;
this.VoiceServerUpdates[gld.Id] = vsrut;
var vsd = new VoiceDispatch
{
OpCode = 4,
Payload = new VoiceStateUpdatePayload
{
GuildId = gld.Id,
ChannelId = channel.Id,
Deafened = false,
Muted = false
}
};
var vsj = JsonConvert.SerializeObject(vsd, Formatting.None);
await (channel.Discord as DiscordClient).WsSendAsync(vsj).ConfigureAwait(false);
var vstu = await vstut.Task.ConfigureAwait(false);
var vstup = new VoiceStateUpdatePayload
{
SessionId = vstu.SessionId,
UserId = vstu.User.Id
};
var vsru = await vsrut.Task.ConfigureAwait(false);
var vsrup = new VoiceServerUpdatePayload
{
Endpoint = vsru.Endpoint,
GuildId = vsru.Guild.Id,
Token = vsru.VoiceToken
};
var vnc = new VoiceNextConnection(this.Client, gld, channel, this.Configuration, vsrup, vstup);
vnc.VoiceDisconnected += this.Vnc_VoiceDisconnected;
await vnc.ConnectAsync().ConfigureAwait(false);
await vnc.WaitForReadyAsync().ConfigureAwait(false);
this.ActiveConnections[gld.Id] = vnc;
return vnc;
}
19
Source : VoiceNextExtension.cs
with MIT License
from IDoEverything
with MIT License
from IDoEverything
public VoiceNextConnection GetConnection(DiscordGuild guild)
{
if (this.ActiveConnections.ContainsKey(guild.Id))
return this.ActiveConnections[guild.Id];
return null;
}
19
Source : DiscordClient.cs
with MIT License
from IDoEverything
with MIT License
from IDoEverything
private void UpdateCachedGuild(DiscordGuild newGuild, JArray rawMembers)
{
if (this._disposed)
return;
if (!this._guilds.ContainsKey(newGuild.Id))
this._guilds[newGuild.Id] = newGuild;
var guild = this._guilds[newGuild.Id];
if (newGuild._channels != null && newGuild._channels.Count > 0)
{
foreach (var channel in newGuild._channels.Values)
{
if (guild._channels.TryGetValue(channel.Id, out _)) continue;
foreach (var overwrite in channel._permissionOverwrites)
{
overwrite.Discord = this;
overwrite._channel_id = channel.Id;
}
guild._channels[channel.Id] = channel;
}
}
foreach (var newEmoji in newGuild._emojis.Values)
_ = guild._emojis.GetOrAdd(newEmoji.Id, _ => newEmoji);
if (rawMembers != null)
{
guild._members.Clear();
foreach (var xj in rawMembers)
{
var xtm = xj.ToObject<TransportMember>();
var xu = new DiscordUser(xtm.User) { Discord = this };
_ = this.UserCache.AddOrUpdate(xtm.User.Id, xu, (id, old) =>
{
old.Username = xu.Username;
old.Discriminator = xu.Discriminator;
old.AvatarHash = xu.AvatarHash;
old.PremiumType = xu.PremiumType;
return old;
});
guild._members[xtm.User.Id] = new DiscordMember(xtm) { Discord = this, _guild_id = guild.Id };
}
}
foreach (var role in newGuild._roles.Values)
{
if (guild._roles.TryGetValue(role.Id, out _)) continue;
role._guild_id = guild.Id;
guild._roles[role.Id] = role;
}
guild.Name = newGuild.Name;
guild.AfkChannelId = newGuild.AfkChannelId;
guild.AfkTimeout = newGuild.AfkTimeout;
guild.DefaultMessageNotifications = newGuild.DefaultMessageNotifications;
guild.Features = newGuild.Features;
guild.IconHash = newGuild.IconHash;
guild.MfaLevel = newGuild.MfaLevel;
guild.OwnerId = newGuild.OwnerId;
guild.VoiceRegionId = newGuild.VoiceRegionId;
guild.SplashHash = newGuild.SplashHash;
guild.VerificationLevel = newGuild.VerificationLevel;
guild.WidgetEnabled = newGuild.WidgetEnabled;
guild.WidgetChannelId = newGuild.WidgetChannelId;
guild.ExplicitContentFilter = newGuild.ExplicitContentFilter;
guild.PremiumTier = newGuild.PremiumTier;
guild.PremiumSubscriptionCount = newGuild.PremiumSubscriptionCount;
guild.Banner = newGuild.Banner;
guild.Description = newGuild.Description;
guild.VanityUrlCode = newGuild.VanityUrlCode;
guild.Banner = newGuild.Banner;
guild.SystemChannelId = newGuild.SystemChannelId;
guild.SystemChannelFlags = newGuild.SystemChannelFlags;
guild.DiscoverySplashHash = newGuild.DiscoverySplashHash;
guild.MaxMembers = newGuild.MaxMembers;
guild.MaxPresences = newGuild.MaxPresences;
guild.ApproximateMemberCount = newGuild.ApproximateMemberCount;
guild.ApproximatePresenceCount = newGuild.ApproximatePresenceCount;
guild.MaxVideoChannelUsers = newGuild.MaxVideoChannelUsers;
guild.PreferredLocale = newGuild.PreferredLocale;
guild.RulesChannelId = newGuild.RulesChannelId;
guild.PublicUpdatesChannelId = newGuild.PublicUpdatesChannelId;
// fields not sent for update:
// - guild.Channels
// - voice states
// - guild.JoinedAt = new_guild.JoinedAt;
// - guild.Large = new_guild.Large;
// - guild.MemberCount = Math.Max(new_guild.MemberCount, guild._members.Count);
// - guild.Unavailable = new_guild.Unavailable;
}
19
Source : LocalAmeisenBotDb.cs
with GNU General Public License v3.0
from Jnnshschl
with GNU General Public License v3.0
from Jnnshschl
public bool GetUnitName(IWowUnit unit, out string name)
{
if (Names.ContainsKey(unit.Guid))
{
name = Names[unit.Guid];
return true;
}
else
{
name = unit.ReadName(MemoryApi, Wow.Offsets);
if (!string.IsNullOrWhiteSpace(name))
{
Names.TryAdd(unit.Guid, name);
return true;
}
name = "unk";
return false;
}
}
19
Source : OracleService.cs
with MIT License
from neo-project
with MIT License
from neo-project
[RpcMethod]
public JObject SubmitOracleResponse(JArray _params)
{
if (status != OracleStatus.Running) throw new InvalidOperationException();
ECPoint oraclePub = ECPoint.DecodePoint(Convert.FromBase64String(_params[0].replacedtring()), ECCurve.Secp256r1);
ulong requestId = (ulong)_params[1].AsNumber();
byte[] txSign = Convert.FromBase64String(_params[2].replacedtring());
byte[] msgSign = Convert.FromBase64String(_params[3].replacedtring());
if (finishedCache.ContainsKey(requestId)) throw new RpcException(-100, "Request has already finished");
using (var snapshot = System.GetSnapshot())
{
uint height = NativeContract.Ledger.CurrentIndex(snapshot) + 1;
var oracles = NativeContract.RoleManagement.GetDesignatedByRole(snapshot, Role.Oracle, height);
if (!oracles.Any(p => p.Equals(oraclePub))) throw new RpcException(-100, $"{oraclePub} isn't an oracle node");
if (NativeContract.Oracle.GetRequest(snapshot, requestId) is null)
throw new RpcException(-100, "Request is not found");
var data = Neo.Helper.Concat(oraclePub.ToArray(), BitConverter.GetBytes(requestId), txSign);
if (!Crypto.VerifySignature(data, msgSign, oraclePub)) throw new RpcException(-100, "Invalid sign");
AddResponseTxSign(snapshot, requestId, oraclePub, txSign);
}
return new JObject();
}
19
Source : OracleService.cs
with MIT License
from neo-project
with MIT License
from neo-project
private async void ProcessRequestsAsync()
{
while (!cancelSource.IsCancellationRequested)
{
using (var snapshot = System.GetSnapshot())
{
SyncPendingQueue(snapshot);
foreach (var (id, request) in NativeContract.Oracle.GetRequests(snapshot))
{
if (cancelSource.IsCancellationRequested) break;
if (!finishedCache.ContainsKey(id) && (!pendingQueue.TryGetValue(id, out OracleTask task) || task.Tx is null))
await ProcessRequestAsync(snapshot, request);
}
}
if (cancelSource.IsCancellationRequested) break;
await Task.Delay(500);
}
status = OracleStatus.Stopped;
}
See More Examples