Exemple #1
0
        public async Task <Task> Start()
        {
            if (_bot == null)
            {
                _botLogger.LogDanger("You can't start bot listener without a bot!");
                return(Task.CompletedTask);
            }
            var server = AskServerAddress();

            _kahlaLocation.UseKahlaServer(server);
            if (!await TestKahlaLive())
            {
                return(Task.CompletedTask);
            }
            await OpenSignIn();

            var code = await AskCode();

            await SignIn(code);
            await DisplayMyProfile();

            var websocketAddress = await GetWSAddress();

            _botLogger.LogInfo($"Your account channel: {websocketAddress}");
            return(MonitorEvents(websocketAddress));
        }
Exemple #2
0
        public async Task <bool> TestKahlaLive()
        {
            try
            {
                BotLogger.LogInfo($"Using Kahla Server: {KahlaLocation}");
                BotLogger.LogInfo("Testing Kahla server connection...");
                var index = await HomeService.IndexAsync();

                BotLogger.LogSuccess("Success! Your bot is successfully connected with Kahla!\r\n");
                BotLogger.LogInfo($"Server time: \t\t{index.UTCTime}\tLocal time: \t\t{DateTime.UtcNow}");
                BotLogger.LogInfo($"Server version: \t{index.APIVersion}\t\t\tLocal version: \t{VersionService.GetSDKVersion()}");
                if (index.APIVersion != VersionService.GetSDKVersion())
                {
                    BotLogger.LogDanger("API version don't match! Kahla bot may crash! We strongly suggest checking the API version first!");
                }
                else
                {
                    BotLogger.LogSuccess("API version match!");
                }
                return(true);
            }
            catch (Exception e)
            {
                BotLogger.LogDanger(e.Message);
                return(false);
            }
        }
Exemple #3
0
        public async Task <bool> Execute(string command)
        {
            var conversations = await _conversationService.AllAsync();

            _botLogger.LogInfo("");
            foreach (var conversation in conversations.Items)
            {
                _botLogger.LogInfo($"ID: {conversation.ConversationId}\tName:\t{conversation.DisplayName}");
            }
            _botLogger.LogInfo("");
            var convId = _botLogger.ReadLine("Enter conversation ID you want to say:");
            var target = conversations.Items.FirstOrDefault(t => t.ConversationId.ToString() == convId);

            if (target == null)
            {
                _botLogger.LogDanger($"Can't find conversation with ID: {convId}");
                return(true);
            }
            var toSay = _botLogger.ReadLine($"Enter the message you want to send to '{target.DisplayName}':");

            if (string.IsNullOrWhiteSpace(toSay))
            {
                _botLogger.LogDanger("Can't send empty content.");
                return(true);
            }
            var encrypted = _aes.OpenSSLEncrypt(toSay, _eventSyncer.Contacts.FirstOrDefault(t => t.ConversationId == target.ConversationId)?.AesKey);
            await _conversationService.SendMessageAsync(encrypted, target.ConversationId);

            _botLogger.LogSuccess("Sent.");
            return(true);
        }
Exemple #4
0
        public async Task <bool> Execute(string command)
        {
            await Task.Delay(0);

            if (int.TryParse(command.Substring(4).Trim(), out int convId))
            {
                var conversation = _eventSyncer.Contacts.FirstOrDefault(t => t.ConversationId == convId);
                if (conversation == null)
                {
                    _botLogger.LogDanger($"Conversation with Id '{convId}' was not found!");
                    return(true);
                }
                foreach (var message in conversation.Messages)
                {
                    if (!message.GroupWithPrevious)
                    {
                        _botLogger.LogInfo($"{message.Sender.NickName} says: \t {_aes.OpenSSLDecrypt(message.Content, conversation.AesKey)}");
                    }
                    else
                    {
                        _botLogger.LogInfo($"\t\t\t {_aes.OpenSSLDecrypt(message.Content, conversation.AesKey)}");
                    }
                }
                return(true);
            }
            foreach (var conversation in _eventSyncer.Contacts)
            {
                var online = conversation.Online == true ? "online" :
                             conversation.Online == false ? "offline" : string.Empty;
                _botLogger.LogInfo($"Name:\t{conversation.DisplayName}");
                _botLogger.LogInfo($"ID:\t{conversation.ConversationId}\t{online}\t\t{conversation.Discriminator}");
                if (!string.IsNullOrWhiteSpace(conversation.LatestMessage?.Content))
                {
                    _botLogger.LogInfo($"Last:\t{_aes.OpenSSLDecrypt(conversation.LatestMessage.Content, conversation.AesKey)}");
                    _botLogger.LogInfo($"Time:\t{conversation.LatestMessage.SendTime}");
                }
                if (conversation.UnReadAmount > 0)
                {
                    _botLogger.LogDanger($"Unread:\t**{conversation.UnReadAmount}**");
                }
                if (conversation.SomeoneAtMe)
                {
                    _botLogger.LogWarning("At!");
                }
                if (conversation.Messages.Count > 0)
                {
                    _botLogger.LogVerbose($"Local Messages:\t**{conversation.Messages.Count}**");
                }
                _botLogger.LogInfo("\n");
            }
            return(true);
        }
Exemple #5
0
        public BotBase SelectBot()
        {
            var builtBots = _bots.ToList();

            if (!int.TryParse(_settingsService["BotCoreIndex"]?.ToString(), out int code))
            {
                _botLogger.LogWarning("Select your bot:\n");
                for (int i = 0; i < builtBots.Count; i++)
                {
                    _botLogger.LogInfo($"\t{i} {builtBots[i].GetType().Name}");
                }
                while (true)
                {
                    _botLogger.LogInfo("Select bot:");
                    var codeString = Console.ReadLine()?.Trim();
                    if (!int.TryParse(codeString, out code) || code >= builtBots.Count)
                    {
                        _botLogger.LogDanger("Invalid item!");
                        continue;
                    }
                    break;
                }
            }
            _settingsService["BotCoreIndex"] = code;
            return(builtBots[code]);
        }
Exemple #6
0
        private async Task CommandLoop()
        {
            var commanding = true;

            while (commanding)
            {
                _botLogger.WriteGrayNewLine("K:\\Bots\\>");
                var command = Console.ReadLine();
                if (command == null)
                {
                    continue;
                }
                if (command.Length < 1)
                {
                    continue;
                }

                var handler = _commandFactory.ProduceHandler(command);
                if (handler == null)
                {
                    _botLogger.LogDanger($"Unknown command: {command}. Please try command: 'help' for help.");
                    continue;
                }
                commanding = await handler.Execute(command);
            }
        }
Exemple #7
0
        public static BotBase SelectBot(
            IEnumerable <BotBase> bots,
            SettingsService settingsService,
            BotLogger botLogger)
        {
            var builtBots = bots.ToList();
            int code      = settingsService.Read().BotCoreIndex;

            if (code < 0)
            {
                botLogger.LogWarning("Select your bot:\n");
                for (int i = 0; i < builtBots.Count; i++)
                {
                    botLogger.LogInfo($"\t{i.ToString()} {builtBots[i].GetType().Name}");
                }
                while (true)
                {
                    botLogger.LogInfo($"Select bot:");
                    var codeString = Console.ReadLine().Trim();
                    if (!int.TryParse(codeString, out code) || code >= builtBots.Count)
                    {
                        botLogger.LogDanger($"Invalid item!");
                        continue;
                    }
                    break;
                }
                settingsService.Save(code);
            }
            return(builtBots[code]);
        }
Exemple #8
0
        public async Task Command()
        {
            await Task.Delay(0);

            while (true)
            {
                var command = Console.ReadLine();
                if (command.Length < 1)
                {
                    continue;
                }
                switch (command.ToLower().Trim()[0])
                {
                case 'q':
                    Environment.Exit(0);
                    return;

                case 'h':
                    _botLogger.LogInfo($"Kahla bot commands:");

                    _botLogger.LogInfo($"\r\nConversation");
                    _botLogger.LogInfo($"\ta\tShow all conversations.");
                    _botLogger.LogInfo($"\ts\tSay something to someone.");
                    _botLogger.LogInfo($"\tb\tBroadcast to all conversations.");

                    _botLogger.LogInfo($"\r\nGroup");
                    _botLogger.LogInfo($"\tm\tMute all groups.");
                    _botLogger.LogInfo($"\tu\tUnmute all groups.");

                    _botLogger.LogInfo($"\r\nNetwork");
                    _botLogger.LogInfo($"\tr\tReconnect to Stargate.");
                    _botLogger.LogInfo($"\tl\tLogout.");

                    _botLogger.LogInfo($"\r\nProgram");
                    _botLogger.LogInfo($"\th\tShow help.");
                    _botLogger.LogInfo($"\tq\tQuit bot.");
                    break;

                default:
                    _botLogger.LogDanger($"Unknown command: {command}. Please try command: 'h' for help.");
                    break;
                }
            }
        }
Exemple #9
0
        public async Task Run(bool enableCommander = true, int autoReconnectMax = int.MaxValue)
        {
            int reconnectAttempts = 0;
            await BuildBot.OnBotStarting();

            ConnectTask = Connect((websocketAddress) =>
            {
                MonitorTask = MonitorEvents(websocketAddress);
                if (enableCommander)
                {
                    CommandTask = _botCommander.Command();
                }
            });
            while (
                !CommandTask.IsCompleted ||
                !MonitorTask.IsCompleted ||
                !ConnectTask.IsCompleted)
            {
                if (reconnectAttempts < autoReconnectMax &&
                    MonitorTask.IsCompleted &&
                    ConnectTask.IsCompleted)
                {
                    if (await SignedIn())
                    {
                        reconnectAttempts++;
                        _botLogger.LogSuccess($"\nTrying to auto reconect! Attempts: {reconnectAttempts}");
                        ConnectTask = Connect((websocketAddress) =>
                        {
                            MonitorTask = MonitorEvents(websocketAddress);
                        });
                    }
                    else
                    {
                        _botLogger.LogDanger("Cannot start reconnecting. Because checking sign in status failed.");
                    }
                }
                await Task.Delay(5000);
            }
        }
Exemple #10
0
        public async void OnStargateMessage(ResponseMessage msg)
        {
            var inevent = JsonConvert.DeserializeObject <KahlaEvent>(msg.ToString());

            switch (inevent.Type)
            {
            case EventType.NewMessage:
                var newMessageEvent = JsonConvert.DeserializeObject <NewMessageEvent>(msg.ToString());
                await InsertNewMessage(
                    newMessageEvent.ConversationId,
                    newMessageEvent.Message,
                    newMessageEvent.PreviousMessageId);
                await OnNewMessageEvent(newMessageEvent);

                break;

            case EventType.NewFriendRequestEvent:
                var newFriendRequestEvent = JsonConvert.DeserializeObject <NewFriendRequestEvent>(msg.ToString());
                PatchFriendRequest(newFriendRequestEvent.Request);
                await BuildBot.OnFriendRequest(newFriendRequestEvent);

                break;

            case EventType.FriendsChangedEvent:
                var friendsChangedEvent = JsonConvert.DeserializeObject <FriendsChangedEvent>(msg.ToString());
                PatchFriendRequest(friendsChangedEvent.Request);
                if (friendsChangedEvent.Result)
                {
                    SyncFriendRequestToContacts(friendsChangedEvent.Request, friendsChangedEvent.CreatedConversation);
                }
                await BuildBot.OnFriendsChangedEvent(friendsChangedEvent);

                break;

            case EventType.FriendDeletedEvent:
                var friendDeletedEvent = JsonConvert.DeserializeObject <FriendDeletedEvent>(msg.ToString());
                DeleteConversationIfExist(friendDeletedEvent.ConversationId);
                await BuildBot.OnWasDeleted(friendDeletedEvent);

                break;

            case EventType.DissolveEvent:
                var dissolveEvent = JsonConvert.DeserializeObject <DissolveEvent>(msg.ToString());
                DeleteConversationIfExist(dissolveEvent.ConversationId);
                await BuildBot.OnGroupDissolve(dissolveEvent);

                break;

            case EventType.SomeoneLeftEvent:
                var someoneLeftEvent = JsonConvert.DeserializeObject <SomeoneLeftEvent>(msg.ToString());
                if (someoneLeftEvent.LeftUser.Id == BuildBot.Profile.Id)
                {
                    // you was kicked
                    DeleteConversationIfExist(someoneLeftEvent.ConversationId);
                }
                else
                {
                    // Some other one, not me, was deleted in a conversation.
                }
                break;

            case EventType.GroupJoinedEvent:
                var groupJoinedEvent = JsonConvert.DeserializeObject <GroupJoinedEvent>(msg.ToString());
                SyncGroupToContacts(groupJoinedEvent.CreatedConversation, groupJoinedEvent.MessageCount, groupJoinedEvent.LatestMessage);
                await BuildBot.OnGroupConnected(new SearchedGroup(groupJoinedEvent.CreatedConversation));

                break;

            default:
                _botLogger.LogDanger($"Unhandled server event: {inevent.TypeDescription}!");
                break;
            }
            await BuildBot.OnMemoryChanged();
        }