Пример #1
0
        public string AskServerAddress()
        {
            var cached = SettingsService.Read();

            if (!string.IsNullOrWhiteSpace(cached.ServerAddress))
            {
                return(cached.ServerAddress);
            }
            BotLogger.LogInfo("Welcome! Please enter the server address of Kahla.");
            BotLogger.LogWarning("\r\nEnter 1 for production\r\nEnter 2 for staging\r\nFor other server, enter like: https://server.kahla.app");
            var result = Console.ReadLine();

            if (result.Trim() == 1.ToString())
            {
                return("https://server.kahla.app");
            }
            else if (result.Trim() == 2.ToString())
            {
                return("https://staging.server.kahla.app");
            }
            else
            {
                return(result);
            }
        }
Пример #2
0
        public async Task <int?> CompleteRequest(int requestId, bool accept)
        {
            var text = accept ? "accepted" : "rejected";

            BotLogger.LogWarning($"Friend request with id '{requestId}' was {text}.");
            var createdConversationId = await FriendshipService.CompleteRequestAsync(requestId, accept);

            return(createdConversationId.Value);
        }
Пример #3
0
        public async Task Connect(Action <string> onGetWebsocket = null)
        {
            _botLogger.LogWarning("Establishing the connection to Kahla...");
            await ReleaseMonitorJob();

            var server = AskServerAddress();

            _settingsService["ServerAddress"] = server;
            try
            {
                await _kahlaLocation.UseKahlaServerAsync(server);
            }
            catch (Exception e)
            {
                _botLogger.LogDanger(e.Message);
                return;
            }
            if (!await SignedIn())
            {
                await OpenSignIn();

                var code = await AskCode();
                await SignIn(code);
            }
            else
            {
                _botLogger.LogSuccess("\nYou are already signed in! Welcome!");
            }
            await RefreshUserProfile();

            var websocketAddress = await GetWsAddress();

            // Trigger on request.
            var requests = (await _friendshipService.MyRequestsAsync())
                           .Items
                           .Where(t => !t.Completed);

            foreach (var request in requests)
            {
                await BuildBot.OnFriendRequest(new NewFriendRequestEvent
                {
                    Request = request
                });
            }
            // Trigger group connected.
            var friends = (await _friendshipService.MineAsync());

            foreach (var group in friends.Groups)
            {
                await BuildBot.OnGroupConnected(group);
            }
            onGetWebsocket?.Invoke(websocketAddress);
            await Task.WhenAll(_backgroundJobs.Select(t => t.StopAsync(CancellationToken.None)));

            await Task.WhenAll(_backgroundJobs.Select(t => t.StartAsync(CancellationToken.None)));
        }
Пример #4
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]);
        }
Пример #5
0
        private async Task InsertNewMessage(int conversationId, Message message, string previousMessageId)
        {
            var conversation = _contacts.SingleOrDefault(t => t.ConversationId == conversationId);

            if (conversation == null)
            {
                _botLogger.LogDanger($"Comming new message from unknown conversation: '{conversationId}' but we can't find it in memory.");
                return;
            }
            if (Guid.Parse(previousMessageId) != Guid.Empty)                               // On server, has previous message.)
            {
                if (conversation.LatestMessage.Id != Guid.Parse(previousMessageId) ||      // Local latest message is not latest.
                    conversation.Messages.All(t => t.Id != Guid.Parse(previousMessageId))) // Server side previous message do not exists locally.
                {
                    // Some message was lost.
                    _botLogger.LogWarning("Some message was lost. Trying to sync...");
                    var missedMessages = await _conversationService.GetMessagesAsync(conversationId, 15, message.Id.ToString());

                    foreach (var missedMessage in missedMessages.Items)
                    {
                        if (!conversation.Messages.Any(t => t.Id == missedMessage.Id))
                        {
                            conversation.Messages.Add(missedMessage);
                        }
                    }
                }
            }
            conversation.LatestMessage = message;
            conversation.Messages.Add(message);
        }
Пример #6
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]);
        }
Пример #7
0
        public async Task <bool> Execute(string command)
        {
            await _botHost.ReleaseMonitorJob();

            await _botHost.LogOff();

            _botLogger.LogWarning("Successfully log out. Use command:`reboot` to reconnect.");
            return(true);
        }
Пример #8
0
        private string AskServerAddress()
        {
            _botLogger.LogInfo("Welcome! Please enter the server address of Kahla.");
            _botLogger.LogWarning("\r\nEnter 1 for production\r\nEnter 2 for staging\r\nFor other server, enter like: https://server.kahla.app");
            var result = Console.ReadLine();

            if (result.Trim() == 1.ToString())
            {
                return("https://server.kahla.app");
            }
            else if (result.Trim() == 2.ToString())
            {
                return("https://staging.server.kahla.app");
            }
            else
            {
                return(result);
            }
        }
Пример #9
0
        public TranslateBot(
            BingTranslator bingTranslator,
            BotLogger botLogger)
        {
            _bingTranslator = bingTranslator;
            _botLogger      = botLogger;
            _botLogger.LogWarning("Please enter your bing API key:");
            var key = Console.ReadLine();

            _bingTranslator.Init(key);
        }
Пример #10
0
        public override Task OnBotInit()
        {
            var profilestring = JsonConvert.SerializeObject(Profile, Formatting.Indented);

            Console.WriteLine(profilestring);

            BotLogger.LogWarning("Please enter your bing API key:");
            var key = Console.ReadLine();

            _bingTranslator.Init(key);
            return(Task.CompletedTask);
        }
Пример #11
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);
        }
Пример #12
0
        public override Task OnBotStarting()
        {
            var key = SettingsService["BingTranslateAPIKey"] as string;

            if (string.IsNullOrWhiteSpace(key))
            {
                BotLogger.LogWarning("Please enter your bing API key:");
                key = Console.ReadLine();
            }
            _bingTranslator.Init(key);
            SettingsService["BingTranslateAPIKey"] = key;
            return(Task.CompletedTask);
        }
Пример #13
0
        public async Task <bool> Execute(string command)
        {
            await Task.Delay(0);

            foreach (var request in _eventSyncer.Requests)
            {
                _botLogger.LogInfo($"Name:\t{request.Creator.NickName}");
                _botLogger.LogInfo($"Time:\t{request.CreateTime}");
                if (request.Completed)
                {
                    _botLogger.LogSuccess("\tCompleted.");
                }
                else
                {
                    _botLogger.LogWarning("\tPending.");
                }
            }
            return(true);
        }