Пример #1
0
        private void OnChatMsg(SteamFriends.ChatMsgCallback callback)
        {
            Kraxbot.Log($"{kraxbot.GetFriendPersonaName(callback.ChatterID)} ({callback.ChatRoomID}): {callback.Message}");

            // TODO: We could launch this in another thread to let it do heavy stuff
            cmnd.Handle(callback.ChatRoomID, callback.ChatterID, callback.Message);
        }
Пример #2
0
        private void OnLoginKey(SteamUser.LoginKeyCallback callback)
        {
            // Save unique ID to use with SteamCommunity
            kraxbot.UniqueID = callback.UniqueID;

            // Save key to file
            File.WriteAllTextAsync("loginkey", callback.LoginKey);
            kraxbot.AcceptNewLoginKey(callback);
            Kraxbot.Log("Saved login key");
        }
Пример #3
0
        public void InviteToGroup(ulong groupID, ulong userID)
        {
            if (!IsLoggedOn)
            {
                return;
            }

            var          postData = $"group={groupID}&invitee={userID}&sessionID={SessionID}&type=groupInvite";
            const string url      = "https://steamcommunity.com/actions/GroupInvite";

            Kraxbot.Log($"InviteToGroup: {Request(url, postData)}");
        }
Пример #4
0
        public void PostComment(SteamID userID, string comment)
        {
            if (!IsLoggedOn)
            {
                return;
            }

            var postData = $"comment={comment}&count=6&sessionid={SessionID}";
            var url      = $"http://steamcommunity.com/comment/Profile/post/{userID.ConvertToUInt64()}/-1/";

            var response = Request(url, postData);

            Kraxbot.Log(response);
        }
Пример #5
0
        private void OnLoggedOn(SteamUser.LoggedOnCallback callback)
        {
            if (callback.Result != EResult.OK)
            {
                // Just so guard and two factor can have the same name
                string code;

                switch (callback.Result)
                {
                // Steam Guard
                case EResult.AccountLogonDenied:
                    Console.Write("Steam Guard: ");
                    code = Console.ReadLine();
                    kraxbot.Login(code);
                    return;

                // Two factor
                case EResult.AccountLoginDeniedNeedTwoFactor:
                    Console.Write("Two factor: ");
                    code = Console.ReadLine();
                    kraxbot.Login(null, code);
                    return;

                // Other error
                default:
                    Kraxbot.Error($"Login failed: {callback.Result}");
                    return;
                }
            }

            // Log
            Kraxbot.Log("Logged in");

            // Save WebAPI stuff
            if (callback.Result == EResult.OK)
            {
                kraxbot.UserNonce = callback.WebAPIUserNonce;
            }

            // Login to Web
            kraxbot.LogOnToWeb();

            // Join chatrooms
            foreach (var chatroom in chatrooms)
            {
                joiningChatroom = chatroom;
                kraxbot.JoinChatRoom(chatroom);
            }
        }
Пример #6
0
        private void OnChatEnter(SteamFriends.ChatEnterCallback callback)
        {
            // TODO: This is triggered on group event

            if (joiningChatroom == null)
            {
                Kraxbot.Log($"Warning: Tried to enter {callback.ChatRoomName} without getting an invite, possible group invite?");
                return;
            }

            var settings = kraxbot.GetChatRoomSettings(callback.ChatID);

            // Fill settings with stuff
            settings.ChatName = callback.ChatRoomName;

            // Add users
            foreach (var member in callback.ChatMembers)
            {
                var user = settings.Users.SingleOrDefault(u => u.SteamID == member.SteamID);

                if (user == default(UserInfo))
                {
                    // User doesn't exist, create
                    settings.Users.Add(new UserInfo
                    {
                        Name       = kraxbot.GetFriendPersonaName(member.SteamID),
                        SteamID    = member.SteamID,
                        Rank       = member.Details,
                        Permission = member.Permissions
                    });
                }
                else
                {
                    // User already exists in list, just update values
                    user.Name       = kraxbot.GetFriendPersonaName(member.SteamID);
                    user.Rank       = member.Details;
                    user.Permission = member.Permissions;
                }
            }

            // Add to list of current chatrooms
            chatrooms.Add(callback.ChatID);

            Kraxbot.Log($"Joined {callback.ChatRoomName} with invite from {settings.InvitedName}");

            // Reset joining chatroom
            joiningChatroom = null;
        }
Пример #7
0
        private void OnChatInvite(SteamFriends.ChatInviteCallback callback)
        {
            // TODO: Is this needed?
            if (callback.InvitedID != kraxbot.SteamID)
            {
                return;
            }

            if (string.IsNullOrEmpty(callback.ChatRoomName))
            {
                kraxbot.SendChatMessage(callback.FriendChatID, "Sorry, I can't (currently) join multi-user chats");
                return;
            }

            var userID   = callback.FriendChatID;
            var userName = kraxbot.GetFriendPersonaName(callback.FriendChatID);

            if (userID != kraxbot.KraxID && (callback.ChatRoomID == lastChatroom || userID == lastInviter))
            {
                // Set as joining the chatroom
                joiningChatroom = callback.ChatRoomID;

                Kraxbot.Log($"Got invite to {callback.ChatRoomName} from {userName}");
                kraxbot.JoinChatRoom(callback.ChatRoomID);

                lastInviter = userID;

                RegisterUserEvent(userID, UserEventType.Invite);
                RegisterGroupEvent(callback.ChatRoomID, GroupEventType.Invite);

                // Update names
                var settings = kraxbot.GetChatRoomSettings(callback.ChatRoomID);
                settings.InvitedID = callback.FriendChatID;
                if (kraxbot.TryGetFriendDetails(userID, out var friend))
                {
                    settings.InvitedName = friend.Name;
                }
            }
            else
            {
                Kraxbot.Log($"Got invited to recent chat from {userName}, declined");
                kraxbot.SendChatMessage(userID, "Sorry, I can't enter this chat. This is either because I recently left it or because you are spamming invites to chats.");
            }
        }
Пример #8
0
        public bool Authenticate(string uniqueID, string loginKey)
        {
            // Check so they are valid
            if (uniqueID == null || loginKey == null)
            {
                return(false);
            }

            var sessionID = Convert.ToBase64String(Encoding.UTF8.GetBytes(uniqueID));

            using (dynamic auth = WebAPI.GetInterface("ISteamUserAuth"))
            {
                // Generate AES session key
                var sessionKey = CryptoHelper.GenerateRandomBlock(32);

                // RSA encrypt it with public key
                byte[] cryptedSessionKey;
                using (var rsa = new RSACrypto(KeyDictionary.GetPublicKey(client.Universe)))
                    cryptedSessionKey = rsa.Encrypt(sessionKey);

                var key = new byte[20];
                Array.Copy(Encoding.ASCII.GetBytes(loginKey), key, loginKey.Length);

                // AES encrypt loginkey with session
                var cryptedLoginKey = CryptoHelper.SymmetricEncrypt(key, sessionKey);

                KeyValue authResult;

                // Get auth result
                try
                {
                    authResult = auth.AuthenticateUser(
                        steamid: client.SteamID.ConvertToUInt64(),
                        sessionkey: HttpUtility.UrlEncode(cryptedSessionKey),
                        encrypted_loginkey: HttpUtility.UrlEncode(cryptedLoginKey),
                        method: "POST",
                        secure: true
                        );
                }
                catch (Exception e)
                {
                    Kraxbot.Log($"Warning: Failed to authenticate: {e.Message}");
                    return(false);
                }

                var token       = authResult["token"].AsString();
                var tokenSecure = authResult["tokensecure"].AsString();

                // Add cookies
                Cookies.Add(new Cookie("sessionid", sessionID, string.Empty, "steamcommunity.com"));
                Cookies.Add(new Cookie("steamLogin", token, string.Empty, "steamcommunity.com"));
                Cookies.Add(new Cookie("steamLoginSecure", tokenSecure, string.Empty, "steamcommunity.com"));

                SessionID        = sessionID;
                SteamLogin       = token;
                SteamLoginSecure = tokenSecure;

                IsLoggedOn = true;

                return(true);
            }
        }
Пример #9
0
        private void OnFriendMsg(SteamFriends.FriendMsgCallback callback)
        {
            // If message is empty, it's just a 'typing...'
            if (callback.Message.Trim().Length == 0)
            {
                return;
            }

            Kraxbot.Log($"{kraxbot.GetFriendPersonaName(callback.Sender)}: {callback.Message}");

            var message = callback.Message;
            var userID  = callback.Sender;

            // PM Spam check
            if (lastFriendTime == DateTime.Now && userID == lastFriendMessage)
            {
                // oh noes
                kraxbot.SendKraxMessage($"Removed {kraxbot.GetFriendPersonaName(userID)} because of spamming in PM");
                kraxbot.RemoveFriend(userID);
                return;
            }

            // Krax commands
            if (message.StartsWith('-') && userID == kraxbot.KraxID)
            {
                if (message == "-cur_cr")
                {
                    var msg = "Chatrooms:";

                    foreach (var chatroom in chatrooms)
                    {
                        var settings = kraxbot.GetChatRoomSettings(chatroom);
                        var bot      = settings.Users.Single(u => u.SteamID == kraxbot.SteamID);

                        msg += $"\n{settings.ChatName}\tsteam://friends/joinchat/{chatroom}\t{settings.InvitedName ?? "Unknown"}\t{settings.Users.Count} users\t{bot.Rank}";
                    }

                    kraxbot.SendKraxMessage(msg);
                }

                else if (message == "-get_ip")
                {
                    using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.IP))
                    {
                        socket.Connect("0.0.0.0", 65530);
                        var endPoint = socket.LocalEndPoint as IPEndPoint;
                        kraxbot.SendKraxMessage($"IP: {endPoint?.Address}");
                    }
                }

                else if (message.StartsWith("-leave "))
                {
                    if (ulong.TryParse(message.Substring(7), out var chat))
                    {
                        kraxbot.LeaveChat(chat);
                    }
                    else
                    {
                        kraxbot.SendKraxMessage($"'{message.Substring(7)}' is not a valid chatID");
                    }
                }

                else if (message.StartsWith("-join "))
                {
                    if (ulong.TryParse(message.Substring(6), out var chat))
                    {
                        kraxbot.JoinChatRoom(chat);
                    }
                    else
                    {
                        kraxbot.SendKraxMessage($"'{message.Substring(6)}' is not a valid chatID");
                    }
                }

                else if (message.StartsWith("-invite "))
                {
                    if (ulong.TryParse(message.Substring(8), out var chat))
                    {
                        kraxbot.InviteToChat(chat, kraxbot.KraxID);
                    }
                    else
                    {
                        kraxbot.SendKraxMessage($"'{message.Substring(8)}' is not a valid chatID");
                    }
                }

                else if (message == "-get_groups")
                {
                    // TODO ?
                }
                else if (message == "-clean_groups")
                {
                    // TODO ?
                }

                else if (message == "-get_friends")
                {
                    // TODO ?
                }
                else if (message == "-clean_friends")
                {
                    // TODO ?
                }

                else if (message == "-quit")
                {
                    running = false;
                    Environment.Exit(0);
                }

                else if (message == "-fortune")
                {
                    kraxbot.SendKraxMessage($"\n{Kraxbot.ExecuteProcess("fortune", "-n 200 -s")}");
                }

                else if (message.StartsWith("-fortune "))
                {
                    if (ulong.TryParse(message.Substring(9), out var chat))
                    {
                        var fortune = Kraxbot.ExecuteProcess("fortune", "-n 200 -s");
                        kraxbot.SendChatRoomMessage(chat, $"\n{fortune}");
                    }
                    else
                    {
                        kraxbot.SendKraxMessage($"'{message.Substring(9)}' is not a valid chatID");
                    }
                }

                else if (message == "-post_comment ")
                {
                    kraxbot.PostComment(kraxbot.KraxID, message.Substring(14));
                }

                else if (message == "-login_community")
                {
                    if (kraxbot.IsLoggedOnToWeb)
                    {
                        kraxbot.SendKraxMessage("Already logged in to web");
                    }
                    else
                    {
                        kraxbot.LogOnToWeb();
                        kraxbot.SendKraxMessage("Logged in to web");
                    }
                }

                else if (message == "-login_community_force")
                {
                    kraxbot.LogOnToWeb();
                    kraxbot.SendKraxMessage("Logged in to web");
                }

                else if (message == "-getNumInvites")
                {
                    kraxbot.SendKraxMessage($"Pending invites: {kraxbot.NumInvites}");
                }
            }

            else if (message.StartsWith('!'))
            {
                kraxbot.SendChatMessage(userID, "Sorry, commands only work in group chats");
            }
            else
            {
                cmnd.HandleCleverbot(userID, message.Trim());
            }

            RegisterUserEvent(userID, UserEventType.Message);

            lastFriendTime    = DateTime.Now;
            lastFriendMessage = userID;
        }
Пример #10
0
        private void OnChatMemberInfo(SteamFriends.ChatMemberInfoCallback callback)
        {
            // TODO: We only care about state changes?
            if (callback.Type != EChatInfoType.StateChange)
            {
                return;
            }

            // Some vars
            var chatRoomID = callback.ChatRoomID;
            var info       = callback.StateChangeInfo;
            var state      = callback.StateChangeInfo.StateChange;

            var settings = kraxbot.GetChatRoomSettings(chatRoomID);

            var userID   = info.ChatterActedOn;
            var userName = GetPlayerName(userID);

            // TODO: Check for default properly
            var user = settings.Users.SingleOrDefault(u => u.SteamID == userID);

            // See what happened
            string message;

            switch (state)
            {
            case EChatMemberStateChange.Entered:      message = "Welcome";      break;                          // Joined

            case EChatMemberStateChange.Left:         message = "Good bye";     break;                          // Left

            case EChatMemberStateChange.Disconnected: message = "RIP";          break;                          // Disconnected

            case EChatMemberStateChange.Kicked:       message = "Bye";          break;                          // Kicked

            case EChatMemberStateChange.Banned:       message = "RIP in peace"; break;                          // Banned

            case EChatMemberStateChange.VoiceSpeaking:     message = "Joined voice chat: "; break;              // Joined voice chat

            case EChatMemberStateChange.VoiceDoneSpeaking: message = "Left voice chat: ";   break;              // Left Voice chat

            default:
                message = $"Error ({state}):";
                break;
            }

            // Check if applied to bot
            if (userID == kraxbot.SteamID)
            {
                kraxbot.SendKraxMessage($"Got {state} from {settings.ChatName}");
                lastChatroom = chatRoomID;
                chatrooms.Remove(chatRoomID);
            }

            // User entered chat
            if (state == EChatMemberStateChange.Entered)
            {
                var member = callback.StateChangeInfo.MemberInfo;

                if (user == default(UserInfo))
                {
                    // User doesn't exist, create
                    user = new UserInfo
                    {
                        Name       = GetPlayerName(userID),
                        SteamID    = userID,
                        Rank       = member.Details,
                        Permission = member.Permissions
                    };

                    settings.Users.Add(user);
                }
                else
                {
                    // User already exists in list, just update values
                    user.Name       = kraxbot.GetFriendPersonaName(userID);
                    user.Rank       = member.Details;
                    user.Permission = member.Permissions;
                }
            }
            else if (user == default(UserInfo))
            {
                Kraxbot.Log($"Warning: Unknown user {userID} in {settings.ChatName}, ignoring message");
                return;
            }

            // User left chat
            else if (state == EChatMemberStateChange.Left)
            {
                user.Disconnects = 0;
                user.LastLeave   = DateTime.Now;
            }

            // Fix for not counting Disconnects when DCKick is set to 'None'
            // When it's 2 it won't say anything anyway
            else if (state == EChatMemberStateChange.Disconnected && settings.DcKick == ESpamAction.None && user.Disconnects < 2)
            {
                user.Disconnects++;
            }

            // Check if we should auto kick/ban
            if (settings.AutoKick.Mode != ESpamAction.None && settings.AutoKick.User == userID)
            {
                switch (settings.AutoKick.Mode)
                {
                case ESpamAction.Ban:
                    kraxbot.BanUser(chatRoomID, userID);
                    kraxbot.SendKraxMessage($"Auto banned {userName} from {settings.ChatName}");
                    break;

                case ESpamAction.Kick:
                    kraxbot.KickUser(chatRoomID, userID);
                    kraxbot.SendKraxMessage($"Auto kicked {userName} from {settings.ChatName}");
                    break;

                    // TODO: Add warning
                }
            }

            // Say welcome message
            if (settings.Welcome)
            {
                if (state == EChatMemberStateChange.Entered)
                {
                    switch (user.Disconnects)
                    {
                    case 0:
                        kraxbot.SendChatRoomMessage(chatRoomID, $"{settings.WelcomeMsg} {userName}{settings.WelcomeEnd}");
                        break;

                    case 1:
                        kraxbot.SendChatRoomMessage(chatRoomID, $"Welcome back {userName}");
                        break;
                    }
                }
                else if (settings.AllStates && user.Disconnects == 0)
                {
                    kraxbot.SendChatRoomMessage(chatRoomID, $"{message} {userName}");
                }
            }

            // Kick or warn user if disconnected enough times
            if (settings.DcKick != ESpamAction.None)
            {
                // If user disconnected, add to counter
                if (state == EChatMemberStateChange.Disconnected)
                {
                    user.Disconnects++;
                }

                // Check disconnects and kick/warn
                // TODO: Make so you can set custom amount
                if (state == EChatMemberStateChange.Entered && user.Disconnects >= 5)
                {
                    kraxbot.SendChatRoomMessage(chatRoomID, $"{userName}, please fix your connection");

                    if (settings.DcKick == ESpamAction.Kick)
                    {
                        kraxbot.SendKraxMessage($"Kicked {userName} due to disconnecting in {settings.ChatName}");
                        kraxbot.KickUser(chatRoomID, userID);
                    }
                    else if (settings.DcKick == ESpamAction.Warn)
                    {
                        // TODO: This could probably just be a method
                        // TODO: We also set .Last in dashe3, why?
                        user.Warnings++;

                        if (user.Warnings == 1)
                        {
                            kraxbot.SendChatRoomMessage(chatRoomID, "This is your first warning");
                        }
                        else if (user.Warnings > 2)
                        {
                            kraxbot.SendChatRoomMessage(chatRoomID, rng.Next(10) == 0 ? "That's it >:c" : "Your own fault :/");
                            user.Warnings = 0;
                            kraxbot.KickUser(chatRoomID, userID);
                        }
                        else
                        {
                            kraxbot.SendChatRoomMessage(chatRoomID, $"You currently have {user.Warnings} warnings");
                        }
                    }

                    user.Disconnects = 0;
                }
            }

            // Log state message
            Kraxbot.Log($"[C] [{settings.ChatName}] {message} {userName}");

            /*
             * TODO
             * We used to have a bot check here in dashe3,
             * but since all those bots have died (xD),
             * I don't think we need the check anymore
             */

            // Check if inviter left
            if (userID == settings.InvitedID && settings.AutoLeave && state == EChatMemberStateChange.Left)
            {
                kraxbot.SendChatRoomMessage(chatRoomID, "Cya!");
                kraxbot.SendKraxMessage($"Left {settings.ChatName} because {userName} left the chat");
                kraxbot.LeaveChat(chatRoomID);
            }
        }
Пример #11
0
 private void OnLoggedOff(SteamUser.LoggedOffCallback loggedOffCallback)
 => Kraxbot.Log("Logged out");
Пример #12
0
 // When connected, login
 private void OnConnected(SteamClient.ConnectedCallback callback)
 {
     Kraxbot.Log("Connected");
     kraxbot.Login();
 }
Пример #13
0
 // When disconnected, attempt to reconnect
 private void OnDisconnected(SteamClient.DisconnectedCallback disconnectedCallback)
 {
     Kraxbot.Log("Disconnected, attemting to reconnect...");
     kraxbot.Connect();
 }