public void Initialise()
        {
            Lastfm = new LastfmClient(LastFm.TEST_APIKEY, LastFm.TEST_APISECRET);

            var authTask = Lastfm.Auth.GetSessionTokenAsync(INTEGRATION_TEST_USER, INTEGRATION_TEST_PASSWORD);
            authTask.Wait();
            Assert.IsTrue(authTask.Result.Success);
        }
        public MediaMetadataService(LastFmConfig lastFmConfig, IConfigurationService configurationService, ILocalLyricsService localLyricsService)
        {
            _metadataConfiguration = configurationService.Metadata;
            _lastfm = new LastfmClient(lastFmConfig.ApiKey, null);
            _geciMe = new GeciMeClient();
            _moeAtHome = new MoeAtHomeClient();
            _localLyricsService = localLyricsService;

            var packageVersion = Windows.ApplicationModel.Package.Current.Id.Version;
            _lastfm.HttpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("TomatoMusic",
                $"{packageVersion.Major}.{packageVersion.Minor}"));
        }
Example #3
0
        public static void Main(string[] args)
        {
            Console.CancelKeyPress += (sender, e) =>
            {
                quitEvent.Set();
                e.Cancel = true;
            };

            Console.WriteLine("\t\t\tDiscordSharp Tester");
            client.ClientPrivateInformation = new DiscordUserInformation();
#if DEBUG
            client.WriteLatestReady = true;
#endif

            if (File.Exists("credentials.txt"))
            {
                using (StreamReader sr = new StreamReader("credentials.txt"))
                {
                    client.ClientPrivateInformation.email = sr.ReadLine();
                    client.ClientPrivateInformation.password = sr.ReadLine();
                }
            }
            else
            {
                Console.Write("Please enter your email: ");
                string email = Console.ReadLine();
                client.ClientPrivateInformation.email = email;

                Console.Write("Now, your password (visible): ");
                string pass = Console.ReadLine();
                client.ClientPrivateInformation.password = pass;
            }

            Console.WriteLine("Attempting login..");

            var worker = new Thread(() =>
            {
                client.VoiceClientConnected += (sender, e) =>
                {
                    owner.SlideIntoDMs("Voice client connection complete.");
                };
                client.TextClientDebugMessageReceived += (sender, e) =>
                {
                    if (e.message.Level == MessageLevel.Error || e.message.Level == MessageLevel.Error || e.message.Level == MessageLevel.Warning)
                    {
                        WriteDebug(e.message, "Text Client");
                        if (client.GetServersList() != null)
                        {
                            DiscordMember onwer = client.GetServersList().Find(x => x.members.Find(y => y.Username == "Axiom") != null).members.Find(x => x.Username == "Axiom");
                            if (onwer != null)
                                if (!e.message.Message.Contains("Setting current game"))
                                    onwer.SendMessage($"**LOGGING**\n```\n[Text Client: {e.message.Level}]: {e.message.Message}\n```");
                        }
                    }
                };
                client.VoiceClientDebugMessageReceived += (sender, e) =>
                {
                    WriteDebug(e.message, "Voice Debug");
                };
                client.RoleDeleted += (sender, e) =>
                {
                    Console.WriteLine($"Role '{e.DeletedRole.name}' deleted.");
                };
                client.UnknownMessageTypeReceived += (sender, e) =>
                {
                    using (var sw = new StreamWriter(e.RawJson["t"].ToString() + ".txt"))
                    {
                        sw.WriteLine(e.RawJson);
                    }
                    client.SendMessageToUser("Heya, a new message type, '" + e.RawJson["t"].ToString() + "', has popped up!", client.GetServersList().Find(x => x.members.Find(y => y.Username == "Axiom") != null).members.Find(x => x.Username == "Axiom"));
                };
                client.AudioPacketReceived += (sender, e) =>
                {
                    //client.EchoPacket(e.Packet);
                };
                client.VoiceStateUpdate += (sender, e) =>
                {
                    Console.WriteLine("***Voice State Update*** User: "******"Server Created: " + e.server.name);
                };
                client.MessageEdited += (sender, e) =>
                {
                    Console.WriteLine(e.message);
                    //if (e.author.user.username == "Axiom")
                    //    client.SendMessageToChannel("What the f**k, <@" + e.author.user.id + "> you can't event type your message right. (\"" + e.MessageEdited.content + "\")", e.Channel);
                };
                client.ChannelCreated += (sender, e) =>
                {
                    var parentServer = client.GetServersList().Find(x => x.channels.Find(y => y.ID == e.ChannelCreated.ID) != null);
                    if (parentServer != null)
                        Console.WriteLine("Channel {0} created in {1}!", e.ChannelCreated.Name, parentServer.name);
                };
                client.PrivateChannelDeleted += (sender, e) =>
                {
                    Console.WriteLine("Private channel deleted with " + e.PrivateChannelDeleted.recipient.Username);
                };
                client.PrivateChannelCreated += (sender, e) =>
                {
                    Console.WriteLine("Private channel started with {0}", e.ChannelCreated.recipient.Username);
                };
                client.PrivateMessageReceived += (sender, e) =>
                {
                    client.SendMessageToUser("Pong!", e.author);
                };
                client.MentionReceived += (sender, e) =>
                {
                    string rawMessage = e.message.content;
                    string whatToSend = $"I received a mention from @{e.author.Username} in #{e.Channel.Name} in {e.Channel.parent.name}. It said: \n```\n{rawMessage}\n```";
                    if (rawMessage.Contains($"{client.Me.ID}"))
                        whatToSend += $"Where `<@{client.Me.ID}>` is my user being mentioned.";
                    DiscordMember owner = client.GetServersList().Find(x => x.members.Find(y => y.Username == "Axiom") != null).members.Find(x => x.Username == "Axiom");
                    client.SendMessageToUser(whatToSend, owner);
                };
                client.MessageReceived += (sender, e) =>
                {
                    DiscordServer fromServer = client.GetServersList().Find(x => x.channels.Find(y => y.ID == e.Channel.ID) != null);

                    Console.WriteLine("[- Message from {0} in {1} on {2}: {3}", e.author.Username, e.Channel.Name, fromServer.name, e.message.content);
                    
                    if (e.message.content.StartsWith("?typemonkey"))
                    {
                        client.SimulateTyping(e.Channel);
                    }
                    else if(e.message.content.StartsWith("?unban"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if(split.Length > 1)
                        {
                            DiscordMember meInServer = e.Channel.parent.members.Find(x => x.ID == client.Me.ID);
                            bool hasPermission = false;
                            foreach(var role in meInServer.Roles)
                            {
                                if (role.permissions.HasPermission(DiscordSpecialPermissions.BanMembers) || role.permissions.HasPermission(DiscordSpecialPermissions.ManageServer))
                                {
                                    hasPermission = true;
                                    break;
                                }
                            }
                            if(hasPermission)
                                client.RemoveBan(e.Channel.parent, split[1]);
                            else
                                e.Channel.SendMessage("No permission to do so!");

                        }
                    }
                    else if(e.message.content.StartsWith("?getbans"))
                    {
                        var banList = client.GetBans(e.Channel.parent);
                        if (banList == null)
                        {
                            e.Channel.SendMessage("No permission!");
                            return;
                        }
                        if(banList.Count > 0)
                        {
                            string msg = $"**{banList.Count}** bans in this server.";
                            msg += "\n```";
                            for(int i = 0; i < banList.Count; i++)
                            {
                                if (i > 5)
                                    break;
                                msg += $"\n* {banList[i].Username} ({banList[i].ID})";
                            }
                            msg += "\n```";
                            e.Channel.SendMessage(msg);
                        }
                        else
                        {
                            e.Channel.SendMessage("No bans in this server!");
                        }
                    }
                    else if(e.message.content.StartsWith("?ban"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if(split.Length > 1)
                        {
                            //<@09380598340598>
                            string id = split[1].Trim(new char[] { '<', '@', '>' });
                            DiscordMember toBan = e.Channel.parent.members.Find(x => x.ID == id);
                            if (toBan != null)
                            {
                                if (client.BanMember(toBan) != null)
                                    e.Channel.SendMessage($"**{toBan.Username}** will be missed.");
                                else
                                    e.Channel.SendMessage("No permission!");
                            }
                            else
                                e.Channel.SendMessage("Ban who?");
                        }
                        else
                            e.Channel.SendMessage("Ban who?");
                    }
                    else if(e.message.content.StartsWith("?stop"))
                    {
                        if(client.ConnectedToVoice())
                        {
                            client.GetVoiceClient().ClearVoiceQueue();
                        }
                    }
                    else if (e.message.content.StartsWith("?editlast"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 1)
                        {
                            DiscordMessage toEdit = client.GetLastMessageSent(e.Channel);
                            if (toEdit != null)
                            {
                                client.EditMessage(toEdit.id, split[1], e.Channel);
                            }
                        }
                    }
                    else if (e.message.content.StartsWith("?testjoinvoice"))
                    {
                        if (e.author.Username != "Axiom")
                            return;
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 1)
                        {
                            DiscordChannel voiceToJoin = e.Channel.parent.channels.Find(x => x.Name.ToLower() == split[1].ToLower() && x.Type == ChannelType.Voice);
                            if (voiceToJoin != null)
                                client.ConnectToVoiceChannel(voiceToJoin);
                        }
                    }
                    else if (e.message.content.StartsWith("?disconnect"))
                    {
                        client.DisconnectFromVoice();
                    }
                    else if (e.message.content.StartsWith("?newguild"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 1)
                        {
                            DiscordServer created = client.CreateGuild(split[1]);
                            DiscordChannel channel = created.channels.Find(x => x.Type == ChannelType.Text);
                            client.ChangeChannelTopic("Created with DiscordSharp test bot", channel);

                            client.SendMessageToChannel($"Join: {client.MakeInviteURLFromCode(client.CreateInvite(channel))}", e.Channel);
                        }
                    }
                    else if (e.message.content.StartsWith("?notify"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                    }
                    else if(e.message.content.StartsWith("?channeltype"))
                    {
                        e.Channel.SendMessage(e.Channel.Type.ToString());
                    }
                    else if (e.message.content.StartsWith("?whereami"))
                    {
                        DiscordServer server = client.GetServersList().Find(x => x.channels.Find(y => y.ID == e.Channel.ID) != null);
                        string owner = "";
                        foreach (var member in server.members)
                            if (member.ID == server.owner.ID)
                                owner = member.Username;
                        string whereami = String.Format("I am currently in *#{0}* ({1}) on server *{2}* ({3}) owned by @{4}. The channel's topic is: {5}", e.Channel.Name, e.Channel.ID, server.name, server.id, owner, e.Channel.Topic);
                        client.SendMessageToChannel(whereami, e.Channel);
                    }
                    else if (e.message.content.StartsWith("?makeroll"))
                    {
                        DiscordMember me = e.Channel.parent.members.Find(x => x.ID == client.Me.ID);
                        DiscordServer inServer = e.Channel.parent;

                        foreach (var role in me.Roles)
                        {
                            if (role.permissions.HasPermission(DiscordSpecialPermissions.ManageRoles))
                            {
                                DiscordRole madeRole = client.CreateRole(inServer);
                                DiscordRole newRole = madeRole.Copy();
                                newRole.name = "DiscordSharp Test Roll";
                                newRole.color = new DiscordSharp.Color("0xFF0000");
                                newRole.permissions.SetPermission(DiscordSpecialPermissions.ManageRoles);

                                client.EditRole(inServer, newRole);
                                client.SendMessageToChannel("Created test roll successfully?", e.Channel);
                                return;
                            }
                        }
                        client.SendMessageToChannel("Can't create role: no permission.", e.Channel);
                    }
                    else if (e.message.content.StartsWith("?getroles"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        //?getroles <@10394803598>
                        if (split.Length > 1)
                        {
                            Regex r = new Regex(@"(?<=<)([^>]+)(?=>)");
                            string userToGetRoles = r.Match(split[1]).Value;
                            userToGetRoles = userToGetRoles.Trim('@'); //lol
                            DiscordMember foundMember = e.Channel.parent.members.Find(x => x.ID == userToGetRoles);
                            if (foundMember != null)
                            {
                                string whatToSend = "Found roles for user **" + foundMember.Username + "**:\n```";
                                for (int i = 0; i < foundMember.Roles.Count; i++)
                                {
                                    if (i > 0)
                                        whatToSend += "\n";
                                    whatToSend += $"* {foundMember.Roles[i].name}: id={foundMember.Roles[i].id} color=0x{foundMember.Roles[i].color.ToString()}, (R: {foundMember.Roles[i].color.R} G: {foundMember.Roles[i].color.G} B: {foundMember.Roles[i].color.B}) permissions={foundMember.Roles[i].permissions.GetRawPermissions()}";

                                    string tempPermissions = "";
                                    foreach (var permissions in foundMember.Roles[i].permissions.GetAllPermissions())
                                    {
                                        tempPermissions += " " + permissions.ToString();
                                    }
                                    whatToSend += "\n\n  Friendly Permissions: " + tempPermissions;
                                }
                                whatToSend += "\n```";
                                client.SendMessageToChannel(whatToSend, e.Channel);
                            }
                            else
                            {
                                client.SendMessageToChannel("User with id `" + userToGetRoles + "` not found.", e.Channel);
                            }
                        }
                    }
                    else if (e.message.content.StartsWith("?test_game"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 0)
                        {
                            client.UpdateCurrentGame(split[1]);
                        }
                    }
                    else if (e.message.content.StartsWith("?gtfo"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 1)
                        {
                            DiscordServer curServer = client.GetServersList().Find(x => x.channels.Find(y => y.ID == split[1]) != null);
                            if (curServer != null)
                            {
                                client.SendMessageToChannel("Leaving server " + curServer.name, e.Channel);
                                client.LeaveServer(curServer.id);
                            }
                        }
                        else
                        {
                            DiscordServer curServer = client.GetServersList().Find(x => x.channels.Find(y => y.ID == e.Channel.ID) != null);
                            if (curServer != null)
                            {
                                //client.SendMessageToChannel("Bye!", e.Channel);
                                client.LeaveServer(e.Channel.parent.id);
                            }
                        }
                    }
                    else if (e.message.content.StartsWith("?everyone"))
                    {
                        //DiscordServer server = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                        //string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        //if (split.Length > 1)
                        //{
                        //    string message = "";
                        //    foreach (var user in server.members)
                        //    {
                        //        if (user.ID == client.Me.ID)
                        //            continue;
                        //        if (user.user.username == "Blank")
                        //            continue;
                        //        message += "@" + user.user.username + " ";
                        //    }
                        //    message += ": " + split[1];
                        //    client.SendMessageToChannel(message, e.Channel);
                        //}
                    }
                    else if (e.message.content.StartsWith("?lastfm"))
                    {
#if __MONOCS__
                        client.SendMessageToChannel("Sorry, not on Mono :(", e.Channel);
#else
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 1)
                        {
                            using (var lllfclient = new LastfmClient(lastfmAuthentication))
                            {
                                try
                                {
                                    var recentScrobbles = lllfclient.User.GetRecentScrobbles(split[1], null, 1, 1);
                                    LastTrack lastTrack = recentScrobbles.Result.Content[0];
                                    client.SendMessageToChannel(string.Format("*{0}* last listened to _{1}_ by _{2}_", split[1], lastTrack.Name, lastTrack.ArtistName), e.Channel);
                                }
                                catch
                                {
                                    client.SendMessageToChannel(string.Format("User _*{0}*_ not found!", split[1]), e.Channel);
                                }
                            }
                        }
                        else
                            client.SendMessageToChannel("Who??", e.Channel);
#endif
                    }
                    else if (e.message.content.StartsWith("?assignrole"))
                    {
                        DiscordServer server = e.Channel.parent;
                        DiscordMember me = server.members.Find(x => x.ID == client.Me.ID);

                        bool hasPermission = false;
                        me.Roles.ForEach(r =>
                        {
                            if (r.permissions.HasPermission(DiscordSpecialPermissions.ManageRoles))
                                hasPermission = true;
                        });
                        if (hasPermission)
                        {
                            string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                            if (split.Length > 0)
                            {
                                DiscordRole toAssign = server.roles.Find(x => x.name.ToLower().Trim() == split[1].ToLower().Trim());
                                if (toAssign != null)
                                {
                                    client.AssignRoleToMember(server, toAssign, server.members.Find(x => x.Username == "Axiom"));
                                }
                                else
                                {
                                    client.SendMessageToChannel($"Role '{split[1]}' not found!", e.Channel);
                                }
                            }
                        }
                        else
                        {
                            client.SendMessageToChannel("Cannot assign role: no permission.", e.Channel);
                        }
                    }
                    else if (e.message.content.StartsWith("?rename"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 0)
                        {
                            //client.ChangeBotUsername(split[1]);
                            DiscordUserInformation newUserInfo = client.ClientPrivateInformation;
                            newUserInfo.username = split[1].ToString();
                            client.ChangeClientInformation(newUserInfo);
                        }
                    }
                    else if (e.message.content.StartsWith("?changepic"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 0)
                        {
                            Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                            string rawString = $"{split[1]}";
                            if (linkParser.Matches(rawString).Count > 0)
                            {
                                string url = linkParser.Matches(rawString)[0].ToString();
                                using (WebClient wc = new WebClient())
                                {
                                    byte[] data = wc.DownloadData(url);
                                    using (MemoryStream mem = new MemoryStream(data))
                                    {
                                        using (var image = System.Drawing.Image.FromStream(mem))
                                        {
                                            client.ChangeClientAvatar(new Bitmap(image));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (e.message.content.StartsWith("?changeguildpic"))
                    {
                        DiscordServer current = e.Channel.parent;
                        DiscordMember me = current.members.Find(x => x.ID == client.Me.ID);
                        foreach (var role in me.Roles)
                        {
                            if (role.permissions.HasPermission(DiscordSpecialPermissions.ManageServer))
                            {
                                string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                                if (split.Length > 0)
                                {
                                    Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                                    string rawString = $"{split[1]}";
                                    if (linkParser.Matches(rawString).Count > 0)
                                    {
                                        string url = linkParser.Matches(rawString)[0].ToString();
                                        using (WebClient wc = new WebClient())
                                        {
                                            byte[] data = wc.DownloadData(url);
                                            using (MemoryStream mem = new MemoryStream(data))
                                            {
                                                using (var image = System.Drawing.Image.FromStream(mem))
                                                {
                                                    client.ChangeGuildIcon(new Bitmap(image), current);
                                                }
                                            }
                                        }
                                    }
                                }
                                return;
                            }
                        }
                        client.SendMessageToChannel("Unable to change pic: No permission.", e.Channel);
                    }
                    else if(e.message.content.StartsWith("?servericon"))
                    {
                        if(e.Channel.parent.IconURL != null)
                        {
                            e.Channel.SendMessage(e.Channel.parent.IconURL);
                        }
                    }
                    else if(e.message.content.StartsWith("?whois"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if(split.Length > 1)
                        {
                            string justID = split[1].Trim(new char []{ '<', '>', '@' });
                            DiscordMember memberToCheck = e.Channel.parent.members.Find(x => x.ID == justID.Trim());
                            if(memberToCheck != null)
                            {
                                string msg = $"User info for {memberToCheck.Username}\n```\nID: {memberToCheck.ID}\nStatus: {memberToCheck.Status}\n";
                                if (memberToCheck.CurrentGame != null)
                                    msg += $"\nCurrent Game: {memberToCheck.CurrentGame}";
                                msg += "\n```";
                                e.Channel.SendMessage(msg);
                            }
                            else
                            {
                                e.Channel.SendMessage("Couldn't find user with ID `" + justID + "`!");
                            }
                        }
                    }
                    else if (e.message.content.StartsWith("?deletelast"))
                    {
                        //client.DeleteMessage(client.GetLastMessageSent(e.Channel).id);

                    }
                    else if (e.message.content.StartsWith("?testdmdelete"))
                    {
                        var msg = client.SendMessageToUser("lmao you suck", client.GetServersList()[0].members.Find(x => x.Username == "Axiom"));
                        client.DeleteMessage(msg);
                    }
                    else if (e.message.content.StartsWith("?prune"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 0)
                        {
                            client.DeleteMultipleMessagesInChannel(e.Channel, int.Parse(split[1]));
                        }
                        else
                        {
                            client.SendMessageToChannel("Prune what?", e.Channel);
                        }
                    }
                    else if (e.message.content.StartsWith("?quoththeraven"))
                        client.SendMessageToChannel("nevermore", e.Channel);
                    else if (e.message.content.StartsWith("?quote"))
                        client.SendMessageToChannel("Luigibot does what Reta don't.", e.Channel);
                    else if (e.message.content.StartsWith("?selfdestruct"))
                    {
                        if (e.author.Username == "Axiom")
                            client.SendMessageToChannel("restaroni in pepparoni", e.Channel);
                        Environment.Exit(0);
                    }
                    else if (e.message.content.Contains("?checkchannelperm"))
                    {
                        DiscordChannel channel = e.Channel;
                        string toSend = $"Channel Permission Overrides for #{channel.Name}\n\n```";
                        foreach (var over in channel.PermissionOverrides)
                        {
                            toSend += $"* Type: {over.type}\n";
                            if (over.type == DiscordPermissionOverride.OverrideType.member)
                                toSend += $"  Member: {over.id} ({channel.parent.members.Find(x => x.ID == over.id).Username})\n";
                            else
                                toSend += $"  Role: {over.id} ({channel.parent.roles.Find(x => x.id == over.id).name})\n";
                            toSend += $" Allowed: {over.GetAllowedRawPermissions()}\n";
                            toSend += $" Friendly:";
                            foreach (var allowed in over.GetAllAllowedPermissions())
                            {
                                toSend += " " + allowed.ToString();
                            }
                            toSend += $"\n Denied: {over.GetDeniedRawPermissions()}\n";
                            toSend += $" Friendly:";
                            foreach (var denied in over.GetAllDeniedPermissions())
                            {
                                toSend += " " + denied.ToString();
                            }
                            toSend += "\n\n";
                        }
                        toSend += "```";
                        client.SendMessageToChannel(toSend, channel);
                    }
                    else if (e.message.content.StartsWith("?createchannel"))
                    {
                        if (e.author.Username == "Axiom")
                        {
                            string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                            if (split.Length > 0)
                            {
                                client.CreateChannel(client.GetServerChannelIsIn(e.Channel), split[1], false);
                            }
                        }
                    }
                    else if (e.message.content.StartsWith("?deletechannel"))
                    {
                        if (e.author.Username == "Axiom")
                        {
                            client.DeleteChannel(e.Channel);
                        }
                    }
                    else if (e.message.content.StartsWith("?changetopic"))
                    {
                        if (e.author.Username == "Axiom")
                        {
                            string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                            if (split.Length > 0)
                                client.ChangeChannelTopic(split[1], e.Channel);
                        }
                    }
                    else if (e.message.content.StartsWith("?join"))
                    {
                        if (e.author.Username == "Axiom")
                        {
                            string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                            if (split.Length > 0)
                            {
                                string substring = split[1].Substring(split[1].LastIndexOf('/') + 1);
                                //client.SendMessageToChannel(substring, e.Channel);
                                client.AcceptInvite(substring);
                            }
                        }
                    }
                    else if(e.message.content.StartsWith("?testvoice"))
                    {
                        if (!client.ConnectedToVoice())
                            return;
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if(split.Length > 1)
                        {
                            if(File.Exists(split[1]))
                            {
                                VoiceStuffs(client.GetVoiceClient(), split[1]);
                            }
                        }
                    }
                    else if (e.message.content.StartsWith("?statusof"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if(split.Length > 1)
                        {
                            string id = split[1].Trim(new char[] { '<', '@', '>' });
                            DiscordMember member = e.Channel.parent.members.Find(x => x.ID == id);
                            if(member != null)
                            {
                                string msg = $"Status of **{member.Username}**";
                                msg += $"\n```\nStatus: " + member.Status.ToString();
                                if (member.CurrentGame != null)
                                    msg += "\nPlaying: " + member.CurrentGame;
                                msg += "\n```";
                                e.Channel.SendMessage(msg);
                            }
                        }
                    }
                    else if (e.message.content.StartsWith("?playing"))
                    {
                        DiscordMember member = e.Channel.parent.members.Find(x => x.Username == "Axiom");
                        using (var lllfclient = new LastfmClient(lastfmAuthentication))
                        {
                            try
                            {
                                client.SimulateTyping(e.Channel);
                                var recentScrobbles = lllfclient.User.GetRecentScrobbles("mrmiketheripper", null, 1, 1);
                                LastTrack lastTrack = recentScrobbles.Result.Content[0];
                                if (lastTrack.TimePlayed != null) //means the track is still playing
                                {
                                    var localTime = lastTrack.TimePlayed.Value.DateTime.ToLocalTime();
                                    if (DateTime.Now.Subtract(localTime) > (lastTrack.Duration == null ? new TimeSpan(0, 10, 0) : lastTrack.Duration))
                                        e.Channel.SendMessage($"<@{member.ID}> last played: **{lastTrack.Name}** by *{lastTrack.ArtistName}*. It was scrobbled at: {localTime} EST (-5).");
                                    else
                                        e.Channel.SendMessage($"<@{member.ID}> is now playing: **{lastTrack.Name}** by *{lastTrack.ArtistName}*.");
                                }
                                else
                                    e.Channel.SendMessage($"<@{member.ID}> is now playing: **{lastTrack.Name}** by *{lastTrack.ArtistName}*.");

                                if (e.message.content.Contains("art"))
                                {
                                    client.SimulateTyping(e.Channel);
                                    using (WebClient wc = new WebClient())
                                    {
                                        Image downloaded = Image.FromStream(new MemoryStream(wc.DownloadData(lastTrack.Images.Medium.AbsoluteUri)));
                                        if (downloaded != null)
                                        {
                                            downloaded.Save("temp.png");
                                            client.AttachFile(e.Channel, "", "temp.png");
                                            File.Delete("temp.png");
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                string whatToSend = $"Couldn't get Last.fm recent scrobbles for you! Exception:\n```{ex.Message}\n{ex.StackTrace}\n```\n";
                                client.SendMessageToUser(whatToSend, client.GetServersList().Find(x => x.members.Find(y => y.Username == "Axiom") != null).members.Find(x => x.Username == "Axiom"));
                            }
                        }
                    }
                };

                client.Connected += (sender, e) =>
                {
                    Console.WriteLine("Connected! User: "******"credentials.txt"))
                    {
                        sw.WriteLine(client.ClientPrivateInformation.email);
                        sw.WriteLine(client.ClientPrivateInformation.password);
                        sw.Flush();
                    }
                    using (var lllfclient = new LastfmClient(lastfmAuthentication))
                    {
                        try
                        {
                            var recentScrobbles = lllfclient.User.GetRecentScrobbles("mrmiketheripper", null, 1, 1);
                            LastTrack lastTrack = recentScrobbles.Result.Content[0];
                            string newGame = $"{lastTrack.Name} by {lastTrack.ArtistName}";
                            if (newGame != client.GetCurrentGame)
                                client.UpdateCurrentGame(newGame);
                        }
                        catch (Exception ex)
                        {
                            string whatToSend = $"Couldn't get Last.fm recent scrobbles for you! Exception:\n```{ex.Message}\n{ex.StackTrace}\n```\n";
                            client.SendMessageToUser(whatToSend, client.GetServersList().Find(x => x.members.Find(y => y.Username == "Axiom") != null).members.Find(x => x.Username == "Axiom"));
                        }
                    }

                    owner = client.GetServersList().Find(x => x.members.Find(y => y.Username == "Axiom") != null).members.Find(x => x.Username == "Axiom");
                };
                client.SocketClosed += (sender, e) =>
                {
                    Console.WriteLine("Closed ({0}): {1}", e.Code, e.Reason);
                };
                //ConnectStuff();
                //while (true) ;
                if (client.SendLoginRequest() != null)
                {
                    Console.WriteLine("Logged in!");

                    client.Connect();
                    Console.WriteLine($"Connected to {client.CurrentGatewayURL}");
                    client.UpdateCurrentGame("development testing");


                }
            });
            worker.Start();

            System.Timers.Timer lastfmUpdateTimer = new System.Timers.Timer(25 * 1000); //check last.fm every 25 seconds
            lastfmUpdateTimer.Elapsed += (sender, e) =>
            {
                using (var lllfclient = new LastfmClient(lastfmAuthentication))
                {
                    try
                    {
                        var recentScrobbles = lllfclient.User.GetRecentScrobbles("mrmiketheripper", null, 1, 1);
                        LastTrack lastTrack = recentScrobbles.Result.Content[0];
                        if (lastTrack.TimePlayed != null)
                        {
                            var localTime = lastTrack.TimePlayed.Value.DateTime.ToLocalTime();
                            if (DateTime.Now.Subtract(localTime) > new TimeSpan(0, 15, 0))
                            {
                                if (client.GetCurrentGame != "")
                                    if (client.GetCurrentGame == null)
                                        client.UpdateCurrentGame("");
                            }
                        }
                        else
                        {
                            string newGame = $"{lastTrack.Name} by {lastTrack.ArtistName}";
                            if (newGame != client.GetCurrentGame)
                                client.UpdateCurrentGame(newGame);
                        }

                    }
                    catch (Exception ex)
                    {
                        string whatToSend = $"Couldn't get Last.fm recent scrobbles for you! Exception:\n```{ex.Message}\n{ex.StackTrace}\n```\n";
                        client.SendMessageToUser(whatToSend, client.GetServersList().Find(x => x.members.Find(y => y.Username == "Axiom") != null).members.Find(x => x.Username == "Axiom"));
                    }
                }
            };
            lastfmUpdateTimer.Start();

            InputCheck();
            //System.Windows.Forms.Application.Run();
            /**
            Since this is a test app and people actually do read my code...
            I'd like to say one thing:
            If you're not going to be doing any input accepting **INSIDE OF THE CONSOLE** you don't have to setup 
            a seperate thread for the client and accept input on main. This is why I've only commented out
            the System.Windows.Forms.Application.Run(); part instead of removing it.

            If you're not accepting input, you can just run client on the main thread and run that 
            System.Windows.Forms.Application.Run(); snippet and this will keep the app alive, with no CPU 
            hit!
            */

            if (client.GetTextClientLogger.LogCount > 0)
            {
                client.GetTextClientLogger.Save($"log-{DateTime.Now.Month}-{DateTime.Now.Day}-{DateTime.Now.Year} {DateTime.Now.Hour} {DateTime.Now.Minute}.log");
                Console.WriteLine("Wrote log.");
            }
            if (client.GetLastVoiceClientLogger != null && client.GetLastVoiceClientLogger.LogCount > 0)
            {
                client.GetLastVoiceClientLogger.Save($"voicelog-{DateTime.Now.Month}-{DateTime.Now.Day}-{DateTime.Now.Year} {DateTime.Now.Hour} {DateTime.Now.Minute}.log");
                Console.WriteLine("Wrote voice log");
            }

            quitEvent.WaitOne();
            client.Dispose();
        }
Example #4
0
        /// <summary>
        /// Interprets commands
        /// </summary>
        /// <param name="command">The full message</param>
        /// <param name="sender">The full sender</param>
        /// <param name="recipient">The full recipient</param>
        private static void InterpretCommand(string command, IrcUser sender, IrcClient client)
        {
            command = command.TrimStart(ProgramSettings.settings.CommandPrefix); //simply removes the prefix

            if (command.StartsWith ("slap"))
            {
                if (ProgramSettings.settings.SlapEnabled)
                {
                    string[] splitCommand = command.Split (new char[] { ' ' }, 2);
                    if (splitCommand.Length > 1)
                    {
                        var listCopy = UsersList;
                        bool foundUser = false;
                        try
                        {
                            foreach (IrcUserAndSeen user in listCopy)
                            {
                                if (user.User.Nick.ToLower () == splitCommand [1].ToLower ().Trim ())
                                {
                                    if (user.User.Nick == client.User.Nick)
                                        client.SendRawMessage ("PRIVMSG {0} :What'd I do? :(", client.Channels [0].Name);
                                    else
                                        client.SendRawMessage ("PRIVMSG {0} :" + "\x01" + "ACTION slaps {1} with a giant fish.\x01", client.Channels [0].Name, user.User.Nick);
                                    foundUser = true;
                                    break;
                                }
                            }
                            if (!foundUser)
                                client.SendRawMessage ("PRIVMSG {0} :User not found!");
                        }
                        catch{}
                    } else
                        client.SendRawMessage ("PRIVMSG {0} :Slap who?", client.Channels [0].Name);
                }
            }
            if (command.StartsWith("removeuser"))
            {
                string[] split = command.Split(new char[]{' '}, 2);
                Console.ForegroundColor = ConsoleColor.Yellow;
                if (split.Length > 1)
                {
                    bool removed = false;
                    for(int i = 0; i < ProgramSettings.settings.UsersAllowedToDisable.Count; i++)
                    {
                        if (ProgramSettings.settings.UsersAllowedToDisable[i] == split[1].ToLower())
                        {
                            ProgramSettings.settings.UsersAllowedToDisable.RemoveAt(i);
                            removed = true;
                        }
                    }
                    if (removed)
                    {
                        Console.WriteLine("Removed user \"{0}\" successfully!", split[1].ToLower());
                        client.SendRawMessage("PRIVMSG {0} :Removed user \"{1}\" successfully!", client.Channels[0].Name, split[1].ToLower());
                    }
                    else
                    {
                        Console.WriteLine("User doesn't exist!");
                        client.SendRawMessage("PRIVMSG {0} :That user never existed in the database!", client.Channels[0].Name);
                    }
                }
                else
                {
                    Console.WriteLine("Remove who?");
                }
                Console.ForegroundColor = ConsoleColor.White;
            }
            if (command.StartsWith("adduser"))
            {
                string[] split = command.Split(new char[]{' '}, 2);
                Console.ForegroundColor = ConsoleColor.Yellow;
                if (split.Length > 1)
                {
                    ProgramSettings.settings.UsersAllowedToDisable.Add(split[1].ToLower());
                    Console.WriteLine("Added user \"{0}\" to the VIP list", split[1].ToLower());
                    client.SendRawMessage("PRIVMSG {0} :Added user \"{1}\" to the VIP list.?", client.Channels[0].Name, split[1].ToLower());
                }
                else
                {
                    Console.WriteLine("Who?");
                    client.SendRawMessage("PRIVMSG {0} :Add who?", client.Channels[0].Name);
                }
                Console.ForegroundColor = ConsoleColor.White;
            }
            if (command.StartsWith("disableseen"))
            {
                foreach (string user in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (user.ToLower() == sender.Nick.ToLower())
                    {
                        ProgramSettings.settings.SeenEnabled = false;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Seen Command Disabled");
                        Console.ForegroundColor = ConsoleColor.White;
                        client.SendRawMessage ("PRIVMSG {0} :Disabled seen command!", client.Channels[0].Name);
                    }
                }
            }
            if (command.StartsWith("enableseen"))
            {
                foreach (string user in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (user.ToLower() == sender.Nick.ToLower())
                    {
                        ProgramSettings.settings.SeenEnabled = true;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Seen Command Enabled");
                        Console.ForegroundColor = ConsoleColor.White;
                        client.SendRawMessage ("PRIVMSG {0} :Enabled seen command!", client.Channels[0].Name);
                    }
                }
            }
            if (command.StartsWith ("enableurlparse"))
            {
                foreach (string user in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (user.ToLower () == sender.Nick.ToLower ())
                    {
                        ProgramSettings.settings.UrlParsingEnabled = true;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("URL Parsing Enabled");
                        Console.ForegroundColor = ConsoleColor.White;
                        client.SendRawMessage ("PRIVMSG {0} :Enabling URL parsing!", client.Channels[0].Name);
                    }
                }
            }
            if (command.StartsWith ("disableurlparse"))
            {
                foreach (string user in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (user.ToLower () == sender.Nick.ToLower ())
                    {
                        ProgramSettings.settings.UrlParsingEnabled = false;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("URL Parsing Disabled");
                        Console.ForegroundColor = ConsoleColor.White;
                        client.SendRawMessage ("PRIVMSG {0} :Disabling URL parsing!", client.Channels[0].Name);
                    }
                }
            }
            if (command.StartsWith ("nick") || command.StartsWith ("name"))
            {
                string[] splitCommand = command.Split (new char[]{ ' ' }, 2);
                if (splitCommand.Length > 1)
                {
                    foreach (string user in ProgramSettings.settings.UsersAllowedToDisable)
                    {
                        if (user.ToLower () == sender.Nick.ToLower ())
                        {
                            string cleanNick = CleanInput (splitCommand [1]);
                            client.Nick (cleanNick);
                            ProgramSettings.settings.LastUsedNick = client.User.Nick;
                        }
                    }
                }
            }
            if(command.StartsWith("motto") || command.StartsWith("slogan"))
            {
                client.SendRawMessage("PRIVMSG {0} :Luigibot does what Reta don't \u00a9", client.Channels[0].Name);
            }
            if(command.StartsWith("version"))
            {
                #if __MONOCS__
                client.SendRawMessage("PRIVMSG {0} :Luigibot v{1} - http://www.github.com/Luigifan/Luigibot - Running under Mono", client.Channels[0].Name, ProgramVersion.ToString());
                #else
                client.SendRawMessage("PRIVMSG {0} :Luigibot v{1} - http://www.github.com/Luigifan/Luigibot", client.Channels[0].Name, ProgramVersion.ToString());
                #endif
            }
            if(command.StartsWith("changeprefix"))
            {
                string[] splitCommand = command.Split(new char[] { ' ' }, 2);
                if (splitCommand.Length > 1)
                {
                    foreach (string user in ProgramSettings.settings.UsersAllowedToDisable)
                    {
                        if(user.ToLower() == sender.Nick.ToLower())
                        {
                            if (splitCommand[1].Length == 1)
                            {
                                if (splitCommand[1] == "/")
                                {
                                    client.SendRawMessage("PRIVMSG {0} :oi u cheeky c**t ill bash ur ead in i swear on me mum", client.Channels[0].Name);
                                    return;
                                }
                                try
                                {
                                    char newPrefix = char.Parse(splitCommand[1]);
                                    ProgramSettings.settings.CommandPrefix = newPrefix;

                                    Console.ForegroundColor = ConsoleColor.Yellow;
                                    Console.WriteLine("Command prefix changed to '{0}' successfully!", newPrefix.ToString());
                                    Console.ForegroundColor = ConsoleColor.White;

                                    client.SendRawMessage("PRIVMSG {0} :Command prefix changed to '{1}' successfully!", client.Channels[0].Name, newPrefix.ToString());
                                    return;
                                }
                                catch (Exception ex)
                                {
                                    client.SendRawMessage("PRIVMSG {0} :Uh-oh! Luigibot encountered an error. Email Luigifan @ [email protected]",
                                        client.Channels[0].Name);

                                    Console.ForegroundColor = ConsoleColor.Red;
                                    Console.WriteLine("UH OH BIG ERROR\nUH OH BIG ERROR");
                                    Console.ForegroundColor = ConsoleColor.White;
                                    Console.WriteLine(ex.Message + "\n");
                                }
                            }
                            else
                            {
                                client.SendRawMessage("PRIVMSG {0} :The prefix must be a single character!", client.Channels[0].Name);
                            }
                        }
                    }
                }
                else
                    client.SendRawMessage("PRIVMSG {0} :What character will prefix my commands?", client.Channels[0].Name);
            }
            if(command.StartsWith("kick"))
            {
                //0: command
                //1: user
                //2: reason
                string[] splitCommand = command.Split(new char[] { ' ' }, 3);
                foreach (string user in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if(user.ToLower() == sender.Nick.ToLower())
                    {
                        try
                        {
                            if (splitCommand.Length > 2)
                            {
                                client.KickUser(client.Channels[0].Name, splitCommand[1], splitCommand[2]);
                            }
                            else
                                client.KickUser(client.Channels[0].Name, splitCommand[1]);
                        }
                        catch (Exception ex)
                        {
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("ERROR: {0}", ex.Message);
                            Console.ForegroundColor = ConsoleColor.White;
                        }
                    }
                }
            }
            if(command.StartsWith("getmodes"))
            {
                client.SendMessage("Modes: " + client.User.Mode, client.Channels[0].Name);
            }
            if (command.StartsWith ("ann"))
            {
                string[] splitCommand = command.Split (new char[]{ ' ' }, 2);
                if (splitCommand.Length > 1)
                {
                    foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                    {
                        if (sender.Nick.ToLower () == nick)
                        {
                            if (splitCommand [1] == "test")
                            {
                                if (ProgramSettings.settings.WelcomeMessage.Contains ("/me"))
                                {
                                    client.SendAction (String.Format (ProgramSettings.settings.WelcomeMessage.Substring (4), sender.Nick), client.Channels [0].Name);
                                } else
                                {
                                    client.SendRawMessage ("PRIVMSG {0} :{1}",
                                        client.Channels [0].Name,
                                        String.Format (ProgramSettings.settings.WelcomeMessage, sender.Nick));
                                }
                            }
                            else
                            {
                                if(splitCommand[1].Contains("{") && splitCommand[1].Contains("}"))
                                {
                                    string[] tester = splitCommand[1].Split(new char[] { '{', '}' }, 3);
                                    foreach(string x in tester)
                                    {
                                        int xf = -1;
                                        bool parsed = false;
                                        try
                                        {
                                            xf = int.Parse(x.ToString());
                                            parsed = true;
                                        }
                                        catch{parsed = false;}

                                        if (parsed)
                                        {
                                            if (xf > 0 || xf < 0)
                                            {
                                                client.SendRawMessage("PRIVMSG {0} :ERROR: Index numbers can't be bigger than 0 or less than 0. MUST BE 0!", client.Channels[0].Name);
                                                return;
                                            }
                                        }
                                    }
                                }
                                ProgramSettings.settings.WelcomeMessage = splitCommand [1];
                                client.SendRawMessage ("PRIVMSG {0} :Welcome message set!", client.Channels [0].Name);
                                Console.ForegroundColor = ConsoleColor.Yellow;
                                Console.WriteLine ("New welcome message set: " + splitCommand [1]);
                                Console.ForegroundColor = ConsoleColor.White;
                            }
                        }
                    }
                }
                else
                {
                    client.SendRawMessage ("PRIVMSG {0} :What message do I set?", client.Channels[0].Name);
                }
            }
            if (command.StartsWith ("enableslap"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.SlapEnabled = true;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Enabling slap");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("enablewelcome"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.WelcomeUserEnabled = true;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Enabling welcome messages");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("disablewelcome"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.WelcomeUserEnabled = false;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Disabling welcome messages");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("disableslap"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.SlapEnabled = false;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Disabling slap");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("eightball") || command.StartsWith ("8ball") || command.StartsWith ("fortune"))
            {
                if (ProgramSettings.settings.EightballEnabled)
                {
                    int ranMessage = random.Next (EightballMessages.Length - 1);
                    if (command.ToLower ().Contains ("waluigibot1337") || command.ToLower ().Contains ("waluigibot") || command.ToLower ().Contains ("waluigi bot"))
                        client.SendRawMessage ("PRIVMSG {0} :Waluigibot is a tool and will never come to fruition.", client.Channels [0].Name);
                    else if (command.ToLower ().Contains ("bot") && !command.ToLower ().Contains ("luigi"))
                        client.SendRawMessage ("PRIVMSG {0} :Your bot is inadequate for the job.", client.Channels [0].Name);
                    else
                        client.SendRawMessage ("PRIVMSG {0} :{1}", client.Channels [0].Name, EightballMessages [ranMessage]);
                }
            }
            if (command.StartsWith ("status"))
            {
                client.SendRawMessage ("PRIVMSG {0} :Slap Enabled: {1}. Eight Ball Enabled: {2}. Welcome Enabled: {3}. Command Prefix: {4}. URL Parsing: {5}",
                    client.Channels [0].Name,
                    ProgramSettings.settings.SlapEnabled,
                    ProgramSettings.settings.EightballEnabled,
                    ProgramSettings.settings.WelcomeUserEnabled,
                    ProgramSettings.settings.CommandPrefix.ToString(),
                    ProgramSettings.settings.UrlParsingEnabled);
            }
            if (command.StartsWith ("lastfm"))
            {
                #if __MONOCS__
                client.SendRawMessage("PRIVMSG {0} :The Last.FM API we use isn't available on Mono.", client.Channels[0].Name);
                #elif __MSCS__
                string[] split = command.Split (new char[] { ' ' }, 2);
                if (split.Length > 1)
                {
                    client.SendRawMessage("PRIVMSG {0} :Sending LastFM request, this may take a few seconds..", client.Channels[0].Name);
                    try
                    {
                        var lastfmClient = new LastfmClient ("4de0532fe30150ee7a553e160fbbe0e0", "0686c5e41f20d2dc80b64958f2df0f0c");
                        var response = lastfmClient.User.GetRecentScrobbles (split [1].ToString ().Trim (), null, 0, 1);
                        LastTrack lastTrack = response.Result.Content [0];
                        client.SendRawMessage ("PRIVMSG {0} :{1} last listened to {2} by {3}.", client.Channels [0].Name, split [1].Trim (), lastTrack.Name, lastTrack.ArtistName);
                    }
                    catch (ArgumentOutOfRangeException iex)
                    {
                        client.SendRawMessage ("PRIVMSG {0} :That user doesn't exist or hasn't scrobbled anything yet!",
                            client.Channels [0].Name);
                    }
                    catch (Exception ex)
                    {
                        client.SendRawMessage ("PRIVMSG {0} :Uh-oh! Luigibot encountered an error. Email Luigifan @ [email protected]",
                            client.Channels [0].Name);

                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine ("UH OH BIG ERROR\nUH OH BIG ERROR");
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine (ex.Message + "\n");
                    }
                }
                #endif
            }
            if (command.StartsWith ("enable8ball") || command.StartsWith ("enableeightball"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.EightballEnabled = true;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Enabling eight ball");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("disable8ball") || command.StartsWith ("disableeightball"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.EightballEnabled = false;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Disabling eight ball");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("selfdestruct"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ExitSafely ();
                        break;
                    }
                }
            }
            if (command.StartsWith ("42"))
            {
                client.SendRawMessage ("PRIVMSG {0} :The Answer to Life, the Universe, and Everything.", client.Channels [0].Name);
            }
            if (command.StartsWith ("commands"))
            {
                client.SendRawMessage ("PRIVMSG {0} :You can find a list of my commands here: https://github.com/Luigifan/Luigibot/wiki/Luigibot-Commands", client.Channels [0].Name);
            }
            if (command.StartsWith ("seen"))
            {
                string[] splitCommand = command.Split (new char[] { ' ' }, 2);
                if (splitCommand.Length > 1)
                {
                    if (splitCommand [1].ToLower () == "knux" || splitCommand [1].ToLower () == "knuckles" || splitCommand [1].ToLower () == "knuckles96")
                    {
                        client.SendRawMessage ("PRIVMSG {0} :Never.", client.Channels [0].Name);
                        return;
                    }
                    var UsersListCopy = UsersList;
                    var UserDatabaseCopy = UsersSeenDatabase.UsersSeenDatabase;
                    //First, check to see if the user is on now
                    bool foundInOnline = false;
                    foreach (IrcUserAndSeen user in UsersListCopy)
                    {
                        if (user.User.Nick.ToLower () == splitCommand [1].ToLower ().Trim ())
                        {
                            foundInOnline = true;
                            if (user.User.Nick == client.User.Nick)
                                client.SendRawMessage ("PRIVMSG {0} :I'm always online c:", client.Channels [0].Name);
                            else
                                client.SendRawMessage ("PRIVMSG {0} :That user is online now!", client.Channels [0].Name);
                            foundInOnline = true;
                            break;
                        }
                    }
                    //Then, we'll check the database
                    bool foundInDatabase = false;
                    List<IrcUserAndSeen> removeLater = new List<IrcUserAndSeen>();
                    if (!foundInOnline)
                    {
                        foreach (IrcUserAndSeen user in UserDatabaseCopy)
                        {
                            if (user.User.Nick == null)
                            {
                                Console.WriteLine("Adding null entry to be removed later");
                                removeLater.Add(user);
                            }
                            else
                            {
                                if (user.User.Nick.ToLower() == splitCommand[1].ToLower().Trim())
                                {
                                    foundInDatabase = true;
                                    client.SendRawMessage("PRIVMSG {0} :{1} was last seen at {2} (EST)", client.Channels[0].Name, user.User.Nick, user.LastSeen.ToString());
                                    break;
                                }
                            }
                        }
                        if (!foundInDatabase && !foundInOnline)
                            client.SendRawMessage ("PRIVMSG {0} :I'm not sure :(", client.Channels [0].Name);
                    }
                } else
                    client.SendRawMessage ("PRIVMSG {0} :Last seen who?", client.Channels [0].Name);
            }
        }
Example #5
0
        // Commands first to help with adding new commands
        static void GenerateCommands(CommandGroupBuilder group)
        {
            // User commands
            group.CreateCommand("servers")
            .Description("I'll send you statistics about the servers, channels and users (can be spammy, goes to private).")
            .MinPermissions(4)
            .Do(async e =>
            {
                var output = "";
                foreach (var server in client.Guilds)
                {
                    output += $"{server.Name}: {server.TextChannels.Count()} text & {server.VoiceChannels.Count()} voice channels, {server.Users.Count()} users. ID: {server.Id}";
                    if (output.Length >= 2000)
                    {
                        var index = output.Length == 2000 ? 0 : output.LastIndexOf('\n');
                        await e.User.SendMessageAsync(Format.Code(index == 0 ? output : output.Substring(0, index)));
                        output = index == 0 ? "" : output.Substring(index + 1);
                    }
                    else
                    {
                        output += '\n';
                    }
                }
                if (output.Any())
                {
                    await e.User.SendMessageAsync(Format.Code(output));
                }
            });

            group.CreateCommand("status")
            .Description("I'll tell you some useful stats about myself.")
            .Do(async e => await e.Channel.SendMessageAsync($"I'm connected to {client.Guilds.Count()} servers, which have a total of {client.Guilds.SelectMany(x => x.TextChannels).Count()} text and {client.Guilds.SelectMany(x => x.VoiceChannels).Count()} voice channels, and see a total of {client.Guilds.SelectMany(x => x.Users).Distinct().Count()} different users.\n{Format.Code($"Uptime: {Helpers.Uptime()}\n{Console.Title}")}"));

            group.CreateCommand("version")
            .Description("I'll tell you the current version and check if a newer version is available.")
            .Do(async e => await e.Channel.SendMessageAsync(VersionCheck()));

            Common.AddCommands(group);

            group.CreateCommand("playeravatar")
            .Parameter("username1", Commands.ParameterType.Required)
            .Parameter("username2", Commands.ParameterType.Optional)
            .Parameter("username3", Commands.ParameterType.Multiple)
            .Description("I'll get you the avatar of each Player.me username provided.")
            .Do(async e =>
            {
                var rclient = Helpers.GetRestClient("https://player.me/api/v1/auth");
                var request = new RestRequest("pre-login", Method.POST);
                foreach (string s in e.Args)
                {
                    request.AddQueryParameter("login", s);
                    JObject result = JObject.Parse(rclient.Execute(request).Content);
                    await e.Channel.SendMessageAsync(s + (result["success"].ToObject <bool>() == false
                            ? " was not found." : $"'s avatar: https:{result["results"]["avatar"]["original"]}"));
                }
            });

            if (config["LastFM"].HasValues)
            {
                lfclient = new LastFM.LastfmClient(config["LastFM"]["apikey"].ToString(), config["LastFM"]["apisecret"].ToString());
                group.CreateCommand("lastfm")
                .Parameter("username(s)", Commands.ParameterType.Unparsed)
                .Description("I'll tell you the last thing you, a lastfm user, or users on this server (if I know their lastfm) listened to.")
                .Do(async e =>
                {
                    var api      = new LastFM.UserApi(lfclient.Auth, lfclient.HttpClient);
                    var users    = e.Args[0].Any() ? e.Message.MentionedUserIds.Any() ? e.Message.Tags.Where(x => x.Type == TagType.UserMention).Select(x => x.Value as IUser) : null : new[] { e.User };
                    var response = "";
                    if (users == null)
                    {
                        response = await GetLastScrobble(api, Tuple.Create(e.Args[0], e.Args[0], false));
                    }
                    else
                    {
                        foreach (var user in (from u in users select Tuple.Create(SQL.ReadUser(u.Id, "lastfm"), u.Username, u == e.User)))
                        {
                            response += (user.Item1 != null ? await GetLastScrobble(api, user)
                                    : $"I don't know {(user.Item3 ? "your" : $"{user.Item2}'s")} lastfm yet{(user.Item3 ? ", please use the `setlastfm <username>` command" : "")}"
                                         ) + ".\n";
                        }
                    }
Example #6
0
 public LastfmTileBuilder(LastfmApiConfig config, HttpClient httpClient)
 {
     _config = config;
     _lastfmClient = new LastfmClient(config.Key, config.Secret, httpClient);
 }
Example #7
0
        // Commands first to help with adding new commands
        static void GenerateCommands(CommandGroupBuilder group)
        {
            // User commands
            group.CreateCommand("servers")
                .Description("I'll send you statistics about the servers, channels and users (can be spammy, goes to private).")
                .MinPermissions(4)
                .Do(async e =>
                {
                    var output = "";
                    foreach (var server in client.Servers)
                    {
                        output += $"{server.Name}: {server.TextChannels.Count()} text & {server.VoiceChannels.Count()} voice channels, {server.Users.Count()} users. ID: {server.Id}";
                        if (output.Length >= 2000)
                        {
                            var index = output.Length == 2000 ? 0 : output.LastIndexOf('\n');
                            await e.User.SendMessage(Format.Code(index == 0 ? output : output.Substring(0, index)));
                            output = index == 0 ? "" : output.Substring(index+1);
                        }
                        else output += '\n';
                    }
                    if (output.Any()) await e.User.SendMessage(Format.Code(output));
                });

            group.CreateCommand("status")
                .Description("I'll tell you some useful stats about myself.")
                .Do(async e => await e.Channel.SendMessage($"I'm connected to {client.Servers.Count()} servers, which have a total of {client.Servers.SelectMany(x => x.TextChannels).Count()} text and {client.Servers.SelectMany(x => x.VoiceChannels).Count()} voice channels, and see a total of {client.Servers.SelectMany(x => x.Users).Distinct().Count()} different users.\n{Format.Code($"Uptime: {Helpers.Uptime()}\n{Console.Title}")}"));

            group.CreateCommand("version")
                .Description("I'll tell you the current version and check if a newer version is available.")
                .Do(async e =>
                {
                    var version = Config.AppVersion;
                    string[] versions = version.Split('.');
                    string remoteversion = JObject.Parse(Helpers.GetRestClient("https://raw.githubusercontent.com").Execute<JObject>(new RestRequest("Kusoneko/Nekobot/master/version.json", Method.GET)).Content)["version"].ToString();
                    string[] remoteversions = remoteversion.Split('.');
                    int diff;
                    string section =
                        (diff = int.Parse(versions[0]) - int.Parse(remoteversions[0])) != 0 ? $"major version{(Math.Abs(diff) == 1 ? "" : "s")}" :
                        (diff = int.Parse(versions[1]) - int.Parse(remoteversions[1])) != 0 ? $"minor version{(Math.Abs(diff) == 1 ? "" : "s")}" :
                        (diff = int.Parse(versions[2]) - int.Parse(remoteversions[2])) != 0 ? $"patch{(Math.Abs(diff) == 1 ? "" : "es")}" : null;
                    await e.Channel.SendMessage($"I'm {(section == null ? $"up to date! (Current version: {version})" : $"currently {Math.Abs(diff)} {section} {(diff > 0 ? "ahead" : "behind")}. (Current version: {version}, latest {("released ")}version: {remoteversion})")}");
                });

            Common.AddCommands(group);

            group.CreateCommand("playeravatar")
                .Parameter("username1", Commands.ParameterType.Required)
                .Parameter("username2", Commands.ParameterType.Optional)
                .Parameter("username3", Commands.ParameterType.Multiple)
                .Description("I'll get you the avatar of each Player.me username provided.")
                .Do(async e =>
                {
                    var rclient = Helpers.GetRestClient("https://player.me/api/v1/auth");
                    var request = new RestRequest("pre-login", Method.POST);
                    foreach (string s in e.Args)
                    {
                        request.AddQueryParameter("login", s);
                        JObject result = JObject.Parse(rclient.Execute(request).Content);
                        await e.Channel.SendMessage(s + (result["success"].ToObject<bool>() == false
                            ? " was not found." : $"'s avatar: https:{result["results"]["avatar"]["original"]}"));
                    }
                });

            if (config["LastFM"].HasValues)
            {
                lfclient = new LastFM.LastfmClient(config["LastFM"]["apikey"].ToString(), config["LastFM"]["apisecret"].ToString());
                group.CreateCommand("lastfm")
                    .Parameter("username(s)", Commands.ParameterType.Unparsed)
                    .Description("I'll tell you the last thing you, a lastfm user, or users on this server (if I know their lastfm) listened to.")
                    .Do(async e =>
                    {
                        var api = new LastFM.UserApi(lfclient.Auth, lfclient.HttpClient);
                        var users = e.Args[0].Any() ? e.Message.MentionedUsers.Any() ? e.Message.MentionedUsers : null : new[]{e.User};
                        var response = "";
                        if (users == null)
                            response = await GetLastScrobble(api, Tuple.Create(e.Args[0], e.Args[0], false));
                        else foreach (var user in (from u in users select Tuple.Create(SQL.ReadUser(u.Id, "lastfm"), u.Name, u == e.User)))
                            response += (user.Item1 != null ? await GetLastScrobble(api, user)
                                    : $"I don't know {(user.Item3 ? "your" : $"{user.Item2}'s")} lastfm yet{(user.Item3 ? ", please use the `setlastfm <username>` command" : "")}"
                                ) + ".\n";
                        await e.Channel.SendMessage(response);
                    });

                group.CreateCommand("setlastfm")
                    .Parameter("username", Commands.ParameterType.Unparsed)
                    .Description("I'll remember your lastfm username.")
                    .Do(async e =>
                    {
                        var lastfm = e.Args[0];
                        if (lastfm.Any() && lastfm.Length < 16)
                        {
                            lastfm = $"'{lastfm}'";
                            await SQL.AddOrUpdateUserAsync(e.User.Id, "lastfm", lastfm);
                            await e.Channel.SendMessage($"I'll remember your lastfm is {lastfm} now, {e.User.Name}.");
                        }
                        else await e.Channel.SendMessage($"'{lastfm}' is not a valid lastfm username.");
                    });
            }
Example #8
0
        public static void Main(string[] args)
        {
            Console.WriteLine("DiscordSharp Tester");
            client.ClientPrivateInformation = new DiscordUserInformation();

            if (File.Exists("credentials.txt"))
            {
                using (StreamReader sr = new StreamReader("credentials.txt"))
                {
                    client.ClientPrivateInformation.email = sr.ReadLine();
                    client.ClientPrivateInformation.password = sr.ReadLine();
                }
            }
            else
            {
                Console.Write("Please enter your email: ");
                string email = Console.ReadLine();
                client.ClientPrivateInformation.email = email;

                Console.Write("Now, your password (visible): ");
                string pass = Console.ReadLine();
                client.ClientPrivateInformation.password = pass;
            }

            Console.WriteLine("Attempting login..");

            var worker = new Thread(() =>
            {
                client.DebugMessageReceived += (sender, e) =>
                {
                    client.SendMessageToUser("[DEBUG MESSAGE]: " + e.message, client.GetServersList().Find(x => x.members.Find(y => y.user.username == "Axiom") != null).members.Find(x => x.user.username == "Axiom"));
                };
                client.UnknownMessageTypeReceived += (sender, e) =>
                {
                    using (var sw = new StreamWriter(e.RawJson["t"].ToString() + ".txt"))
                    {
                        sw.WriteLine(e.RawJson);
                    }
                    client.SendMessageToUser("Heya, a new message type, '" + e.RawJson["t"].ToString() + "', has popped up!", client.GetServersList().Find(x => x.members.Find(y => y.user.username == "Axiom") != null).members.Find(x => x.user.username == "Axiom"));
                };
                client.VoiceStateUpdate += (sender, e) =>
                {
                    Console.WriteLine("***Voice State Update*** User: "******"Server Created: " + e.server.name);
                };
                client.MessageEdited += (sender, e) =>
                {
                    if (e.author.user.username == "Axiom")
                        client.SendMessageToChannel("What the f**k, <@" + e.author.user.id + "> you can't event type your message right. (\"" + e.MessageEdited.content + "\")", e.Channel);
                };
                client.ChannelCreated += (sender, e) =>
                {
                    var parentServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.ChannelCreated.id) != null);
                    if (parentServer != null)
                        Console.WriteLine("Channel {0} created in {1}!", e.ChannelCreated.name, parentServer.name);
                };
                client.PrivateChannelCreated += (sender, e) =>
                {
                    Console.WriteLine("Private channel started with {0}", e.ChannelCreated.recipient.username);
                };
                client.PrivateMessageReceived += (sender, e) =>
                {
                    client.SendMessageToUser("Pong!", e.author);
                };
                client.MentionReceived += (sender, e) =>
                {
                    if (e.author.user.id != client.Me.user.id)
                        client.SendMessageToChannel("Heya, @" + e.author.user.username, e.Channel);
                };
                client.MessageReceived += (sender, e) =>
                {
                    DiscordServer fromServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                    Console.WriteLine("[- Message from {0} in {1} on {2}: {3}", e.author.user.username, e.Channel.name, fromServer.name, e.message.content);
                    if (e.message.content.StartsWith("?status"))
                        client.SendMessageToChannel("I work ;)", e.Channel);
                    else if (e.message.content.StartsWith("?notify"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                    }
                    else if (e.message.content.StartsWith("?whereami"))
                    {
                        DiscordServer server = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                        string owner = "";
                        foreach (var member in server.members)
                            if (member.user.id == server.owner_id)
                                owner = member.user.username;
                        string whereami = String.Format("I am currently in *#{0}* ({1}) on server *{2}* ({3}) owned by {4}. The channel's topic is: {5}", e.Channel.name, e.Channel.id, server.name, server.id, owner, e.Channel.topic);
                        client.SendMessageToChannel(whereami, e.Channel);
                    }
                    else if (e.message.content.StartsWith("?test_game"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 0)
                        {
                            client.UpdateCurrentGame(int.Parse(split[1]));
                        }
                    }
                    else if (e.message.content.StartsWith("?gtfo"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 1)
                        {
                            DiscordServer curServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == split[1]) != null);
                            if (curServer != null)
                            {
                                client.SendMessageToChannel("Leaving server " + curServer.name, e.Channel);
                                client.LeaveServer(curServer.id);
                            }
                        }
                        else
                        {
                            DiscordServer curServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                            client.SendMessageToChannel("Bye!", e.Channel);
                            client.LeaveServer(curServer.id);
                        }
                    }
                    else if (e.message.content.StartsWith("?everyone"))
                    {
                        DiscordServer server = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 1)
                        {
                            string message = "";
                            foreach (var user in server.members)
                            {
                                if (user.user.id == client.Me.user.id)
                                    continue;
                                if (user.user.username == "Blank")
                                    continue;
                                message += "@" + user.user.username + " ";
                            }
                            message += ": " + split[1];
                            client.SendMessageToChannel(message, e.Channel);
                        }
                    }
                    else if (e.message.content.StartsWith("?lastfm"))
                    {
#if __MONOCS__
                        client.SendMessageToChannel("Sorry, not on Mono :(", e.Channel);
#else
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 1)
                        {
                            using (var lllfclient = new LastfmClient("4de0532fe30150ee7a553e160fbbe0e0", "0686c5e41f20d2dc80b64958f2df0f0c", null, null))
                            {
                                try
                                {

                                    var recentScrobbles = lllfclient.User.GetRecentScrobbles(split[1], null, 1, 1);
                                    LastTrack lastTrack = recentScrobbles.Result.Content[0];
                                    client.SendMessageToChannel(string.Format("*{0}* last listened to _{1}_ by _{2}_", split[1], lastTrack.Name, lastTrack.ArtistName), e.Channel);
                                }
                                catch
                                {
                                    client.SendMessageToChannel(string.Format("User _*{0}*_ not found!", split[1]), e.Channel);
                                }
                            }
                        }
                        else
                            client.SendMessageToChannel("Who??", e.Channel);
#endif
                    }
                    else if (e.message.content.StartsWith("?rename"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 0)
                        {
                            //client.ChangeBotUsername(split[1]);
                            DiscordUserInformation newUserInfo = client.ClientPrivateInformation;
                            newUserInfo.username = split[1].ToString();
                            client.ChangeBotInformation(newUserInfo);
                        }
                    }
                    else if (e.message.content.StartsWith("?changepic"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 0)
                        {
                            Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase);
                            string rawString = $"{split[1]}";
                            if (linkParser.Matches(rawString).Count > 0)
                            {
                                string url = linkParser.Matches(rawString)[0].ToString();
                                using (WebClient wc = new WebClient())
                                {
                                    byte[] data = wc.DownloadData(url);
                                    using (MemoryStream mem = new MemoryStream(data))
                                    {
                                        using (var image = System.Drawing.Image.FromStream(mem))
                                        {
                                            client.ChangeBotPicture(new Bitmap(image));
                                        }
                                    }
                                }
                            }
                        }
                    }
                    else if (e.message.content.StartsWith("?whois"))
                    {
                        //?whois <@01393408>
                        Regex r = new Regex("\\d+");
                        Match m = r.Match(e.message.content);
                        Console.WriteLine("WHOIS INVOKED ON: " + m.Value);
                        var foundServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                        if (foundServer != null)
                        {
                            var foundMember = foundServer.members.Find(x => x.user.id == m.Value);
                            client.SendMessageToChannel(string.Format("<@{0}>: {1}, {2}", foundMember.user.id, foundMember.user.id, foundMember.user.username), e.Channel);
                        }
                    }
                    else if (e.message.content.StartsWith("?prune"))
                    {
                        string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                        if (split.Length > 0)
                        {
                            if (split[1].Trim() == "all")
                            {
                                int messagesDeleted = client.DeleteAllMessages();
                                if (split.Length > 1 && split[2] != "nonotice")
                                    client.SendMessageToChannel(messagesDeleted + " messages deleted across all channels.", e.Channel);
                            }
                            else if (split[1].Trim() == "here")
                            {
                                int messagesDeleted = client.DeleteAllMessagesInChannel(e.Channel);
                                if (split.Length > 1 && split[2] != "nonotice")
                                    client.SendMessageToChannel(messagesDeleted + " messages deleted in channel '" + e.Channel.name + "'.", e.Channel);
                            }
                            else
                            {
                                DiscordChannel channelToPrune = client.GetChannelByName(split[1].Trim());
                                if (channelToPrune != null)
                                {
                                    int messagesDeleted = client.DeleteAllMessagesInChannel(channelToPrune);
                                    if (split.Length > 1 && split[2] != "nonotice")
                                        client.SendMessageToChannel(messagesDeleted + " messages deleted in channel '" + channelToPrune.name + "'.", e.Channel);
                                }
                            }
                        }
                        else
                        {
                            client.SendMessageToChannel("Prune what?", e.Channel);
                        }
                    }
                    else if (e.message.content.StartsWith("?quoththeraven"))
                        client.SendMessageToChannel("nevermore", e.Channel);
                    else if (e.message.content.StartsWith("?quote"))
                        client.SendMessageToChannel("Luigibot does what Reta don't.", e.Channel);
                    else if (e.message.content.StartsWith("?selfdestruct"))
                    {
                        if (e.author.user.username == "Axiom")
                            client.SendMessageToChannel("restaroni in pepparoni", e.Channel);
                        Environment.Exit(0);
                    }
                    else if (e.message.content.StartsWith("?changetopic"))
                    {
                        if (e.author.user.username == "Axiom")
                        {
                            string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                            if (split.Length > 0)
                                client.ChangeChannelTopic(split[1], e.Channel);
                        }
                    }
                    else if (e.message.content.StartsWith("?join"))
                    {
                        if (e.author.user.username == "Axiom")
                        {
                            string[] split = e.message.content.Split(new char[] { ' ' }, 2);
                            if (split.Length > 0)
                            {
                                string substring = split[1].Substring(split[1].LastIndexOf('/') + 1);
                                //client.SendMessageToChannel(substring, e.Channel);
                                client.AcceptInvite(substring);
                            }
                        }
                    }
                };
                client.Connected += (sender, e) =>
                {
                    Console.WriteLine("Connected! User: "******"Closed ({0}): {1}", e.Code, e.Reason);
                };
                //ConnectStuff();
                //while (true) ;
                if (client.SendLoginRequest() != null)
                {
                    Console.WriteLine("Logged in!");

                    client.ConnectAndReadMessages();
                    Console.WriteLine($"Connected to {client.CurrentGatewayURL}");
                    client.UpdateCurrentGame(256);
                }
            });
            worker.Start();

            InputCheck();
            //System.Windows.Forms.Application.Run();
            /**
            Since this is a test app and people actually do read my code...
            I'd like to say one thing:
            If you're not going to be doing any input accepting **INSIDE OF THE CONSOLE** you don't have to setup 
            a seperate thread for the client and accept input on main. This is why I've only commented out
            the System.Windows.Forms.Application.Run(); part instead of removing it.

            If you're not accepting input, you can just run client on the main thread and run that 
            System.Windows.Forms.Application.Run(); snippet and this will keep the app alive, with no CPU 
            hit!
            */
            client.Dispose();

            Console.ReadLine();
        }
Example #9
0
        /// <summary>
        /// Interprets commands
        /// </summary>
        /// <param name="command">The full message</param>
        /// <param name="sender">The full sender</param>
        /// <param name="recipient">The full recipient</param>
        private static void InterpretCommand(string command, IrcUser sender, IrcClient client)
        {
            if (command.StartsWith ("?slap"))
            {
                if (ProgramSettings.settings.SlapEnabled)
                {
                    string[] splitCommand = command.Split (new char[] { ' ' }, 2);
                    if (splitCommand.Length > 1)
                    {
                        var listCopy = UsersList;
                        bool foundUser = false;
                        try
                        {
                            foreach (IrcUserAndSeen user in listCopy)
                            {
                                if (user.User.Nick.ToLower () == splitCommand [1].ToLower ().Trim ())
                                {
                                    if (user.User.Nick == client.User.Nick)
                                        client.SendRawMessage ("PRIVMSG {0} :What'd I do? :(", client.Channels [0].Name);
                                    else
                                        client.SendRawMessage ("PRIVMSG {0} :" + "\x01" + "ACTION slaps {1} with a giant fish.\x01", client.Channels [0].Name, user.User.Nick);
                                    foundUser = true;
                                    break;
                                }
                            }
                            if (!foundUser)
                                client.SendRawMessage ("PRIVMSG {0} :User not found!");
                        } catch (Exception ex)
                        {
                        }
                    } else
                        client.SendRawMessage ("PRIVMSG {0} :Slap who?", client.Channels [0].Name);
                }
            }
            if (command.StartsWith ("?ann"))
            {
                string[] splitCommand = command.Split (new char[]{ ' ' }, 2);
                if (splitCommand.Length > 1)
                {
                    foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                    {
                        if (sender.Nick.ToLower () == nick)
                        {
                            if (splitCommand [1] == "test")
                            {
                                if (ProgramSettings.settings.WelcomeMessage.Contains ("/me"))
                                {
                                    client.SendAction (String.Format (ProgramSettings.settings.WelcomeMessage.Substring (4), sender), client.Channels [0].Name);
                                } else
                                {
                                    client.SendRawMessage ("PRIVMSG {0} :{1}",
                                        client.Channels [0].Name,
                                        String.Format (ProgramSettings.settings.WelcomeMessage, sender));
                                }
                            } else
                            {
                                ProgramSettings.settings.WelcomeMessage = splitCommand [1];
                                client.SendRawMessage ("PRIVMSG {0} :Welcome message set!", client.Channels [0].Name);
                                Console.ForegroundColor = ConsoleColor.Yellow;
                                Console.WriteLine ("New welcome message set: " + splitCommand [1]);
                                Console.BackgroundColor = ConsoleColor.White;
                            }
                        }
                    }
                }
                else
                {
                    client.SendRawMessage ("PRIVMSG {0} :What message do I set?", client.Channels[0].Name);
                }
            }
            if (command.StartsWith ("?enableslap"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.SlapEnabled = true;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Enabling slap");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("?enablewelcome"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.WelcomeUserEnabled = true;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Enabling welcome messages");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("?disablewelcome"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.WelcomeUserEnabled = false;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Disabling welcome messages");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("?disableslap"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.SlapEnabled = false;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Disabling slap");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("?eightball") || command.StartsWith ("!8ball") || command.StartsWith ("!fortune"))
            {
                if (ProgramSettings.settings.EightballEnabled)
                {
                    int ranMessage = random.Next (EightballMessages.Length - 1);
                    if (command.ToLower ().Contains ("waluigibot1337") || command.ToLower ().Contains ("waluigibot") || command.ToLower ().Contains ("waluigi bot"))
                        client.SendRawMessage ("PRIVMSG {0} :Waluigibot is a tool and will never come to fruition.", client.Channels [0].Name);
                    else if (command.ToLower ().Contains ("bot") && !command.ToLower ().Contains ("luigi"))
                        client.SendRawMessage ("PRIVMSG {0} :Your bot is inadequate for the job.", client.Channels [0].Name);
                    else
                        client.SendRawMessage ("PRIVMSG {0} :{1}", client.Channels [0].Name, EightballMessages [ranMessage]);
                }
            }
            if (command.StartsWith ("?status"))
            {
                client.SendRawMessage ("PRIVMSG {0} :Slap Enabled: {1}. Eight Ball Enabled: {2}. Welcome Enabled: {3}",
                    client.Channels [0].Name,
                    ProgramSettings.settings.SlapEnabled,
                    ProgramSettings.settings.EightballEnabled,
                    ProgramSettings.settings.WelcomeUserEnabled);
            }
            if (command.StartsWith ("?lastfm"))
            {
                string[] split = command.Split (new char[] { ' ' }, 2);
                if (split.Length > 1)
                {
                    try
                    {
                        var lastfmClient = new LastfmClient ("4de0532fe30150ee7a553e160fbbe0e0", "0686c5e41f20d2dc80b64958f2df0f0c");
                        var response = lastfmClient.User.GetRecentScrobbles (split [1].ToString ().Trim (), null, 0, 1);
                        LastTrack lastTrack = response.Result.Content [0];
                        client.SendRawMessage ("PRIVMSG {0} :{1} last listened to {2} by {3}.", client.Channels [0].Name, split [1].Trim (), lastTrack.Name, lastTrack.ArtistName);
                    } catch (ArgumentOutOfRangeException iex)
                    {
                        client.SendRawMessage ("PRIVMSG {0} :That user doesn't exist or hasn't scrobbled anything yet!",
                            client.Channels [0].Name);
                    } catch (Exception ex)
                    {
                        client.SendRawMessage ("PRIVMSG {0} :Uh-oh! Luigibot encountered an error. Email Luigifan @ [email protected]",
                            client.Channels [0].Name);

                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine ("UH OH BIG ERROR\nUH OH BIG ERROR");
                        Console.ForegroundColor = ConsoleColor.White;
                        Console.WriteLine (ex.Message + "\n");
                    }
                }
            }
            if (command.StartsWith ("?enable8ball") || command.StartsWith ("!enableeightball"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.EightballEnabled = true;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Enabling eight ball");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("?disable8ball") || command.StartsWith ("!disableeightball"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ProgramSettings.settings.EightballEnabled = false;

                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine ("Disabling eight ball");
                        Console.ForegroundColor = ConsoleColor.White;

                        break;
                    }
                }
            }
            if (command.StartsWith ("?selfdestruct"))
            {
                foreach (var nick in ProgramSettings.settings.UsersAllowedToDisable)
                {
                    if (sender.Nick.ToLower () == nick)
                    {
                        ExitSafely ();
                        break;
                    }
                }
            }
            if (command.StartsWith ("?42"))
            {
                client.SendRawMessage ("PRIVMSG {0} :The Answer to Life, the Universe, and Everything.", client.Channels [0].Name);
            }
            if (command.StartsWith ("?commands"))
            {
                client.SendRawMessage ("PRIVMSG {0} :You can find a list of my commands here: https://github.com/Luigifan/Luigibot/wiki/Luigibot-Commands", client.Channels [0].Name);
            }
            if (command.StartsWith ("?seen"))
            {
                string[] splitCommand = command.Split (new char[] { ' ' }, 2);
                if (splitCommand.Length > 1)
                {
                    if (splitCommand [1].ToLower () == "knux" || splitCommand [1].ToLower () == "knuckles" || splitCommand [1].ToLower () == "knuckles96")
                    {
                        client.SendRawMessage ("PRIVMSG {0} :Never.", client.Channels [0].Name);
                        return;
                    }
                    var UsersListCopy = UsersList;
                    var UserDatabaseCopy = UsersSeenDatabase.UsersSeenDatabase;
                    //First, check to see if the user is on now
                    bool foundInOnline = false;
                    foreach (IrcUserAndSeen user in UsersListCopy)
                    {
                        if (user.User.Nick.ToLower () == splitCommand [1].ToLower ().Trim ())
                        {
                            foundInOnline = true;
                            if (user.User.Nick == client.User.Nick)
                                client.SendRawMessage ("PRIVMSG {0} :I'm always online c:", client.Channels [0].Name);
                            else
                                client.SendRawMessage ("PRIVMSG {0} :That user is online now!", client.Channels [0].Name);
                            foundInOnline = true;
                            break;
                        }
                    }
                    //Then, we'll check the database
                    bool foundInDatabase = false;
                    if (!foundInOnline)
                    {
                        foreach (IrcUserAndSeen user in UserDatabaseCopy)
                        {
                            if (user.User.Nick.ToLower () == splitCommand [1].ToLower ().Trim ())
                            {
                                foundInDatabase = true;
                                client.SendRawMessage ("PRIVMSG {0} :{1} was last seen at {2} (EST)", client.Channels [0].Name, user.User.Nick, user.LastSeen.ToString ());
                                break;
                            }
                        }
                        if (!foundInDatabase && !foundInOnline)
                            client.SendRawMessage ("PRIVMSG {0} :I'm not sure :(", client.Channels [0].Name);
                    }
                } else
                    client.SendRawMessage ("PRIVMSG {0} :Last seen who?", client.Channels [0].Name);
            }
        }
Example #10
0
        public static void Main(string[] args)
        {
            Console.WriteLine("DiscordSharp Tester");
            client.LoginInformation = new DiscordLoginInformation();
            Console.Write("Please enter your email: ");
            string email = Console.ReadLine();
            client.LoginInformation.email[0] = email;

            Console.Write("Now, your password (visible): ");
            string pass = Console.ReadLine();
            client.LoginInformation.password[0] = pass;

            Console.WriteLine("Attempting login..");
            client.MessageReceived += (sender, e) =>
            {
                Console.WriteLine(e.message);
            };
            client.URLMessageAutoUpdate += (sender, e) =>
            {
                string message = "*URL(s) Submitted:*\n";
                for (int i = 0; i < e.embeds.Count; i++)
                    message += string.Format("{0}: Title: {1}, URL: {2}, Type: {3}, Description: {4}, Provider URL: {5}, Provider Name: {6}\n",
                        i, e.embeds[i].title, e.embeds[i].url, e.embeds[i].type, e.embeds[i].description, e.embeds[i].provider_url, e.embeds[i].provider_name);
                client.SendMessageToChannel(message, e.channel);
            };

            client.UserTypingStart += (sender, e) =>
            {
            };
            client.MessageEdited += (sender, e) =>
            {
                if (e.author.user.username == "Axiom")
                    client.SendMessageToChannel("What the f**k, <@" + e.author.user.id + "> you can't event type your message right. (\"" + e.MessageEdited.content + "\")", e.Channel);
            };
            client.ChannelCreated += (sender, e) =>
            {
                var parentServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.ChannelCreated.id) != null);
                if (parentServer != null)
                    Console.WriteLine("Channel {0} created in {1}!", e.ChannelCreated.name, parentServer.name);
            };
            client.PrivateChannelCreated += (sender, e) =>
            {
                Console.WriteLine("Private channel started with {0}", e.ChannelCreated.recipient.username);
            };
            client.PrivateMessageReceived += (sender, e) =>
            {
                client.SendMessageToUser("Pong!", e.author);
            };
            client.MentionReceived += (sender, e) =>
            {
                if (e.author.user.id != client.Me.user.id)
                    client.SendMessageToChannel("Heya, @" + e.author.user.username, e.Channel);
            };
            client.MessageReceived += (sender, e) =>
            {
                DiscordServer fromServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                Console.WriteLine("[- Message from {0} in {1} on {2}: {3}", e.author.user.username, e.Channel.name, fromServer.name, e.message);
                if (e.message.StartsWith("?status"))
                    client.SendMessageToChannel("I work ;)", e.Channel);
                else if (e.message.StartsWith("?notify"))
                {
                    string[] split = e.message.Split(new char[] { ' ' }, 2);
                }
                else if (e.message.StartsWith("?whereami"))
                {
                    DiscordServer server = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                    string owner = "";
                    foreach (var member in server.members)
                        if (member.user.id == server.owner_id)
                            owner = member.user.username;
                    string whereami = String.Format("I am currently in *#{0}* ({1}) on server *{2}* ({3}) owned by {4}.", e.Channel.name, e.Channel.id, server.name, server.id, owner);
                    client.SendMessageToChannel(whereami, e.Channel);
                }
                else if (e.message.StartsWith("?everyone"))
                {
                    DiscordServer server = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                    string[] split = e.message.Split(new char[] { ' ' }, 2);
                    if (split.Length > 1)
                    {
                        string message = "";
                        foreach (var user in server.members)
                        {
                            if (user.user.id == client.Me.user.id)
                                continue;
                            if (user.user.username == "Blank")
                                continue;
                            message += "@" + user.user.username + " ";
                        }
                        message += ": " + split[1];
                        client.SendMessageToChannel(message, e.Channel);
                    }
                }
                else if (e.message.StartsWith("?lastfm"))
                {
#if __MONOCS__
                        client.SendMessageToChannel("Sorry, not on Mono :(", e.Channel);
#else
                    string[] split = e.message.Split(new char[] { ' ' }, 2);
                    if (split.Length > 1)
                    {
                        using (var lllfclient = new LastfmClient("4de0532fe30150ee7a553e160fbbe0e0", "0686c5e41f20d2dc80b64958f2df0f0c", null, null))
                        {
                            try
                            {
                                var recentScrobbles = lllfclient.User.GetRecentScrobbles(split[1], null, 0, 1);
                                LastTrack lastTrack = recentScrobbles.Result.Content[0];
                                client.SendMessageToChannel(string.Format("*{0}* last listened to _{1}_ by _{2}_", split[1], lastTrack.Name, lastTrack.ArtistName), e.Channel);
                            }
                            catch
                            {
                                client.SendMessageToChannel(string.Format("User _*{0}*_ not found!", split[1]), e.Channel);
                            }
                        }
                    }
                    else
                        client.SendMessageToChannel("Who??", e.Channel);
#endif
                }
                else if (e.message.StartsWith("?whois"))
                {
                    //?whois <@01393408>
                    Regex r = new Regex("\\d+");
                    Match m = r.Match(e.message);
                    Console.WriteLine("WHOIS INVOKED ON: " + m.Value);
                    var foundServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null);
                    if (foundServer != null)
                    {
                        var foundMember = foundServer.members.Find(x => x.user.id == m.Value);
                        client.SendMessageToChannel(string.Format("<@{0}>: {1}, {2}", foundMember.user.id, foundMember.user.id, foundMember.user.username), e.Channel);
                    }
                }
                else if (e.message.StartsWith("?quoththeraven"))
                    client.SendMessageToChannel("nevermore", e.Channel);
                else if (e.message.StartsWith("?quote"))
                    client.SendMessageToChannel("Luigibot does what Reta don't.", e.Channel);
                else if (e.message.StartsWith("?selfdestruct"))
                {
                    if (e.author.user.username == "Axiom")
                        client.SendMessageToChannel("riparoni and cheese", e.Channel);
                    Environment.Exit(0);
                }
            };
            client.Connected += (sender, e) =>
            {
                Console.WriteLine("Connected! User: "******"Closed ({0}): {1}", e.Code, e.Reason);
            };
            ConnectStuff();
            while (true) ;
        }
 /// <summary>
 /// Creates a new <see cref="LastfmClient"/>.
 /// </summary>
 internal static void CreateNewClient()
 {
   Client = new LastfmClient(APIKEY, APISECRET);
   ClientAuthChanged?.Invoke(null, EventArgs.Empty);
 }