예제 #1
0
        public async Task SetLeaveChannel(SocketTextChannel textChannel)
        {
            var path     = $"GuildSettings/{this.Context.Guild.Id}";
            var jsonNode = await JsonCache.LoadJsonAsync(path);

            if (jsonNode == null)
            {
                jsonNode = new JSONObject();
            }

            jsonNode["leaveChannelId"] = textChannel?.Id.ToString() ?? string.Empty;
            await JsonCache.SaveToJson(path, jsonNode);


            var embed = new EmbedBuilder();

            if (textChannel != null)
            {
                embed.Title       = $"Leave channel set to";
                embed.Description = textChannel.Mention;
            }
            else
            {
                embed.Title = $"Disabled Leave guild messages";
            }

            await this.ReplyAsync("", false, embed.Build());
        }
예제 #2
0
        private async Task OnUserUpdated(SocketUser oldUser, SocketUser newUser)
        {
            if (newUser is not SocketGuildUser user)
            {
                return;
            }

            var json = await JsonCache.LoadJsonAsync($"DynamicVoiceChannels/{user.Guild}");

            if (json == null)
            {
                return;
            }
            var dynamicChannels = json["channels"].AsArray;

            if (dynamicChannels == null || dynamicChannels.Count <= 0)
            {
                return;
            }

            var allVoiceChannels = user.Guild.VoiceChannels;

            foreach (var voiceChannel in allVoiceChannels)
            {
                var usersOnVoiceChannel = user.Guild.Users.Where(x => x.VoiceChannel == voiceChannel).ToArray();
                if (usersOnVoiceChannel.Length <= 0)
                {
                    continue;
                }
            }
        }
예제 #3
0
        private async Task CheckForBotPublicIp()
        {
            var ip = await this.GetBotPublicIp();

            var json = await JsonCache.LoadJsonAsync("Ip") ?? new JSONObject
            {
                ["lastIp"] = ""
            };

            if (json["lastIp"].Value == ip)
            {
                return;
            }

            // ip changed

            json["lastIp"].Value = ip;
            await JsonCache.SaveToJson("Ip", json);
        }
예제 #4
0
        public async Task ShowWeather(params string[] locationStrings)
        {
            if (locationStrings.Length <= 0)
            {
                return;
            }
            var location = locationStrings.CJoin();

            if (string.IsNullOrEmpty(location))
            {
                return;
            }
            location = ChatService.RemoveDiacritics(location.ToLower());

            Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture;

            // check cache
            var weatherJson = await JsonCache.LoadJsonAsync($"WeatherInfo/{location}", this.MAX_CACHE_AGE);

            if (weatherJson == null)
            {
                var locationEncoded = HttpUtility.UrlEncode(location);
                var apiKey          = this._config["api-key-weather"];

                // api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}
                var client   = new RestClient($"https://api.openweathermap.org/data/2.5/weather?q={locationEncoded}&appid={apiKey}");
                var request  = new RestRequest(Method.GET);
                var timeline = await client.ExecuteAsync(request);

                if (!string.IsNullOrEmpty(timeline.ErrorMessage))
                {
                    Console.WriteLine($"Error trying to get weather for '{locationEncoded}': {timeline.ErrorMessage}");
                    return;
                }
                if (string.IsNullOrEmpty(timeline.Content))
                {
                    return;
                }

                weatherJson = JSON.Parse(timeline.Content);
                if (weatherJson == null || weatherJson["cod"].AsInt != 200)
                {
                    Console.WriteLine($"Error trying to parse weather json for {location}! timeline.Content:\n{timeline.Content}");
                    return;
                }

                weatherJson["cacheTime"] = (DateTime.UtcNow - TimeSpan.FromHours(3)).ToString("hh:mm:ss tt");

                await JsonCache.SaveToJson($"WeatherInfo/{location}", weatherJson);
            }

            var currentCelsius = weatherJson["main"]["temp"].AsFloat - 273.15f;             // kelvin to celsius

            var embed = new EmbedBuilder();

            embed.Title       = $"{currentCelsius:0} °C";
            embed.Description = $"Temperatura em {weatherJson["name"].Value}";

            var cacheTimeStr = weatherJson["cacheTime"].Value;

            if (!string.IsNullOrEmpty(cacheTimeStr))
            {
                embed.Footer = new EmbedFooterBuilder {
                    Text = $"Atualizado as {cacheTimeStr}"
                };
            }

            // get icon
            try {
                var iconCode = weatherJson["weather"][0]["icon"].Value;
                embed.ThumbnailUrl = $"http://openweathermap.org/img/w/{iconCode}.png";
            } catch (Exception e) {
                Console.WriteLine($"Error trying to set icon from weather {location}:\n{e}");
            }

            // get humildade
            try {
                var value = weatherJson["main"]["humidity"].Value;
                embed.AddField(
                    new EmbedFieldBuilder {
                    Name     = $"{value}%",
                    Value    = "Humildade",
                    IsInline = true
                }
                    );
            } catch (Exception e) {
                Console.WriteLine($"Error trying to set humidity: {e}");
            }

            // get sensation
            float feelsLike = 0;

            try {
                feelsLike = weatherJson["main"]["feels_like"].AsFloat - 273.15f;                 // kelvin to celsius
                embed.AddField(
                    new EmbedFieldBuilder {
                    Name     = $"{feelsLike:0} °C",
                    Value    = "Sensação térmica",
                    IsInline = true
                }
                    );
            } catch (Exception e) {
                Console.WriteLine($"Error trying to set sensation: {e}");
            }

            // get wind
            try {
                var value = weatherJson["wind"]["speed"].AsFloat * 3.6f;                 // mp/s to km/h
                embed.AddField(
                    new EmbedFieldBuilder {
                    Name     = $"{value:0} (km/h)",
                    Value    = "Ventos",
                    IsInline = true
                }
                    );
            } catch (Exception e) {
                Console.WriteLine($"Error trying to set wind: {e}");
            }

            // get weather name
            try {
                var value       = weatherJson["weather"][0]["main"].Value;
                var description = weatherJson["weather"][0]["description"].Value;
                embed.AddField(
                    new EmbedFieldBuilder {
                    Name     = value,
                    Value    = description,
                    IsInline = true
                }
                    );
            } catch (Exception e) {
                Console.WriteLine($"Error trying to set weather name and description field: {e}");
            }

            await this.ReplyAsync(this.GetWeatherVerbalStatus((int)feelsLike), false, embed.Build());
        }
예제 #5
0
        private async Task DiscordOnMessageReceived(SocketMessage socketMessage)
        {
            if (!(socketMessage is SocketUserMessage socketUserMessage))
            {
                return;
            }
            if (socketUserMessage.Channel == null)
            {
                return;
            }
            var msg = socketUserMessage.Resolve().ToLower();

            if (string.IsNullOrEmpty(msg))
            {
                return;
            }

            // check for msg about dolar
            if (msg.Length == 1)
            {
                if (msg != "$")
                {
                    return;
                }
            }
            else
            {
                if (!msg.Contains("dolar"))
                {
                    return;
                }
            }

            // thread culture
            var cultureInfo = new CultureInfo("en-us");

            Thread.CurrentThread.CurrentCulture   = cultureInfo;
            Thread.CurrentThread.CurrentUICulture = cultureInfo;

            // get last exchange json
            var exchangeJson = await JsonCache.LoadJsonAsync(JPATH_EXCHANGEINFO, TimeSpan.FromMinutes(15));

            if (exchangeJson == null)
            {
                var apiKey = this._config["apikey-freecurrencyconverter"];

                // Example:
                // https://free.currconv.com/api/v7/convert?q=USD_BRL&compact=ultra&apiKey=82e456034f1bb5418116
                var client   = new RestClient($"https://free.currconv.com/api/v7/convert?q=USD_BRL&compact=ultra&apiKey={apiKey}");
                var request  = new RestRequest(Method.GET);
                var timeline = await client.ExecuteAsync(request);

                if (!string.IsNullOrEmpty(timeline.ErrorMessage))
                {
                    Console.WriteLine($"Error trying to get exchangeJson: {timeline.ErrorMessage}");
                    return;
                }
                if (string.IsNullOrEmpty(timeline.Content))
                {
                    return;
                }

                exchangeJson = JSON.Parse(timeline.Content);
                if (exchangeJson == null || exchangeJson.IsNull)
                {
                    Console.WriteLine($"Error trying to parse exchangeJson! timeline.Content:\n{timeline.Content}");
                    return;
                }

                exchangeJson["cacheTime"] = (DateTime.UtcNow - TimeSpan.FromHours(3)).ToString("hh:mm:ss tt");

                await JsonCache.SaveToJson(JPATH_EXCHANGEINFO, exchangeJson);
            }

            var currencyValue = exchangeJson[JKEY_USD_BRL].AsFloat;

            var embed = new EmbedBuilder {
                Title       = currencyValue.ToString("C2", cultureInfo),
                Description = "Cotação do dolar",
                Color       = Color.DarkGreen
            };

            var cacheTimeStr = exchangeJson["cacheTime"].Value;

            if (!string.IsNullOrEmpty(cacheTimeStr))
            {
                embed.Footer = new EmbedFooterBuilder {
                    Text = $"Atualizado as {cacheTimeStr}"
                };
            }

            var channel = socketUserMessage.Channel;

            if (socketUserMessage.Channel == null)
            {
                return;
            }

            await channel.SendMessageAsync(MentionUtils.MentionUser(socketUserMessage.Author.Id), false, embed.Build());
        }