Example #1
0
 public async Task leave(string serverName = null)
 {
     p.doAction(Context.User, Context.Guild.Id, Program.Module.Settings);
     if (Context.User.Id != Sentences.ownerId)
     {
         await ReplyAsync(Sentences.onlyMasterStr(Context.Guild.Id));
     }
     else
     {
         if (serverName == null)
         {
             await Context.Guild.LeaveAsync();
         }
         else
         {
             IGuild g = p.client.Guilds.ToList().Find(x => x.Name.ToUpper() == serverName.ToUpper());
             if (g == null)
             {
                 await ReplyAsync(Sentences.noCorrespondingGuild(Context.Guild.Id));
             }
             else
             {
                 await g.LeaveAsync();
                 await ReplyAsync(Sentences.doneStr(Context.Guild.Id));
             }
         }
     }
 }
Example #2
0
        public async Task randomPastebin()
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.GoogleShortener);
            if (!(Context.Channel as ITextChannel).IsNsfw)
            {
                await ReplyAsync(Sentences.chanIsNotNsfw(Context.Guild.Id));
            }
            else
            {
                Tuple <string, string> result = null;
                try
                {
                    result = await getUrl();
                }
                catch (GoogleApiException ex)
                {
                    if (ex.HttpStatusCode == HttpStatusCode.Forbidden)
                    {
                        await ReplyAsync(Sentences.tooManyRequests(Context.Guild.Id, "goo.gl"));

                        return;
                    }
                }
                if (result == null)
                {
                    await ReplyAsync(Sentences.nothingAfterXIterations(Context.Guild.Id, 500));
                }
                else
                {
                    await ReplyAsync("I found something, here is the short URL: " + result.Item1 + Environment.NewLine
                                     + ((result != null) ? ("It'll lead you here: " + result.Item2) : ("It will lead you nowhere since the URL was disabled...")));
                }
            }
        }
Example #3
0
        public static async Task <Tuple <string, string> > GetYoutubeVideo(string[] words, IMessageChannel chan, int maxResult = 1)
        {
            if (words.Length == 0)
            {
                await chan.SendMessageAsync(Sentences.youtubeHelp((chan as ITextChannel).GuildId));

                return(null);
            }
            var searchListRequest = Program.p.youtubeService.Search.List("snippet");

            searchListRequest.Q          = Program.addArgs(words);
            searchListRequest.MaxResults = maxResult;
            var searchListResponse = await searchListRequest.ExecuteAsync();

            if (searchListResponse.Items.Count < maxResult)
            {
                await chan.SendMessageAsync(Sentences.youtubeNotFound((chan as ITextChannel).GuildId));

                return(null);
            }
            Google.Apis.YouTube.v3.Data.SearchResult sr = searchListResponse.Items[maxResult - 1];
            if (sr.Id.Kind != "youtube#video")
            {
                return(await GetYoutubeVideo(words, chan, maxResult + 1));
            }
            else
            {
                return(new Tuple <string, string>("https://www.youtube.com/watch?v=" + sr.Id.VideoId, sr.Snippet.Title));
            }
        }
Example #4
0
        private async Task GuildJoin(SocketGuild arg)
        {
            string       currTime = DateTime.UtcNow.ToString("ddMMyyHHmmss");
            ITextChannel chan     = returnChannel(arg.Channels.ToList(), arg.Id);

            if (!Directory.Exists("Saves"))
            {
                Directory.CreateDirectory("Saves");
            }
            if (!File.Exists("Saves/sanaraDatas.dat"))
            {
                File.WriteAllText("Saves/sanaraDatas.dat", currTime); // Creation date
            }
            if (!Directory.Exists("Saves/Servers/" + arg.Id))
            {
                Directory.CreateDirectory("Saves/Servers/" + arg.Id);
                File.WriteAllText("Saves/Servers/" + arg.Id + "/serverDatas.dat", currTime + Environment.NewLine + 0 + Environment.NewLine + arg.Name); // Join date | unused | server name
                await chan.SendMessageAsync(Sentences.introductionMsg(arg.Id));
            }
            if (!File.Exists("Saves/Servers/" + arg.Id + "/kancolle.dat"))
            {
                File.WriteAllText("Saves/Servers/" + arg.Id + "/kancolle.dat", "0" + Environment.NewLine + "0" + Environment.NewLine + "0" + Environment.NewLine + "0" + Environment.NewLine + "0");
            }
            // Attempt game, attempt ship, ship found, bestScore, ids of people who help to have the best score
            if (!Directory.Exists("Saves/Users"))
            {
                Directory.CreateDirectory("Saves/Users");
            }
            guildLanguages.Add(arg.Id, (File.Exists("Saves/Servers/" + arg.Id + "/language.dat")) ? (File.ReadAllText("Saves/Servers/" + arg.Id + "/language.dat")) : ("en"));
            prefixs.Add(arg.Id, (File.Exists("Saves/Servers/" + arg.Id + "/prefix.dat")) ? (File.ReadAllText("Saves/Servers/" + arg.Id + "/prefix.dat")) : ("s."));
            foreach (IUser u in arg.Users)
            {
                if (!File.Exists("Saves/Users/" + u.Id + ".dat"))
                {
                    relations.Add(new Character(u.Id, u.Username));
                }
                else
                {
                    try
                    {
                        if (!relations.Any(x => x._name == Convert.ToUInt64(File.ReadAllLines("Saves/Users/" + u.Id + ".dat")[1])))
                        {
                            relations.Add(new Character());
                            relations[relations.Count - 1].saveAndParseInfos(File.ReadAllLines("Saves/Users/" + u.Id + ".dat"));
                        }
                    }
                    catch (IndexOutOfRangeException)
                    {
                        if (arg.Id.ToString() == File.ReadAllLines("Saves/sanaraDatas.dat")[2])
                        {
                            await chan.SendMessageAsync(Sentences.introductionError(arg.Id, u.Id.ToString(), u.Username));
                        }
                    }
                }
            }
        }
Example #5
0
            public async Task <bool> Skip(IMessageChannel chan)
            {
                if (m_process == null)
                {
                    return(false);
                }
                await chan.SendMessageAsync(Sentences.songSkipped((chan as ITextChannel).GuildId, m_musics[0].title));

                m_process.Kill();
                return(true);
            }
Example #6
0
 public async Task listRadio(params string[] words)
 {
     p.doAction(Context.User, Context.Guild.Id, Program.Module.Radio);
     if (!p.radios.Any(x => x.m_guildId == Context.Guild.Id))
     {
         await ReplyAsync(Sentences.radioNotStarted(Context.Guild.Id));
     }
     else
     {
         await ReplyAsync(p.radios.Find(x => x.m_guildId == Context.Guild.Id).GetPlaylist(Context.Guild.Id));
     }
 }
Example #7
0
        public async Task map(params string[] mapName)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Kancolle);
            if (mapName.Length != 2 || mapName[0].Length != 1 || mapName[1].Length != 1 ||
                mapName[0][0] <= '0' || mapName[0][0] > '6' || mapName[1][0] <= '0' || mapName[1][0] > '6' ||
                (mapName[0][0] != '1' && mapName[1][0] == '6'))
            {
                await ReplyAsync(Sentences.mapHelp(Context.Guild.Id));

                return;
            }
            using (WebClient wc = new WebClient())
            {
                string url  = "http://kancolle.wikia.com/wiki/World_" + mapName[0][0] + "/" + mapName[0][0] + "-" + mapName[1][0];
                string html = wc.DownloadString(url);
                wc.Encoding = Encoding.UTF8;
                string htmlRaw = wc.DownloadString(url + "?action=raw");
                html = html.Split(new string[] { "typography-xl-optout" }, StringSplitOptions.None)[1];
                string[] allLinks    = html.Split(new string[] { "href=" }, StringSplitOptions.None);
                int      currentTime = Convert.ToInt32(DateTime.Now.ToString("HHmmss"));
                wc.DownloadFile(Program.getElementXml("\"", allLinks[1], '"'), "kancolleMap" + currentTime + "1.png");
                wc.DownloadFile(Program.getElementXml("\"", allLinks[2], '"'), "kancolleMap" + currentTime + "2.png");
                await ReplyAsync(Program.getElementXml("|en = ", htmlRaw, '\n'));

                await Context.Channel.SendFileAsync("kancolleMap" + currentTime + "1.png");

                await Context.Channel.SendFileAsync("kancolleMap" + currentTime + "2.png");

                File.Delete("kancolleMap" + currentTime + "1.png");
                File.Delete("kancolleMap" + currentTime + "2.png");
                string branchingRules;
                if (htmlRaw.Contains("{{MapBranchingTable"))
                {
                    branchingRules = htmlRaw.Split(new string[] { "{{MapBranchingTable" }, StringSplitOptions.None)[1];
                }
                else
                {
                    branchingRules = htmlRaw.Split(new string[] { "{{Map/Branching" }, StringSplitOptions.None)[1];
                }
                string[] allBranches = branchingRules.Split(new string[] { "}}" }, StringSplitOptions.None)[0].Split('\n');
                string   finalStr    = "";
                foreach (string currBranch in allBranches)
                {
                    if (currBranch.Length == 0 || currBranch.StartsWith("|title") || currBranch.StartsWith("|id"))
                    {
                        continue;
                    }
                    string line = currBranch.Substring(1, currBranch.Length - 1);
                    finalStr += line + Environment.NewLine;
                }
                await ReplyAsync(finalStr);
            }
        }
Example #8
0
        public async Task randomXkcd(params string[] command)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Xkcd);
            int?myNb = null;

            if (command.Length > 0)
            {
                try
                {
                    myNb = Convert.ToInt32(Program.addArgs(command));
                }
                catch (FormatException)
                {
                    await ReplyAsync(Sentences.xkcdWrongArg(Context.Guild.Id));

                    return;
                }
                catch (OverflowException)
                {
                    await ReplyAsync(Sentences.xkcdWrongArg(Context.Guild.Id));

                    return;
                }
            }
            using (WebClient wc = new WebClient())
            {
                string json  = wc.DownloadString("https://xkcd.com/info.0.json");
                int    nbMax = Convert.ToInt32(Program.getElementXml("\"num\":", json, ','));
                int    nb;
                if (myNb == null)
                {
                    nb = p.rand.Next(nbMax) + 1;
                }
                else
                {
                    if (myNb < 1 || myNb > nbMax)
                    {
                        await ReplyAsync(Sentences.xkcdWrongId(Context.Guild.Id, nbMax));

                        return;
                    }
                    nb = (int)myNb;
                }
                json = wc.DownloadString("https://xkcd.com/" + nb.ToString() + "/info.0.json");
                string dlUrl    = Program.getElementXml("\"img\": \"", json, '"');
                string currName = "xkcd" + DateTime.Now.ToString("HHmmssfff") + Context.Guild.ToString() + Context.User.Id.ToString() + "." + dlUrl.Split('.')[dlUrl.Split('.').Length - 1];
                wc.DownloadFile(dlUrl, currName);
                await Context.Channel.SendFileAsync(currName);

                File.Delete(currName);
            }
        }
Example #9
0
 public async Task reloadLanguage()
 {
     p.doAction(Context.User, Context.Guild.Id, Program.Module.Settings);
     if (Context.User.Id != Sentences.ownerId)
     {
         await ReplyAsync(Sentences.onlyMasterStr(Context.Guild.Id));
     }
     else
     {
         p.UpdateLanguageFiles();
         await ReplyAsync(Sentences.doneStr(Context.Guild.Id));
     }
 }
Example #10
0
        public async Task playShiritori(params string[] gameName)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Game);
            if (p.games.Any(x => x.m_chan == Context.Channel))
            {
                await ReplyAsync(Sentences.gameAlreadyRunning(Context.Guild.Id));
            }
            else
            {
                string finalGameName = Program.addArgs(gameName);
                if (finalGameName == null || (finalGameName.ToLower() != "shiritori" && finalGameName.ToLower() != "kancolle" && finalGameName.ToLower() != "booru"))
                {
                    await ReplyAsync(Sentences.invalidGameName(Context.Guild.Id));
                }
                else
                {
                    if (!p.gameThread.IsAlive)
                    {
                        p.gameThread.Start();
                    }
                    Game g = null;
                    if (finalGameName.ToLower() == "shiritori")
                    {
                        await ReplyAsync(Sentences.rulesShiritori(Context.Guild.Id));

                        g = new Shiritori(Context.Channel, Context.Guild, Context.User);
                    }
                    else if (finalGameName.ToLower() == "kancolle")
                    {
                        await ReplyAsync(Sentences.rulesKancolle(Context.Guild.Id));

                        g = new Kancolle(Context.Channel, Context.Guild, Context.User);
                    }
                    else if (finalGameName.ToLower() == "booru")
                    {
                        if (!(Context.Channel as ITextChannel).IsNsfw)
                        {
                            await ReplyAsync(Sentences.chanIsNotNsfw(Context.Guild.Id));

                            return;
                        }
                        await ReplyAsync(Sentences.rulesBooru(Context.Guild.Id));

                        g = new BooruGame(Context.Channel, Context.Guild, Context.User);
                    }
                    p.games.Add(g);
                    g.Post();
                }
            }
        }
Example #11
0
            public string GetPlaylist(ulong guildId)
            {
                if (m_process == null || m_process.HasExited)
                {
                    return(Sentences.radioNoSong(guildId));
                }
                string finalStr = "🎵 Current: " + m_musics[0].title + Environment.NewLine;

                for (int i = 1; i < m_musics.Count; i++)
                {
                    finalStr += i + ". " + m_musics[i].title + ((m_musics[i].downloading) ? (" (Downloading...)") : ("")) + Environment.NewLine;
                }
                return(finalStr);
            }
Example #12
0
        public async Task addRadio(params string[] words)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Radio);
            if (words.Length == 0)
            {
                await ReplyAsync(Sentences.radioNeedArg(Context.Guild.Id));
            }
            else if (p.radios.Any(x => x.m_guildId == Context.Guild.Id) && !p.radios.Find(x => x.m_guildId == Context.Guild.Id).CanAddMusic())
            {
                await ReplyAsync(Sentences.radioTooMany(Context.Guild.Id));
            }
            else
            {
                if (!p.radios.Any(x => x.m_guildId == Context.Guild.Id))
                {
                    if (!await StartRadio(Context.Channel))
                    {
                        return;
                    }
                }
                Tuple <string, string> youtubeResult = await YoutubeModule.GetYoutubeVideo(words, Context.Channel);

                if (youtubeResult != null)
                {
                    RadioChannel radio = p.radios.Find(x => x.m_guildId == Context.Guild.Id);
                    if (radio.ContainMusic(youtubeResult.Item1))
                    {
                        await ReplyAsync(Sentences.radioAlreadyInList(Context.Guild.Id));

                        return;
                    }
                    radio.AddMusic("Saves/Radio/" + radio.m_guildId + "/" + Program.cleanWord(youtubeResult.Item2) + ".mp3", youtubeResult.Item2, youtubeResult.Item1, await Context.Guild.GetUserAsync(Sentences.myId), Context.Guild.Id.ToString());
                    YouTubeVideo video = GetYoutubeVideo(youtubeResult.Item1);
                    if (video == null)
                    {
                        radio.RemoveSong(youtubeResult.Item1);
                        await ReplyAsync(Sentences.cantDownload(Context.Guild.Id));
                    }
                    else
                    {
                        await ReplyAsync(youtubeResult.Item2 + " was added to the list.");

                        DownloadAudio(video, radio, youtubeResult.Item1, Program.cleanWord(youtubeResult.Item2));
                    }
                }
            }
        }
Example #13
0
        public async Task stopRadio(params string[] words)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Radio);
            RadioChannel radio = p.radios.Find(x => x.m_guildId == Context.Guild.Id);

            if (radio == null)
            {
                await ReplyAsync(Sentences.radioNotStarted(Context.Guild.Id));
            }
            else
            {
                await radio.Stop();

                p.radios.Remove(radio);
                await ReplyAsync(Sentences.doneStr(Context.Guild.Id));
            }
        }
Example #14
0
        public async Task skipRadio(params string[] words)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Radio);
            RadioChannel radio = p.radios.Find(x => x.m_guildId == Context.Guild.Id);

            if (radio == null)
            {
                await ReplyAsync(Sentences.radioNotStarted(Context.Guild.Id));
            }
            else
            {
                bool suceed = await radio.Skip(Context.Channel);

                if (!suceed)
                {
                    await ReplyAsync(Sentences.radioNoSong(Context.Guild.Id));
                }
            }
        }
Example #15
0
        public async Task archive()
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Settings);
            if (Context.User.Id != 144851584478740481)
            {
                await ReplyAsync(Sentences.onlyMasterStr(Context.Guild.Id));
            }
            else
            {
                await ReplyAsync(Sentences.copyingFiles(Context.Guild.Id));

                if (!Directory.Exists("Archives"))
                {
                    Directory.CreateDirectory("Archives");
                }
                string currTime = DateTime.UtcNow.ToString("yy-MM-dd-HH-mm-ss");
                Directory.CreateDirectory("Archives/" + currTime);
                copyContent("Saves", "Archives/" + currTime);
                await ReplyAsync(Sentences.createArchiveStr(Context.Guild.Id, currTime));
            }
        }
Example #16
0
        private async Task <bool> StartRadio(IMessageChannel chan)
        {
            if (p.radios.Any(x => x.m_guildId == Context.Guild.Id))
            {
                await chan.SendMessageAsync(Sentences.radioAlreadyStarted(Context.Guild.Id));

                return(true);
            }
            IGuildUser guildUser = Context.User as IGuildUser;

            if (guildUser.VoiceChannel == null)
            {
                await chan.SendMessageAsync(Sentences.radioNeedChannel(Context.Guild.Id));

                return(false);
            }
            IAudioClient audioClient = await guildUser.VoiceChannel.ConnectAsync();

            p.radios.Add(new RadioChannel(guildUser.VoiceChannel, Context.Channel, audioClient)); // You need opus.dll and libsodium.dll
            return(true);
        }
Example #17
0
        public async Task mal(params string[] animeNameArr)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.AnimeManga);
            string animeName = Program.addArgs(animeNameArr);

            if (animeName.Length == 0)
            {
                await ReplyAsync(Sentences.animeHelp(Context.Guild.Id));

                return;
            }
            try
            {
                string result = p.malClient.DownloadString("https://myanimelist.net/api/anime/search.xml?q=" + animeName.Replace(" ", "%20"));
                if (!result.Contains("<entry>"))
                {
                    await ReplyAsync(Sentences.animeNotFound(Context.Guild.Id));
                }
                else
                {
                    EmbedBuilder b = parseContent(result, animeName, (Context.Channel as ITextChannel).IsNsfw);
                    await ReplyAsync("", false, b.Build());
                }
            }
            catch (WebException ex)
            {
                HttpWebResponse code = ex.Response as HttpWebResponse;
                if (code != null)
                {
                    if (code.StatusCode == HttpStatusCode.Forbidden)
                    {
                        await ReplyAsync(Sentences.tooManyRequests(Context.Guild.Id, "MyAnimeList"));
                    }
                }
                else
                {
                    await ReplyAsync("An unexpected error occured: " + ex.Message);
                }
            }
        }
Example #18
0
        public async Task malManga(params string[] mangaNameArr) // Stuck in loop ?
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.AnimeManga);
            string mangaName = Program.addArgs(mangaNameArr);

            if (mangaName.Length == 0)
            {
                await ReplyAsync(Sentences.animeHelp(Context.Guild.Id));

                return;
            }
            try
            {
                string result = p.malClient.DownloadString("https://myanimelist.net/api/manga/search.xml?q=" + mangaName.Replace(" ", "%20"));
                if (!result.Contains("<entry>"))
                {
                    await ReplyAsync(Sentences.mangaNotFound(Context.Guild.Id));
                }
                else
                {
                    EmbedBuilder b = parseContent(result, mangaName, (Context.Channel as ITextChannel).IsNsfw);
                    if (b == null)
                    {
                        await ReplyAsync(Sentences.chanIsNotNsfw(Context.Guild.Id));
                    }
                    else
                    {
                        await ReplyAsync("", false, b.Build());
                    }
                }
            }
            catch (WebException ex)
            {
                HttpWebResponse code = ex.Response as HttpWebResponse;
                if (code.StatusCode == HttpStatusCode.Forbidden)
                {
                    await ReplyAsync(Sentences.tooManyRequests(Context.Guild.Id, "MyAnimeList"));
                }
            }
        }
Example #19
0
        public async Task Infos(params string[] command)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Communication);
            IGuildUser user;

            if (command.Length == 0)
            {
                user = Context.User as IGuildUser;
            }
            else
            {
                user = await Program.GetUser(Program.addArgs(command), Context.Guild);

                if (user == null)
                {
                    await ReplyAsync(Sentences.userNotExist(Context.Guild.Id));

                    return;
                }
            }
            await InfosUser(user);
        }
Example #20
0
 public async Task setLanguage(params string[] language)
 {
     p.doAction(Context.User, Context.Guild.Id, Program.Module.Settings);
     if (Context.User.Id != Context.Guild.OwnerId)
     {
         await ReplyAsync(Sentences.onlyOwnerStr(Context.Guild.Id, Context.Guild.OwnerId));
     }
     else if (language.Length == 0)
     {
         await ReplyAsync(Sentences.needLanguage(Context.Guild.Id));
     }
     else
     {
         string nextLanguage = Program.addArgs(language);
         string lang         = null;
         if (p.allLanguages.ContainsKey(nextLanguage))
         {
             lang = nextLanguage;
         }
         foreach (var key in p.allLanguages)
         {
             if (key.Value.Contains(nextLanguage))
             {
                 lang = key.Key;
                 break;
             }
         }
         if (lang == null)
         {
             await ReplyAsync(Sentences.needLanguage(Context.Guild.Id));
         }
         else
         {
             p.guildLanguages[Context.Guild.Id] = lang;
             File.WriteAllText("Saves/Servers/" + Context.Guild.Id + "/language.dat", lang);
             await ReplyAsync(Sentences.doneStr(Context.Guild.Id));
         }
     }
 }
Example #21
0
 public async Task setPrefix(params string[] command)
 {
     p.doAction(Context.User, Context.Guild.Id, Program.Module.Settings);
     if (Context.User.Id != Context.Guild.OwnerId)
     {
         await ReplyAsync(Sentences.onlyOwnerStr(Context.Guild.Id, Context.Guild.OwnerId));
     }
     else
     {
         if (command.Length == 0)
         {
             p.prefixs[Context.Guild.Id] = "";
             File.WriteAllText("Saves/Servers/" + Context.Guild.Id + "/prefix.dat", "");
             await ReplyAsync(Sentences.prefixRemoved(Context.Guild.Id));
         }
         else
         {
             string prefix = Program.addArgs(command);
             p.prefixs[Context.Guild.Id] = prefix;
             File.WriteAllText("Saves/Servers/" + Context.Guild.Id + "/prefix.dat", prefix);
             await ReplyAsync(Sentences.doneStr(Context.Guild.Id));
         }
     }
 }
Example #22
0
        private async Task HandleCommandAsync(SocketMessage arg)
        {
            var msg = arg as SocketUserMessage;

            if (msg == null)
            {
                return;
            }
            if (arg.Author.Id == 352216646267437059)
            {
                /// Get some informations about the bot for statistics purposes
                if (arg.Content == "<@&330483872544587776> Please send me your informations for comparison.")
                {
                    List <ulong> users = new List <ulong>();
                    foreach (var g in client.Guilds)
                    {
                        foreach (var g2 in g.Users)
                        {
                            if (!users.Contains(g2.Id))
                            {
                                users.Add(g2.Id);
                            }
                        }
                    }
                    int      nbMsgs = 0;
                    DateTime dt     = DateTime.UtcNow;
                    if (Directory.Exists("Saves/Stats/" + dt.Month.ToString()))
                    {
                        foreach (string s in Directory.GetFiles("Saves/Stats/" + dt.Month.ToString()))
                        {
                            nbMsgs += Convert.ToInt32(File.ReadAllText(s));
                        }
                    }
                    await(((ITextChannel)(arg.Channel))).SendMessageAsync($"<@{Sentences.idPikyu}> Here are the compare informations: " + client.Guilds.Count + "|" + users.Count + "|" + getLenghtFolder("Saves") + "o|Zirk|" + nbMsgs);
                }
            }
            /// When playing games
            else if (arg.Author.Id != Sentences.myId)
            {
                GameModule.Game game = games.Find(x => x.m_chan == arg.Channel);
                if (game != null)
                {
                    game.CheckCorrect(arg.Content, arg.Author);
                }
            }
            int    pos    = 0;
            string prefix = prefixs[(arg.Channel as ITextChannel).GuildId];

            if (msg.HasMentionPrefix(client.CurrentUser, ref pos) || (prefix != "" && msg.HasStringPrefix(prefix, ref pos)))
            {
                var context = new SocketCommandContext(client, msg);
                if (context.Guild == null)
                {
                    await context.Channel.SendMessageAsync(Sentences.dontPm(446053427714326528)); // Workaround because can't get id of null guild

                    return;
                }
                DateTime dt     = DateTime.UtcNow;
                var      result = await commands.ExecuteAsync(context, pos);

                // Count how many messages the bot receive
                if (result.IsSuccess && !context.User.IsBot)
                {
                    commandReceived++;
                    if (!Directory.Exists("Saves"))
                    {
                        Directory.CreateDirectory("Saves");
                    }
                    if (!Directory.Exists("Saves/Stats"))
                    {
                        Directory.CreateDirectory("Saves/Stats");
                    }
                    if (!Directory.Exists("Saves/Stats/" + dt.Month.ToString()))
                    {
                        Directory.CreateDirectory("Saves/Stats/" + dt.Month.ToString());
                    }
                    if (File.Exists("Saves/Stats/" + dt.Month.ToString() + '/' + dt.Day.ToString() + ".dat"))
                    {
                        File.WriteAllText("Saves/Stats/" + dt.Month.ToString() + '/' + dt.Day.ToString() + ".dat", (Convert.ToInt32(File.ReadAllText("Saves/Stats/" + dt.Month.ToString() + '/' + dt.Day.ToString() + ".dat")) + 1).ToString());
                    }
                    else
                    {
                        File.WriteAllText("Saves/Stats/" + dt.Month.ToString() + '/' + dt.Day.ToString() + ".dat", "1");
                    }
                    File.WriteAllText("Saves/CommandReceived.dat", commandReceived + Environment.NewLine + lastHourSent);
                }
            }
        }
Example #23
0
        public async Task Indent(params string[] arg)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Code);
            if (arg.Length == 0)
            {
                await ReplyAsync(Sentences.indenteHelp(Context.Guild.Id));

                return;
            }
            List <string> code   = new List <string>();
            string        curr   = "";
            bool          inCond = false;

            foreach (string s in arg)
            {
                if (s.StartsWith("```"))
                {
                    curr += s;
                    code.Add(curr);
                    curr = "";
                }
                else if (s[s.Length - 1] == ';')
                {
                    curr += s;
                    code.Add(curr);
                    curr = "";
                }
                else if (s == "try" || s == "{" || s == "}")
                {
                    code.Add(curr);
                    code.Add(s);
                    curr = "";
                }
                else if (s.StartsWith("for") || s.StartsWith("while") || s.StartsWith("if") || s.StartsWith("else") || s.StartsWith("catch"))
                {
                    curr  += s + ' ';
                    inCond = true;
                }
                else if (inCond && s[s.Length - 1] == ')')
                {
                    curr += s;
                    code.Add(curr);
                    curr   = "";
                    inCond = false;
                }
                else
                {
                    curr += s + ' ';
                }
            }
            string finalStr    = "";
            int    currIndente = 0;
            bool   tmpIdent    = false;

            foreach (string s in code)
            {
                if (s == "")
                {
                    continue;
                }
                string line = s;
                if (line.StartsWith("for") || line.StartsWith("while") || line.StartsWith("if") || line.StartsWith("else") || s.StartsWith("catch"))
                {
                    tmpIdent = true;
                    for (int i = 0; i < currIndente; i++)
                    {
                        finalStr += '\t';
                    }
                    finalStr += line + Environment.NewLine;
                    continue;
                }
                else if (line[0] == '{')
                {
                    for (int i = 0; i < currIndente; i++)
                    {
                        finalStr += '\t';
                    }
                    finalStr += line + Environment.NewLine;
                    currIndente++;
                    tmpIdent = false;
                    continue;
                }
                else if (line[0] == '}')
                {
                    currIndente--;
                    tmpIdent = false;
                }
                for (int i = 0; i < currIndente; i++)
                {
                    finalStr += '\t';
                }
                if (tmpIdent)
                {
                    finalStr += '\t';
                }
                finalStr += line + Environment.NewLine;
                tmpIdent  = false;
            }
            await ReplyAsync(finalStr);
        }
Example #24
0
#pragma warning restore CS1998

        /// <summary>
        /// Get an image given various informations
        /// </summary>
        /// <param name="booru">Which booru is concerned (see above)</param>
        /// <param name="tags">Tags that need to be contain on the image</param>
        /// <param name="chan">Channel the image will be post in</param>
        /// <param name="currName">Temporary name of the file</param>
        /// <param name="isSfw">Is the channel safe for work ?</param>
        /// <param name="isGame">If the request from Game module (doesn't count dl for stats and don't get informations about tags)</param>
        public static async void getImage(Booru booru, string[] tags, ITextChannel chan, string currName, bool isSfw, bool isGame)
        {
            if (!isSfw && !chan.IsNsfw)
            {
                await chan.SendMessageAsync(Sentences.chanIsNotNsfw(chan.GuildId));

                return;
            }
            IGuildUser me = await chan.Guild.GetUserAsync(Sentences.myId);

            if (!me.GuildPermissions.AttachFiles)
            {
                await chan.SendMessageAsync(Sentences.needAttachFile(chan.GuildId));

                return;
            }
            if (!isGame)
            {
                await chan.SendMessageAsync(Sentences.prepareImage(chan.GuildId));
            }
            string url = getBooruUrl(booru, tags);

            if (url == null)
            {
                await chan.SendMessageAsync(Sentences.tagsNotFound(tags));
            }
            else
            {
                using (WebClient wc = new WebClient())
                {
                    wc.Headers.Add("User-Agent: Sanara");
                    string json      = wc.DownloadString(url);
                    string image     = booru.getFileUrl(json);
                    string imageName = currName + "." + image.Split('.')[image.Split('.').Length - 1];
                    wc.Headers.Add("User-Agent: Sanara");
                    wc.DownloadFile(image, imageName);
                    FileInfo file = new FileInfo(imageName);
                    Program.p.statsMonth[(int)booru.getId()] += file.Length;
                    if (file.Length >= 8000000)
                    {
                        await chan.SendMessageAsync(Sentences.fileTooBig(chan.GuildId));
                    }
                    else
                    {
                        while (true)
                        {
                            try
                            {
                                await chan.SendFileAsync(imageName);

                                break;
                            }
                            catch (RateLimitedException) { }
                        }
                        if (!isGame)
                        {
                            List <string> finalStr = getTagsInfos(json, booru);
                            foreach (string s in finalStr)
                            {
                                await chan.SendMessageAsync(s);
                            }
                        }
                    }
                    File.Delete(imageName);
                }
                if (!isGame)
                {
                    string finalStrModule = "";
                    foreach (long i in Program.p.statsMonth)
                    {
                        finalStrModule += i + "|";
                    }
                    finalStrModule = finalStrModule.Substring(0, finalStrModule.Length - 1);
                    File.WriteAllText("Saves/MonthModules.dat", finalStrModule + Environment.NewLine + Program.p.lastMonthSent);
                }
            }
        }
Example #25
0
 public async Task WhoAreYou()
 {
     p.doAction(Context.User, Context.Guild.Id, Program.Module.Communication);
     await ReplyAsync(Sentences.whoIAmStr(Context.Guild.Id));
 }
Example #26
0
 public async Task SayHi()
 {
     p.doAction(Context.User, Context.Guild.Id, Program.Module.Communication);
     await ReplyAsync(Sentences.hiStr(Context.Guild.Id));
 }
Example #27
0
 public async Task help()
 {
     p.doAction(Context.User, Context.Guild.Id, Program.Module.Communication);
     await ReplyAsync("", false, Sentences.help(Context.Guild.Id, (Context.Channel as ITextChannel).IsNsfw));
 }
Example #28
0
        public async Task getNhentai(params string[] keywords)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Doujinshi);
            if (!(Context.Channel as ITextChannel).IsNsfw)
            {
                await ReplyAsync(Sentences.chanIsNotNsfw(Context.Guild.Id));

                return;
            }
            string tags = "";

            if (keywords.Length != 0)
            {
                foreach (string s in keywords)
                {
                    tags += s + "+";
                }
                tags = tags.Substring(0, tags.Length - 1);
            }
            string xml;

            using (WebClient w = new WebClient())
            {
                w.Encoding = Encoding.UTF8;
                if (keywords.Length == 0)
                {
                    xml = w.DownloadString("https://nhentai.net/api/galleries/all?page=0");
                }
                else
                {
                    xml = w.DownloadString("https://nhentai.net/api/galleries/search?query=" + tags + "&page=8000");
                }
            }
            int page = p.rand.Next(Convert.ToInt32(Program.getElementXml("\"num_pages\":", xml, ','))) + 1;

            using (WebClient w = new WebClient())
            {
                w.Encoding = Encoding.UTF8;
                if (keywords.Length == 0)
                {
                    xml = w.DownloadString("https://nhentai.net/api/galleries/all?page=" + page);
                }
                else
                {
                    xml = w.DownloadString("https://nhentai.net/api/galleries/search?query=" + tags + "&page=" + page);
                }
            }
            List <string> allDoujinshi = xml.Split(new string[] { "title" }, StringSplitOptions.None).ToList();

            allDoujinshi.RemoveAt(0);
            if (allDoujinshi.Count == 0)
            {
                string[] allTags = tags.Split(new string[] { "+" }, StringSplitOptions.RemoveEmptyEntries);
                await ReplyAsync(Sentences.tagsNotFound(allTags));
            }
            else
            {
                string   curr      = allDoujinshi[p.rand.Next(allDoujinshi.Count)];
                string[] ids       = curr.Split(new string[] { "}]" }, StringSplitOptions.None);
                string   currBlock = "";
                for (int i = ids.Length - 1; i >= 0; i--)
                {
                    currBlock = Program.getElementXml("id\":", ids[i], ',');
                    if (currBlock != "")
                    {
                        if (keywords.Length == 0)
                        {
                            await ReplyAsync("https://nhentai.net/g/" + currBlock);
                        }
                        else
                        {
                            string finalOk = "";
                            foreach (string t in keywords)
                            {
                                bool isOk = false;
                                foreach (string s in ids[i - 1].Split(new string[] { "},{" }, StringSplitOptions.None))
                                {
                                    if (Program.getElementXml("\"name\":\"", s, '"').Contains(t))
                                    {
                                        isOk = true;
                                        break;
                                    }
                                }
                                if (!isOk)
                                {
                                    finalOk = t;
                                    break;
                                }
                            }
                            if (finalOk == "")
                            {
                                await ReplyAsync("https://nhentai.net/g/" + currBlock);
                            }
                            else
                            {
                                await ReplyAsync(Sentences.tagsNotFound(new string[] { finalOk }));
                            }
                        }
                        break;
                    }
                }
            }
        }
Example #29
0
        public async Task drop(params string[] shipNameArr)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Kancolle);
            if (shipNameArr.Length == 0)
            {
                await ReplyAsync(Sentences.kancolleHelp(Context.Guild.Id));

                return;
            }
            string shipName = Program.cleanWord(Program.addArgs(shipNameArr));

            using (WebClient wc = new WebClient())
            {
                wc.Encoding = Encoding.UTF8;
                string        html         = wc.DownloadString("http://kancolle.wikia.com/wiki/Internals/Translations");
                List <string> allShipsName = html.Split(new string[] { "<tr" }, StringSplitOptions.None).ToList();
                allShipsName.RemoveAt(0);
                string shipContain = allShipsName.Find(x => Program.cleanWord(Program.getElementXml("\">", x, '<')) == shipName);
                if (shipContain == null)
                {
                    await ReplyAsync(Sentences.shipgirlDontExist(Context.Guild.Id));

                    return;
                }
                shipName = Program.getElementXml("<td>", shipContain, '<');
                html     = wc.DownloadString("https://wikiwiki.jp/kancolle/%E8%89%A6%E5%A8%98%E3%83%89%E3%83%AD%E3%83%83%E3%83%97%E9%80%86%E5%BC%95%E3%81%8D");
                html     = html.Split(new string[] { "<thead>" }, StringSplitOptions.None)[1];
                html     = html.Split(new string[] { "艦種別表" }, StringSplitOptions.None)[0];
                string[] shipgirls = html.Split(new string[] { "<tr>" }, StringSplitOptions.None);
                string   shipgirl  = shipgirls.ToList().Find(x => x.Contains(shipName));
                string   finalStr  = "";
                if (shipgirl == null)
                {
                    await ReplyAsync(Sentences.shipNotReferencedMap(Context.Guild.Id));
                }
                else
                {
                    string[] cathegories = shipgirl.Split(new string[] { "<td class=\"style_td\"" }, StringSplitOptions.RemoveEmptyEntries);
                    int[]    toKeep      = new int[] { 4, 5, 6, 7, 8, 9,     // World 1
                                                       11, 12, 13, 14, 15,   // world 2
                                                       17, 18, 19, 20, 21,   // World 3
                                                       23, 24, 25, 26, 27,   // World 4
                                                       29, 30, 31, 32, 33,   // World 5
                                                       35, 36, 37, 38, 39 }; // World 6
                    int level = 1;
                    int world = 1;
                    foreach (int i in toKeep)
                    {
                        string node = Program.getElementXml(">", cathegories[i], '<');
                        if (node.Length > 0)
                        {
                            switch (node[0])
                            {
                            case '●':
                                finalStr += world + "-" + level + ": Only on normal nodes" + Environment.NewLine;
                                break;

                            case '○':
                                finalStr += world + "-" + level + ": Only on boss node" + Environment.NewLine;
                                break;

                            case '◎':
                                finalStr += world + "-" + level + ": Anywhere on the map" + Environment.NewLine;
                                break;

                            default:
                                finalStr += world + "-" + level + ": Findable on the map" + Environment.NewLine;
                                break;
                            }
                        }
                        level++;
                        if ((world == 1 && level > 6) || (world > 1 && level > 5))
                        {
                            world++;
                            level = 1;
                        }
                    }
                    if (finalStr.Length > 0)
                    {
                        string rarity = Program.getElementXml(">", cathegories[1], '<');
                        await ReplyAsync("Rarity: " + ((rarity.Length > 0) ? (rarity) : ("?")) + "/7" + Environment.NewLine + finalStr);
                    }
                    else
                    {
                        await ReplyAsync(Sentences.dontDropOnMaps(Context.Guild.Id));
                    }
                }
                wc.Headers.Add("User-Agent: Sanara");
                html = wc.DownloadString("http://unlockacgweb.galstars.net/KanColleWiki/viewCreateShipLogList");
                html = Regex.Replace(
                    html,
                    @"\\[Uu]([0-9A-Fa-f]{4})",
                    m => char.ToString(
                        (char)ushort.Parse(m.Groups[1].Value, NumberStyles.AllowHexSpecifier)));     // Replace \\u1313 by \u1313
                string[] htmlSplit = html.Split(new string[] { shipName }, StringSplitOptions.None);
                if (htmlSplit.Length == 1)
                {
                    await ReplyAsync(Sentences.shipNotReferencedConstruction(Context.Guild.Id));

                    return;
                }
                string[] allIds = htmlSplit[htmlSplit.Length - 2].Split(new string[] { "\",\"" }, StringSplitOptions.None);
                wc.Headers.Add("User-Agent: Sanara");
                html = wc.DownloadString("http://unlockacgweb.galstars.net/KanColleWiki/viewCreateShipLog?sid=" + (allIds[allIds.Length - 1].Split('"')[0]));
                html = html.Split(new string[] { "order_by_probability" }, StringSplitOptions.None)[1];
                html = html.Split(new string[] { "flagship_order" }, StringSplitOptions.None)[0];
                string[] allElements = html.Split(new string[] { "{\"item1\":" }, StringSplitOptions.None);
                finalStr = "Ship Construction:" + Environment.NewLine;
                for (int i = 1; i < ((allElements.Length > 6) ? (6) : (allElements.Length)); i++)
                {
                    string[] ressources = allElements[i].Split(new string[] { ",\"" }, StringSplitOptions.None);
                    finalStr += Program.getElementXml(":", ressources[7], '}') + "% -- Fuel: " + ressources[0] + ", Ammos: " + Program.getElementXml(":", ressources[1], '?') + ", Iron: " + Program.getElementXml(":", ressources[2], '?') + ", Bauxite: " + Program.getElementXml(":", ressources[3], '?')
                                + ", Dev mat: " + Program.getElementXml(":", ressources[4], '?') + Environment.NewLine;
                }
                await ReplyAsync(finalStr);
            }
        }
Example #30
0
        public async Task charac(params string[] shipNameArr)
        {
            p.doAction(Context.User, Context.Guild.Id, Program.Module.Kancolle);
            if (shipNameArr.Length == 0)
            {
                await ReplyAsync(Sentences.kancolleHelp(Context.Guild.Id));

                return;
            }
            string     shipName = Program.addArgs(shipNameArr);
            IGuildUser me       = await Context.Guild.GetUserAsync(Sentences.myId);

            string url = "https://kancolle.wikia.com/api/v1/Search/List?query=" + shipName + "&limit=1";

            try
            {
                using (WebClient w = new WebClient())
                {
                    w.Encoding = Encoding.UTF8;
                    List <string> finalStr = new List <string>();
                    finalStr.Add("");
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                    string json = w.DownloadString(url);
                    string code = Program.getElementXml("\"id\":", json, ',');
                    url  = "http://kancolle.wikia.com/api/v1/Articles/Details?ids=" + code;
                    json = w.DownloadString(url);
                    string image = Program.getElementXml("\"thumbnail\":\"", json, '"');
                    if (Program.getElementXml("\"title\":\"", json, '"').ToUpper() != shipName.ToUpper())
                    {
                        await ReplyAsync(Sentences.shipgirlDontExist(Context.Guild.Id));

                        return;
                    }
                    url  = "http://kancolle.wikia.com/wiki/" + Program.getElementXml("\"title\":\"", json, '"') + "?action=raw";
                    json = w.DownloadString(url);
                    if (Program.getElementXml("{{", json, '}') != "ShipPageHeader" && Program.getElementXml("{{", json, '}') != "Ship/Header")
                    {
                        await ReplyAsync(Sentences.shipgirlDontExist(Context.Guild.Id));

                        return;
                    }
                    int currentTime = Convert.ToInt32(DateTime.Now.ToString("HHmmss"));
                    if (me.GuildPermissions.AttachFiles)
                    {
                        image = image.Split(new string[] { ".jpg" }, StringSplitOptions.None)[0] + ".jpg";
                        image = image.Replace("\\", "");
                        w.DownloadFile(image, "shipgirl" + currentTime + ".jpg");
                    }
                    url  = "http://kancolle.wikia.com/api/v1/Articles/AsSimpleJson?id=" + code;
                    json = w.DownloadString(url);
                    string[] jsonInside = json.Split(new string[] { "\"title\"" }, StringSplitOptions.None);
                    int      currI      = 0;
                    foreach (string s in jsonInside)
                    {
                        if (s.Contains("Personality"))
                        {
                            finalStr[0] += "**Personality**" + Environment.NewLine;
                            string[] allExplanations = s.Split(new string[] { "\"te" }, StringSplitOptions.None);
                            foreach (string str in allExplanations)
                            {
                                string per = Program.getElementXml("xt\":\"", str, '"');
                                if (per != "")
                                {
                                    finalStr[0] += per + Environment.NewLine;
                                }
                            }
                            break;
                        }
                    }
                    foreach (string s in jsonInside)
                    {
                        if (s.Contains("Appearance"))
                        {
                            finalStr[0] += Environment.NewLine + "**Appearance**" + Environment.NewLine;
                            string[] allExplanations = s.Split(new string[] { "\"te" }, StringSplitOptions.None);
                            foreach (string str in allExplanations)
                            {
                                string per = Program.getElementXml("xt\":\"", str, '"');
                                if (per != "")
                                {
                                    if (finalStr[currI].Length + per.Length > 1500)
                                    {
                                        currI++;
                                        finalStr.Add("");
                                    }
                                    finalStr[currI] += per + Environment.NewLine;
                                }
                            }
                            break;
                        }
                    }
                    foreach (string s in jsonInside)
                    {
                        if (s.Contains("Second Remodel"))
                        {
                            finalStr[0] += "**Second Remodel**" + Environment.NewLine;
                            string[] allExplanations = s.Split(new string[] { "\"te" }, StringSplitOptions.None);
                            foreach (string str in allExplanations)
                            {
                                string per = Program.getElementXml("xt\":\"", str, '"');
                                if (per != "")
                                {
                                    if (finalStr[currI].Length + per.Length > 1500)
                                    {
                                        currI++;
                                        finalStr.Add("");
                                    }
                                    finalStr[currI] += per + Environment.NewLine;
                                }
                            }
                            break;
                        }
                    }
                    foreach (string s in jsonInside)
                    {
                        if (s.Contains("Trivia"))
                        {
                            finalStr[currI] += Environment.NewLine + "**Trivia**" + Environment.NewLine;
                            string[] allExplanations = s.Split(new string[] { "\"te" }, StringSplitOptions.None);
                            foreach (string str in allExplanations)
                            {
                                string per = Program.getElementXml("xt\":\"", str, '"');
                                if (per != "")
                                {
                                    if (finalStr[currI].Length + per.Length > 1500)
                                    {
                                        currI++;
                                        finalStr.Add("");
                                    }
                                    finalStr[currI] += per + Environment.NewLine;
                                }
                            }
                            break;
                        }
                    }
                    if (me.GuildPermissions.AttachFiles)
                    {
                        await Context.Channel.SendFileAsync("shipgirl" + currentTime + ".jpg");
                    }
                    foreach (string s in finalStr)
                    {
                        await ReplyAsync(Regex.Replace(
                                             s,
                                             @"\\[Uu]([0-9A-Fa-f]{4})",
                                             m => char.ToString(
                                                 (char)ushort.Parse(m.Groups[1].Value, NumberStyles.AllowHexSpecifier)))); // Replace \\u1313 by \u1313
                    }
                    if (me.GuildPermissions.AttachFiles)
                    {
                        File.Delete("shipgirl" + currentTime + ".jpg");
                    }
                }
            }
            catch (WebException ex)
            {
                HttpWebResponse code = ex.Response as HttpWebResponse;
                if (code.StatusCode == HttpStatusCode.NotFound)
                {
                    await ReplyAsync(Sentences.shipgirlDontExist(Context.Guild.Id));
                }
            }
        }