public WheelOfFortuneGame(ulong userId, long bet, ICurrencyService cs) { _rng = new NadekoRandom(); _cs = cs; _bet = bet; _userId = userId; }
public async Task Ir(IUserMessage umsg, [Remainder] string query = null) { var channel = (ITextChannel)umsg.Channel; if (string.IsNullOrWhiteSpace(query)) { return; } try { using (var http = new HttpClient()) { var rng = new NadekoRandom(); var reqString = $"https://www.googleapis.com/customsearch/v1?q={Uri.EscapeDataString(query)}&cx=018084019232060951019%3Ahs5piey28-e&num=1&searchType=image&start={ rng.Next(1, 50) }&fields=items%2Flink&key={NadekoBot.Credentials.GoogleApiKey}"; var obj = JObject.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false)); var items = obj["items"] as JArray; await channel.SendMessageAsync(items[0]["link"].ToString()).ConfigureAwait(false); } } catch (HttpRequestException exception) { if (exception.Message.Contains("403 (Forbidden)")) { await channel.SendMessageAsync("Daily limit reached!"); } else { await channel.SendMessageAsync("Something went wrong."); } } }
public async Task Roll(IUserMessage umsg) { var channel = (ITextChannel)umsg.Channel; if (channel == null) { return; } var rng = new NadekoRandom(); var gen = rng.Next(1, 101); var num1 = gen / 10; var num2 = gen % 10; var imageStream = await Task.Run(() => { try { var ms = new MemoryStream(); new[] { GetDice(num1), GetDice(num2) }.Merge().SaveAsPng(ms); ms.Position = 0; return(ms); } catch { return(new MemoryStream()); } }); await channel.SendFileAsync(imageStream, "dice.png", $"{umsg.Author.Mention} rolled " + Format.Code(gen.ToString())).ConfigureAwait(false); }
public SearchImageCacher(IHttpClientFactory factory) { _log = LogManager.GetCurrentClassLogger(); _rng = new NadekoRandom(); _cache = new SortedSet <ImageCacherObject>(); _httpFactory = factory; }
public PlantPickService(DbService db, CommandHandler cmd, NadekoBot bot, NadekoStrings strings, IDataCache cache, FontProvider fonts, IBotConfigProvider bc, ICurrencyService cs, CommandHandler cmdHandler, DiscordSocketClient client) { _db = db; _strings = strings; _images = cache.LocalImages; _fonts = fonts; _bc = bc; _log = LogManager.GetCurrentClassLogger(); _cs = cs; _cmdHandler = cmdHandler; _rng = new NadekoRandom(); _client = client; cmd.OnMessageNoTrigger += PotentialFlowerGeneration; using (var uow = db.GetDbContext()) { var guildIds = client.Guilds.Select(x => x.Id).ToList(); var configs = uow._context.Set <GuildConfig>() .AsQueryable() .Include(x => x.GenerateCurrencyChannelIds) .Where(x => guildIds.Contains(x.GuildId)) .ToList(); _generationChannels = new ConcurrentHashSet <ulong>(configs .SelectMany(c => c.GenerateCurrencyChannelIds.Select(obj => obj.ChannelId))); } }
public async Task WhosPlaying([Remainder] string game) { game = game?.Trim().ToUpperInvariant(); if (string.IsNullOrWhiteSpace(game)) { return; } if (!(Context.Guild is SocketGuild socketGuild)) { _log.Warn("Can't cast guild to socket guild."); return; } var rng = new NadekoRandom(); var arr = await Task.Run(() => socketGuild.Users .Where(u => u.Activity?.Name?.ToUpperInvariant() == game) .Select(u => u.Username) .OrderBy(x => rng.Next()) .Take(60) .ToArray()).ConfigureAwait(false); int i = 0; if (arr.Length == 0) { await ReplyErrorLocalizedAsync("nobody_playing_game").ConfigureAwait(false); } else { await Context.Channel.SendConfirmAsync("```css\n" + string.Join("\n", arr.GroupBy(item => (i++) / 2) .Select(ig => string.Concat(ig.Select(el => $"• {el,-27}")))) + "\n```") .ConfigureAwait(false); } }
public static HangmanObject GetTerm(string type) { if (string.IsNullOrWhiteSpace(type)) { throw new ArgumentNullException(nameof(type)); } type = type.Trim(); var rng = new NadekoRandom(); if (type == "All") { var keys = data.Keys.ToArray(); type = keys[rng.Next(0, keys.Length)]; } HangmanObject[] termTypes; data.TryGetValue(type, out termTypes); if (termTypes == null || termTypes.Length == 0) { return(null); } return(termTypes[rng.Next(0, termTypes.Length)]); }
public async Task Roll(IUserMessage umsg, int num) { var channel = (ITextChannel)umsg.Channel; if (channel == null) { return; } var ordered = true; if (num < 1 || num > 30) { await channel.SendMessageAsync("Invalid number specified. You can roll up to 1-30 dice at a time.").ConfigureAwait(false); return; } var rng = new NadekoRandom(); var dice = new List <Image>(num); var values = new List <int>(num); for (var i = 0; i < num; i++) { var randomNumber = rng.Next(1, 7); var toInsert = dice.Count; if (ordered) { if (randomNumber == 6 || dice.Count == 0) { toInsert = 0; } else if (randomNumber != 1) { for (var j = 0; j < dice.Count; j++) { if (values[j] < randomNumber) { toInsert = j; break; } } } } else { toInsert = dice.Count; } dice.Insert(toInsert, GetDice(randomNumber)); values.Insert(toInsert, randomNumber); } var bitmap = dice.Merge(); var ms = new MemoryStream(); bitmap.SaveAsPng(ms); ms.Position = 0; await channel.SendFileAsync(ms, "dice.png", $"{umsg.Author.Mention} rolled {values.Count} {(values.Count == 1 ? "die" : "dice")}. Total: **{values.Sum()}** Average: **{(values.Sum() / (1.0f * values.Count)).ToString("N2")}**").ConfigureAwait(false); }
public static async Task <string> GetATFbooruImageLink(string tag) { var rng = new NadekoRandom(); var link = $"https://atfbooru.ninja/posts?" + $"limit=100"; if (!string.IsNullOrWhiteSpace(tag)) { link += $"&tags={tag.Replace(" ", "+")}"; } using (var http = new HttpClient()) { var webpage = await http.GetStringAsync(link).ConfigureAwait(false); var matches = Regex.Matches(webpage, "data-file-url=\"(?<id>.*?)\""); if (matches.Count == 0) { return(null); } return($"https://atfbooru.ninja" + $"{matches[rng.Next(0, matches.Count)].Groups["id"].Value}"); } }
public async Task NRoll(IUserMessage umsg, [Remainder] string range) { var channel = (ITextChannel)umsg.Channel; try { int rolled; if (range.Contains("-")) { var arr = range.Split('-') .Take(2) .Select(int.Parse) .ToArray(); if (arr[0] > arr[1]) { throw new ArgumentException("First argument should be bigger than the second one."); } rolled = new NadekoRandom().Next(arr[0], arr[1] + 1); } else { rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } await channel.SendMessageAsync($"{umsg.Author.Mention} rolled **{rolled}**.").ConfigureAwait(false); } catch (Exception ex) { await channel.SendMessageAsync($":anger: {ex.Message}").ConfigureAwait(false); } }
public ReplacementBuilder WithRngRegex() { var rng = new NadekoRandom(); _regex.TryAdd(rngRegex, (match) => { if (!int.TryParse(match.Groups["from"].ToString(), out var from)) { from = 0; } if (!int.TryParse(match.Groups["to"].ToString(), out var to)) { to = 0; } if (from == 0 && to == 0) { return(rng.Next(0, 11).ToString()); } if (from >= to) { return(string.Empty); } return(rng.Next(from, to + 1).ToString()); }); return(this); }
public static async Task <string> GetDanbooruImageLink(string tag) { var rng = new NadekoRandom(); if (tag == "loli") //loli doesn't work for some reason atm { tag = "flat_chest"; } var link = $"http://danbooru.donmai.us/posts?" + $"page={rng.Next(0, 15)}"; if (!string.IsNullOrWhiteSpace(tag)) { link += $"&tags={tag.Replace(" ", "_")}"; } using (var http = new HttpClient()) { var webpage = await http.GetStringAsync(link).ConfigureAwait(false); var matches = Regex.Matches(webpage, "data-large-file-url=\"(?<id>.*?)\""); if (matches.Count == 0) { return(null); } return($"http://danbooru.donmai.us" + $"{matches[rng.Next(0, matches.Count)].Groups["id"].Value}"); } }
public string GetRandomCurrencyImage() { var rng = new NadekoRandom(); var cur = _images.ImageUrls.Currency; return(cur[rng.Next(0, cur.Length)]); }
private async Task InternalRoll(int num, bool ordered) { if (num < 1 || num > 30) { await ReplyErrorLocalizedAsync("dice_invalid_number", 1, 30).ConfigureAwait(false); return; } var rng = new NadekoRandom(); var dice = new List <Image <Rgba32> >(num); var values = new List <int>(num); for (var i = 0; i < num; i++) { var randomNumber = rng.Next(1, 7); var toInsert = dice.Count; if (ordered) { if (randomNumber == 6 || dice.Count == 0) { toInsert = 0; } else if (randomNumber != 1) { for (var j = 0; j < dice.Count; j++) { if (values[j] < randomNumber) { toInsert = j; break; } } } } else { toInsert = dice.Count; } dice.Insert(toInsert, GetDice(randomNumber)); values.Insert(toInsert, randomNumber); } using (var bitmap = dice.Merge(out var format)) using (var ms = bitmap.ToStream(format)) { foreach (var d in dice) { d.Dispose(); } await Context.Channel.SendFileAsync(ms, $"dice.{format.FileExtensions.First()}", Format.Bold(Context.User.ToString()) + " " + GetText("dice_rolled_num", Format.Bold(values.Count.ToString())) + " " + GetText("total_average", Format.Bold(values.Sum().ToString()), Format.Bold((values.Sum() / (1.0f * values.Count)).ToString("N2")))).ConfigureAwait(false); } }
public GamesService(CommandHandler cmd, IBotConfigProvider bc, NadekoBot bot, NadekoStrings strings, IDataCache data, CommandHandler cmdHandler, ICurrencyService cs, FontProvider fonts) { _bc = bc; _cmd = cmd; _strings = strings; _images = data.LocalImages; _cmdHandler = cmdHandler; _log = LogManager.GetCurrentClassLogger(); _rng = new NadekoRandom(); _cs = cs; _fonts = fonts; //8ball EightBallResponses = _bc.BotConfig.EightBallResponses.Select(ebr => ebr.Text).ToImmutableArray(); //girl ratings _t = new Timer((_) => { GirlRatings.Clear(); }, null, TimeSpan.FromDays(1), TimeSpan.FromDays(1)); try { TypingArticles = JsonConvert.DeserializeObject <List <TypingArticle> >(File.ReadAllText(TypingArticlesPath)); } catch (Exception ex) { _log.Warn("Error while loading typing articles {0}", ex.ToString()); TypingArticles = new List <TypingArticle>(); } }
private async Task InternalHentai(IMessageChannel channel, string tag, bool noError) { var rng = new NadekoRandom(); var arr = Enum.GetValues(typeof(DapiSearchType)); var type = (DapiSearchType)arr.GetValue(new NadekoRandom().Next(2, arr.Length)); ImageCacherObject img; try { img = await _service.DapiSearch(tag, type, Context.Guild?.Id, true).ConfigureAwait(false); } catch (TagBlacklistedException) { await ReplyErrorLocalized("blacklisted_tag").ConfigureAwait(false); return; } if (img == null) { if (!noError) { await ReplyErrorLocalized("not_found").ConfigureAwait(false); } return; } await channel.EmbedAsync(new EmbedBuilder().WithOkColor() .WithImageUrl(img.FileUrl) .WithDescription($"[{GetText("tag")}: {tag}]({img})")) .ConfigureAwait(false); }
public async Task NRoll([Remainder] string range) { try { int rolled; if (range.Contains("-")) { var arr = range.Split('-') .Take(2) .Select(int.Parse) .ToArray(); if (arr[0] > arr[1]) { throw new ArgumentException("Second argument must be larger than the first one."); } rolled = new NadekoRandom().Next(arr[0], arr[1] + 1); } else { rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } await Context.Channel.SendConfirmAsync($"{Context.User.Mention} rolled **{rolled}**.").ConfigureAwait(false); } catch (Exception ex) { await Context.Channel.SendErrorAsync($":anger: {ex.Message}").ConfigureAwait(false); } }
public static async Task <string> GetRandomGalleryImageID(string page, string window) { try { using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Add("Authorization", $"Client-ID {NadekoBot.Credentials.ImgurApiKey}"); var rng = new NadekoRandom(); var reqString = $" https://api.imgur.com/3/gallery/hot/viral/{Uri.EscapeUriString(window)}/{Uri.EscapeUriString(page)}?showViral=bool"; var obj = JObject.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false)); var items = obj["data"] as JArray; var randomInt = rng.Next(1, items.Count); if (obj["success"].ToString().Equals("false")) { return("API call to Imgur was unsuccessful ;("); } else { return(items[randomInt]["link"].ToString()); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(""); } }
public static async Task <string> GetImgurImage(string query) { if (string.IsNullOrWhiteSpace(query)) { return("Enter a query!"); } try { using (var http = new HttpClient()) { http.DefaultRequestHeaders.Clear(); http.DefaultRequestHeaders.Add("Authorization", $"Client-ID {NadekoBot.Credentials.ImgurApiKey}"); var rng = new NadekoRandom(); var reqString = $"https://api.imgur.com/3/gallery/search/top/1?q_any={Uri.EscapeUriString(query)}"; var obj = JObject.Parse(await http.GetStringAsync(reqString).ConfigureAwait(false)); var items = obj["data"] as JArray; if (obj["success"].ToString().Equals("false")) { return("API call to Imgur was unsuccessful ;("); } else { return(items[rng.Next(1, items.Count)]["link"].ToString()); } } } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(""); } }
private static KeyValuePair <string, ImmutableArray <byte> > GetRandomCurrencyImage() { var rng = new NadekoRandom(); var images = NadekoBot.Images.Currency; return(images[rng.Next(0, images.Length)]); }
public async Task NRoll([Remainder] string range) { int rolled; if (range.Contains("-")) { var arr = range.Split('-') .Take(2) .Select(int.Parse) .ToArray(); if (arr[0] > arr[1]) { await ReplyErrorLocalizedAsync("second_larger_than_first").ConfigureAwait(false); return; } rolled = new NadekoRandom().Next(arr[0], arr[1] + 1); } else { rolled = new NadekoRandom().Next(0, int.Parse(range) + 1); } await ReplyConfirmLocalizedAsync("dice_rolled", Format.Bold(rolled.ToString())).ConfigureAwait(false); }
public WheelOfFortuneGame(ulong userId, long bet, ICurrencyService cs, ILeaderboardService lb) { _rng = new NadekoRandom(); _cs = cs; _bet = bet; _userId = userId; _lb = lb; }
public async Task MagicItem(IUserMessage umsg) { var channel = (ITextChannel)umsg.Channel; var rng = new NadekoRandom(); var item = magicItems[rng.Next(0, magicItems.Count)].ToString(); await channel.SendMessageAsync(item).ConfigureAwait(false); }
/*public Uri Birb(); * [NadekoCommand, Usage, Description, Aliases] * [RequireContext(ContextType.Guild)] * public Task Birdup() * { * * }*/ ///public Uri GetRandomBlackmail() public byte[] GetRandomBlackmail() { var rng = new NadekoRandom(); ///var blk = _images.ImageUrls.NoContext; ///return blk[rng.Next(0, blk.Length)]; return(_images.NoContext[rng.Next(0, _images.NoContext.Count)]); }
public Task<Quote> SearchQuoteKeywordTextAsync(ulong guildId, string keyword, string text) { var rngk = new NadekoRandom(); return _set.Where(q => q.Text.ContainsNoCase(text, StringComparison.OrdinalIgnoreCase) && q.GuildId == guildId && q.Keyword == keyword) .OrderBy(q => rngk.Next()) .FirstOrDefaultAsync(); }
private async Task Start() { CurrentPhase = Phase.Running; if (_users.Count <= 1) { foreach (var user in _users) { if (user.Bet > 0) { await _currency.AddAsync(user.UserId, "Race refund", user.Bet).ConfigureAwait(false); } } var _sf = OnStartingFailed?.Invoke(this); CurrentPhase = Phase.Ended; return; } var _ = OnStarted?.Invoke(this); var _t = Task.Run(async() => { var rng = new NadekoRandom(); while (!_users.All(x => x.Progress >= 60)) { foreach (var user in _users) { user.Progress += rng.Next(1, 11); if (user.Progress >= 60) { user.Progress = 60; } } var finished = _users.Where(x => x.Progress >= 60 && !FinishedUsers.Contains(x)) .Shuffle(); FinishedUsers.AddRange(finished); var _ignore = OnStateUpdate?.Invoke(this); await Task.Delay(2500).ConfigureAwait(false); } var win_amount = 0; foreach (var u in FinishedUsers) { win_amount += (int)u.Bet; } if (FinishedUsers[0].Bet > 0) { await _currency.AddAsync(FinishedUsers[0].UserId, "Won a Race", win_amount) .ConfigureAwait(false); } var _ended = OnEnded?.Invoke(this); }); }
public SearchImageCacher() { _http = new HttpClient(); _http.AddFakeHeaders(); _log = LogManager.GetCurrentClassLogger(); _rng = new NadekoRandom(); _cache = new SortedSet <ImageCacherObject>(); }
private GirlRating GetGirl(ulong uid) { var rng = new NadekoRandom(); var roll = rng.Next(1, 1001); var ratings = _service.Ratings.GetAwaiter().GetResult(); double hot; double crazy; string advice; if (roll < 500) { hot = NextDouble(0, 5); crazy = NextDouble(4, 10); advice = ratings.Nog; } else if (roll < 750) { hot = NextDouble(5, 8); crazy = NextDouble(4, .6 * hot + 4); advice = ratings.Fun; } else if (roll < 900) { hot = NextDouble(5, 10); crazy = NextDouble(.61 * hot + 4, 10); advice = ratings.Dan; } else if (roll < 951) { hot = NextDouble(8, 10); crazy = NextDouble(7, .6 * hot + 4); advice = ratings.Dat; } else if (roll < 990) { hot = NextDouble(8, 10); crazy = NextDouble(5, 7); advice = ratings.Wif; } else if (roll < 999) { hot = NextDouble(8, 10); crazy = NextDouble(2, 3.99d); advice = ratings.Tra; } else { hot = NextDouble(8, 10); crazy = NextDouble(4, 5); advice = ratings.Uni; } return(new GirlRating(_images, _httpFactory, crazy, hot, roll, advice)); }
private void GenerateCode() { var rng = new NadekoRandom(); for (var i = 0; i < 5; i++) { Code += _sneakyGameStatusChars[rng.Next(0, _sneakyGameStatusChars.Length)]; } }
public async Task Place(IUserMessage imsg, PlaceType placeType, uint width = 0, uint height = 0) { var channel = (ITextChannel)imsg.Channel; string url = ""; switch (placeType) { case PlaceType.Cage: url = "http://www.placecage.com"; break; case PlaceType.Steven: url = "http://www.stevensegallery.com"; break; case PlaceType.Beard: url = "http://placebeard.it"; break; case PlaceType.Fill: url = "http://www.fillmurray.com"; break; case PlaceType.Bear: url = "https://www.placebear.com"; break; case PlaceType.Kitten: url = "http://placekitten.com"; break; case PlaceType.Bacon: url = "http://baconmockup.com"; break; case PlaceType.Xoart: url = "http://xoart.link"; break; } var rng = new NadekoRandom(); if (width <= 0 || width > 1000) { width = (uint)rng.Next(250, 850); } if (height <= 0 || height > 1000) { height = (uint)rng.Next(250, 850); } url += $"/{width}/{height}"; await channel.SendMessageAsync(url).ConfigureAwait(false); }