示例#1
0
        /// <summary>
        /// Manual API-Call
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string TalkWithCleverBot(string text)
        {
            using (var client = new HttpClient())
            {
                var values = new Dictionary <string, string>
                {
                    { "user", Bot.Config.CleverbotAPIUser },
                    { "key", Bot.Config.CleverbotAPIKey },
                    { "nick", Bot.Config.CleverbotNick },
                    { "text", text },
                    { "locale", "de-DE" }
                };

                var content = new FormUrlEncodedContent(values);

                try
                {
                    var response = client.PostAsync("https://cleverbot.io/1.0/ask", content);

                    var responseString = response.Result.Content.ReadAsStringAsync();
                    response.Wait();
                    var responseObject = Newtonsoft.Json.Linq.JObject.Parse(responseString.Result.ToString());
                    var answer         = responseObject.GetValue("response").ToString();
                    return(answer);
                }
                catch (Exception e)
                {
                    Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "TalkWithCleverBot()", text));
                    return("The Cleverbot-API is currently unavailable.");
                }
            }
        }
示例#2
0
        private static void DoBackup()
        {
            Bot.NotifyDevs("Running scheduled backup...");
            string path       = filePath.Replace("jenkins.xml", "");
            string backupPath = Path.Combine(path, "backup");

            if (!Directory.Exists(backupPath))
            {
                Directory.CreateDirectory(backupPath);
            }
            string fileName = string.Format("jenkins_{0}.xml",
                                            Supporter.GetFileDateString(DateTime.Now));
            string combinedFilePath = Path.Combine(backupPath, fileName);

            //            if (!File.Exists(combinedFilePath))
            try
            {
                File.Copy(filePath, combinedFilePath, true);
            }
            catch (Exception e)
            {
                Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "DoBackup()", filePath + "\r\n" + combinedFilePath));
            }
            Bot.NotifyDevs(string.Format("Backup for **{0}** complete. :floppy_disk::white_check_mark:",
                                         Supporter.GetFileDateString(DateTime.Now)));

            CheckAndScheduleBackUp(true);
        }
示例#3
0
        private bool TryAssignRoleToUser(User user, Role role)
        {
            try
            {
                user.AddRoles(new Role[] { role });
                Bot.NotifyDevs("Added Role **" + role.Name + "** to user **" + user.Name + "** on server **" + user.Server.Name + "**");
                try
                {
                    if (Bot.Config.GamesSyncNotifyUsers)
                    {
                        if (TryGetTextChannel(role.Name, user.Server, out var tChannel))
                        {
                            Bot.SendMessage("Sup " + role.Mention + " player, " + user.Mention, tChannel);
                        }
                    }
                }
                catch (Exception e)
                {
                    Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "TryAssignRoleToUser", new object[] { user.Server.Name, user.Name, role.Name }));
                }

                return(true);
            }
            catch (Exception e)
            {
                Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, this.GetType().FullName));
                return(false);
            }
        }
示例#4
0
        private async void CompareRolesForUserAndAssign(User user, string[] games)
        {
            string currentGame = user.CurrentGame.Value.Name;

            if (games.Contains(currentGame))
            {
                var gameRoles = user.Server.FindRoles(currentGame, true);
                if (gameRoles.Count() == 1 && !user.HasRole(gameRoles.First()))
                {
                    // Role in server and user does not have it
                    // user.AddRoles(new Role[] { gameRole.First() });
                    TryAssignRoleToUser(user, gameRoles.First());
                    if (user.Server.FindChannels(ConvertToChannelName(currentGame), ChannelType.Text, true).Count() == 0)
                    {
                        await CreateGameChannel(user.Server, currentGame, gameRoles.First());
                    }
                }
                else
                {
                    if (gameRoles.Count() > 1)
                    {
                        Bot.NotifyDevs("One or more roles found for **" + currentGame + "** in Server **" + user.Server.Name + "** for user **" + user.Name + "**");
                    }
                    return; // Role isn't in server
                }
            }
        }
示例#5
0
        public static async void GetTrendingGIF(Channel channel)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    string response = await client.GetStringAsync(string.Format("http://api.giphy.com/v1/gifs/trending?api_key={0}&limit={1}"
                                                                                , Bot.Config.GiphyAPIKey
                                                                                , Bot.Config.GiphySearchLimit));

                    var    requestObject     = Newtonsoft.Json.Linq.JObject.Parse(response);
                    var    dataString        = requestObject.GetValue("data").ToString();
                    JArray dataObject        = Newtonsoft.Json.Linq.JArray.Parse(dataString);
                    var    arrayString       = dataObject.ElementAt(Supporter.GetRandom(Bot.Config.GiphySearchLimit)).ToString();
                    var    arrayObject       = Newtonsoft.Json.Linq.JObject.Parse(arrayString);
                    var    imagesString      = arrayObject.GetValue("images").ToString();
                    var    imagesObject      = Newtonsoft.Json.Linq.JObject.Parse(imagesString);
                    var    fixedHeightString = imagesObject.GetValue("fixed_height").ToString();
                    var    fixedHeightObject = Newtonsoft.Json.Linq.JObject.Parse(fixedHeightString);
                    string gifURL            = fixedHeightObject.GetValue("url").ToString();
                    await channel.SendMessage(gifURL);
                }
                catch (Exception e)
                {
                    Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "GetTrendingGIF()"));
                }
            }
        }
示例#6
0
        private static async void NotifyAbstinenceUsers()
        {
            Server server      = voteChannel.Server;
            var    onlineUsers = server.Users
                                 .Where(r =>
                                        r.IsBot.Equals(false))
                                 .Where(r =>
                                        r.Status.Value.Equals("online") ||
                                        r.Status.Value.Equals("idle") ||
                                        r.Status.Value.Equals("dnd") ||
                                        r.Status.Value.Equals("invisible"));

            if (onlineUsers.Count() == 0)
            {
                return;
            }
            int count = 0;

            foreach (var user in onlineUsers)
            {
                if (!userVotes.Keys.Contains(user.Id))
                {
                    await user.SendMessage(string.Format("Bisher habe ich noch keine Stimme von dir für die Abstimmung auf dem Server **{0}** aufgezeichnet.\r\nDu hast noch bis **{1}** Zeit dein vote abzugeben ansonsten wird deine Stimme als enthalten gezählt.\r\n/**vote** /**food** /**foodAll**",
                                                         server.Name,
                                                         nextVoteEnd.ToLongTimeString()));

                    count++;
                }
            }
            Bot.NotifyDevs(string.Format("Notifed {0} users to vote", count));
        }
示例#7
0
        private static void UpdateSchnautOffers(List <SchnautOffer> offers)
        {
            bool allOffersdeleted = false;
            int  index            = 1;

            while (!allOffersdeleted)
            {
                if (IsValidKRZ("SCHN" + index))
                {
                    DelFoodOption("SCHN" + index);
                    index = index + 1;
                }
                else
                {
                    allOffersdeleted = true;
                }
            }
            index = 1;
            List <string> addedItems = new List <string>();

            foreach (var offer in offers)
            {
                List <Food.Day> dayList = new List <Food.Day>();
                dayList.Add(offer.OfferDay);
                AddFoodOption("SCHN" + index, "Schnaut Launsbach", offer.Desc + " - " + offer.Price + "€", dayList.AsEnumerable(), "Vorbestellen unter 0641 82225");
                addedItems.Add("SCHN" + index);
                index = index + 1;
            }
            Bot.NotifyDevs(Supporter.BuildList("Added offers", addedItems.ToArray()));
            Jenkins.Write();
        }
示例#8
0
        public string GetFunFact(out string info, string term = "random", string type = "")
        {
            if (type == "" || !types.Contains(type))
            {
                type = TryParseType(term);
                if (type == "date")
                {
                    term = ConvertDate(term);
                }
            }

            using (var webClient = new WebClient())
            {
                string request = string.Format("http://numbersapi.com/{0}/{1}"
                                               , term
                                               , type);
                try
                {
                    info = "#FunFact about **" + term + "**";
                    return(webClient.DownloadString(request));
                }
                catch (Exception e)
                {
                    Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, this.GetType().FullName, request));
                    info = "";
                    return(string.Empty);
                }
            }
        }
示例#9
0
        private void CheckForStartedStreams()
        {
            if (!Bot.Config.ParseSuccessfull)
            {
                return;
            }
            string[] twitchChannels = Jenkins.Twitch.GetGlobalObservingTwitchChannels();

            Dictionary <ulong, string> broadcastList = new Dictionary <ulong, string>();

            foreach (var twitchChannel in twitchChannels)
            {
                string  request = "";
                ulong[] discordChannelsToBroadcast = Jenkins.Twitch.GetFollowingDiscordChannelsForTwitchChannel(twitchChannel);

                if (discordChannelsToBroadcast.Length == 0 && false) // ToDo Exception #1
                {
                    Bot.NotifyDevs("Incontinence in database for Twitch-Channel **" + twitchChannel + "**");
                    return;
                }

                request = string.Format("https://api.twitch.tv/kraken/streams/{0}?client_id={1}"
                                        , twitchChannel
                                        , Bot.Config.TwitchAPIKey);
                try
                {
                    using (var client = new HttpClient())
                    {
                        var response = client.GetStringAsync(request);
                        response.Wait();
                        var requestObject = JObject.Parse(response.Result);
                        var streamString  = requestObject.GetValue("stream").ToString();
                        if ((streamString != null && streamString != string.Empty))
                        {
                            var   streamObject = JObject.Parse(streamString);
                            ulong streamId     = ulong.Parse(streamObject.GetValue("_id").ToString());
                            if (Jenkins.Twitch.IsStreamNotPosted(streamId))
                            {
                                var channelString = streamObject.GetValue("channel").ToString();
                                var channelObject = JObject.Parse(channelString);
                                Jenkins.Twitch.AddStream(streamObject, channelObject);
                                string broadcast = Supporter.BuildStreamBroadcast(Jenkins.Twitch.GetStream(streamId));
                                foreach (var discordChannel in discordChannelsToBroadcast)
                                {
                                    broadcastList.Add(discordChannel, broadcast);
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "CheckForStartedStreams()", request));
                }
            }
            BroadcastStreamUpdates(broadcastList);
        }
示例#10
0
 private void SetUpTimer(TimeSpan timeToGo)
 {
     if (timeToGo < TimeSpan.Zero)
     {
         Bot.NotifyDevs("Unhandled exception(?) in SetUpTimer()\r\n" + timeToGo.ToString());
         return; //time already passed
     }
     timer = new System.Threading.Timer(x =>
     {
         CheckServers();
     }, null, timeToGo, Timeout.InfiniteTimeSpan);
 }
示例#11
0
 private static void SetUpNextVoteTimer(TimeSpan timeToGo, DateTime nextVoteEnd)
 {
     if (timeToGo < TimeSpan.Zero)
     {
         Bot.NotifyDevs("Unhandled exception(?) in SetUpNextVoteTimer()\r\n" + timeToGo.ToString());
         //SetUpTimer((new TimeSpan(1,0,0,0) - timeToGo.Negate()));
         return;//time already passed
     }
     nextVoteTimer = new System.Threading.Timer(x =>
     {
         StartVote(nextVoteEnd, Bot.Client.GetChannel(Bot.Config.DailyVoteChannel));
     }, null, timeToGo, Timeout.InfiniteTimeSpan);
 }
示例#12
0
 private static void SetUpTimer(TimeSpan timeToGo)
 {
     if (timeToGo < TimeSpan.Zero)
     {
         Bot.NotifyDevs("Unhandled exception(?) in SetUpTimer()\r\n" + timeToGo.ToString());
         //SetUpTimer((new TimeSpan(1,0,0,0) - timeToGo.Negate()));
         return;//time already passed
     }
     backupTimer = new System.Threading.Timer(x =>
     {
         DoBackup();
     }, null, timeToGo, Timeout.InfiniteTimeSpan);
 }
示例#13
0
 public static string Talk(string msg)
 {
     try
     {
         var msgTask = cleverBotSession.SendAsync(msg);
         msgTask.Wait();
         return(msgTask.Result);
     }
     catch (Exception e)
     {
         Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "Talk()", msg));
         return("The Cleverbot-API is currently unavailable.");
     }
 }
示例#14
0
 private static void SetUpNotificationTimer(TimeSpan timeToGo)
 {
     if (timeToGo < TimeSpan.Zero)
     {
         Bot.NotifyDevs("Unhandled exception(?) in SetUpNotificationTimer()\r\n" + timeToGo.ToString());
         return;
     }
     notificationTimer = new System.Threading.Timer(x =>
     {
         voteChannel.SendMessage("Das Voting läuft noch **" + Supporter.GetDurationGerman(nextVoteEnd - DateTime.Now) + "**\r\nStimmen können noch eingereicht werden mit /**vote** <KRZ>");
         NotifyAbstinenceUsers();
     }, null, timeToGo, Timeout.InfiniteTimeSpan);
     Bot.NotifyDevs("Notification set for " + DateTime.Now.Add(timeToGo).ToLongTimeString() + " in " + Supporter.GetDuration(timeToGo));
 }
示例#15
0
        private string ConvertDate(string arg)
        {
            DateTime dt;

            if (DateTime.TryParse(arg, out dt))
            {
                return(dt.ToString("MM/dd").Replace('.', '/'));
            }
            else
            {
                Bot.NotifyDevs("Could not parse date '" + arg + "' in " + this.GetType().FullName);
                return("random");
            }
        }
示例#16
0
 private async void BroadcastStreamUpdates(Dictionary <ulong, string> broadcasts)
 {
     foreach (var broadcast in broadcasts)
     {
         try
         {
             Channel channelToPost = Bot.Client.GetChannel(broadcast.Key);
             await channelToPost.SendMessage(broadcast.Value);
         }
         catch (Exception e)
         {
             Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "BroadcastStreamUpdates\r\nInconsistence for parametred channelId", new object[] { broadcast.Key }));
         }
     }
 }
示例#17
0
 private static void SetupBattletimer(string id)
 {
     timers.Add(id, new System.Threading.Timer(x =>
     {
         PRSGame prsGame;
         if (activeGames.TryGetValue(id, out prsGame))
         {
             FinishBattle(prsGame);
         }
         else
         {
             Bot.NotifyDevs("Could not find game for ID: " + id);
         }
     }, null, new TimeSpan(0, 5, 0), Timeout.InfiniteTimeSpan));
 }
示例#18
0
 public static void DownloadAndPlayURL(string URL, Message botMsg, User user, Channel vChannel)
 {
     TextChannel      = botMsg.Channel;
     MediaMessage     = botMsg;
     User             = user;
     vChannelToStream = vChannel;
     try
     {
         DownloadAudio(URL);
     }
     catch (Exception e)
     {
         Bot.NotifyDevs(Supporter.BuildExceptionMessage(e));
     }
 }
示例#19
0
        public static async void GetGIF(string keyword, Channel channel)
        {
            using (var client = new HttpClient())
            {
                try
                {
                    string response = await client.GetStringAsync(string.Format("http://api.giphy.com/v1/gifs/search?q={0}&api_key={1}&limit={2}"
                                                                                , keyword
                                                                                , Bot.Config.GiphyAPIKey
                                                                                , Bot.Config.GiphySearchLimit));

                    var    requestObject = Newtonsoft.Json.Linq.JObject.Parse(response);
                    var    dataString    = requestObject.GetValue("data").ToString();
                    JArray dataObject    = Newtonsoft.Json.Linq.JArray.Parse(dataString);
                    if (dataObject.Count == 0)
                    {
                        await channel.SendMessage(string.Format("There are no results for **{0}** :("
                                                                , keyword));

                        return;
                    }
                    var    arrayString       = dataObject.ElementAt(Supporter.GetRandom(dataObject.Count)).ToString();
                    var    arrayObject       = Newtonsoft.Json.Linq.JObject.Parse(arrayString);
                    var    imagesString      = arrayObject.GetValue("images").ToString();
                    var    imagesObject      = Newtonsoft.Json.Linq.JObject.Parse(imagesString);
                    var    fixedHeightString = imagesObject.GetValue("fixed_height").ToString();
                    var    fixedHeightObject = Newtonsoft.Json.Linq.JObject.Parse(fixedHeightString);
                    string gifURL            = fixedHeightObject.GetValue("url").ToString();
                    await channel.SendMessage(string.Format("**#{0}**\r\n{1}"
                                                            , keyword
                                                            , gifURL));
                }
                catch (Exception e)
                {
                    if (e.Message.Equals("Sequence contains no elements") || e.Message.Equals("Die Sequenz enthält keine Elemente") || e.Data.ToString() == "System.Collections.ListDictionaryInternal")
                    {
                        return;
                    }
                    Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "GetGIF()", keyword));
                }
            }
        }
示例#20
0
        private async System.Threading.Tasks.Task CreateGameChannel(Server server, string game, Role role)
        {
            try
            {
                var tChannel = await server.CreateChannel(ConvertToChannelName(game), ChannelType.Text);

                await tChannel.Edit(tChannel.Name, "Everyone who got @" + game);

                await tChannel.AddPermissionsRule(server.EveryoneRole, new ChannelPermissions(0), new ChannelPermissions(523328));

                await tChannel.AddPermissionsRule(role, new ChannelPermissions(384064), new ChannelPermissions(8192));

                await tChannel.SendMessage("Welcome " + role.Mention + " players! :video_game:");

                Bot.NotifyDevs("Created channel **#" + tChannel.Name + "** in server **" + server.Name + "**");
            }
            catch (Exception e)
            {
                Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "CreateGameChannel"));
            }
        }
示例#21
0
        private async void CheckForNewServerroles(Server server, string[] currentGames)
        {
            var duplicateGames = currentGames.GroupBy(x => x)
                                 .Where(group => group.Count() > (Bot.Config.CreateNewRoleLimit - 1))
                                 .Select(group => group.Key);

            foreach (var game in duplicateGames)
            {
                if (server.FindRoles(game, true).Count() == 0)
                {
                    await server.CreateRole(game, null, Supporter.GetRandomColor(), false, true);

                    Bot.NotifyDevs("Created Role **" + game + "** in Server **" + server.Name + "**");
                }
                IEnumerable <Role> roles = server.FindRoles(game, true);
                if (server.FindChannels(ConvertToChannelName(game), ChannelType.Text, true).Count() == 0 && roles.Count() == 1)
                {
                    await CreateGameChannel(server, game, roles.First());
                }
            }
        }
示例#22
0
        public string TryParseType(string arg)
        {
            int   n;
            Regex r = new Regex("^[a-zA-Z0-9]*$");

            if (int.TryParse(arg, out n))
            {
                return("math");
            }
            else if (arg.Contains("/") || IsMonth(arg))
            {
                return("date");
            }
            else if (r.IsMatch(arg))
            {
                return("trivia");
            }
            else
            {
                Bot.NotifyDevs("Could not parse argument: " + arg);
                return("trivia");
            }
        }
示例#23
0
        private async static void DownloadAudio(string URL)
        {
            string link = URL;
            IEnumerable <YoutubeExtractor.VideoInfo> videoInfos = null;

            try
            {
                videoInfos   = DownloadUrlResolver.GetDownloadUrls(link);
                MediaMessage = await TextChannel.SendMessage("Downloading audio...");
            }
            catch (Exception)
            {
                await MediaMessage.Delete();

                await User.SendMessage("Invalid link :(");

                return;
            }

            VideoInfo video = videoInfos.First(info => info.VideoType == VideoType.Mp4 && info.Resolution == 0);

            mediaName = video.Title;
            audioPath = Path.Combine(Environment.CurrentDirectory, "files", "audio", video.Title + video.AudioExtension);
            mp3Path   = Path.Combine(Environment.CurrentDirectory, "files", "mp3", video.Title + ".mp3");
            var audioDownloader = new VideoDownloader(video, audioPath);

            audioDownloader.DownloadFinished += AudioDownloader_DownloadFinished;
            try
            {
                audioDownloader.Execute();
            }
            catch (Exception e)
            {
                Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "DownloadAudio()", URL));
                await MediaMessage.Edit("Failed downloading audio");
            }
        }
示例#24
0
 public void RegisterTwitchChannel(string name, Channel channel = null)
 {
     using (var client = new HttpClient())
     {
         string request = string.Format("https://api.twitch.tv/kraken/channels/{0}?client_id={1}"
                                        , name
                                        , Bot.Config.TwitchAPIKey);
         try
         {
             var response = client.GetStringAsync(request);
             response.Wait();
             var channelObject = JObject.Parse(response.Result);
             Jenkins.Twitch.AddTwitchChannel(channelObject);
         }
         catch (Exception e)
         {
             Bot.NotifyDevs(Supporter.BuildExceptionMessage(e, "RegisterTwitchChannel()", request));
             if (channel != null)
             {
                 Bot.SendMessage("There's no Twitch-Channel called **" + name + "** :(", channel);
             }
         }
     }
 }