Exemplo n.º 1
0
        static void Main(string[] args)
        {
            AIMLbot.Bot  chatBot;
            AIMLbot.User chatUser;
            string       channel = args[0];
            string       rnick   = args[1];
            string       rmsg    = args[2];

            try
            {
                if (rmsg.StartsWith("!") == false)
                {
                    string query = rmsg;
                    ObsidianFunctions.Functions ObsidFunc = new ObsidianFunctions.Functions();
                    chatBot = new AIMLbot.Bot();
                    chatBot.loadSettings();
                    chatUser = new AIMLbot.User(rnick, chatBot);
                    chatBot.loadAIMLFromFiles();
                    chatBot.isAcceptingUserInput = true;
                    AIMLbot.Request r   = new AIMLbot.Request(query, chatUser, chatBot);
                    AIMLbot.Result  res = chatBot.Chat(r);
                    Console.WriteLine("PRIVMSG " + rnick + " :" + res.Output);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("PRIVMSG " + rnick + " :" + ex.ToString());
            }
        }
Exemplo n.º 2
0
        public override void OnInvoke(object sender, System.EventArgs e, object target)
        {
            ListViewItem ali      = target as ListViewItem;
            string       username = null;
            UUID         uuid     = UUID.Zero;

            if (ali != null)
            {
                uuid     = (UUID)ali.Tag;
                username = instance.Names.Get(uuid);
            }
            else
            {
                FriendInfo fi = target as FriendInfo;
                uuid     = fi.UUID;
                username = instance.Names.Get(uuid);
            }
            if (username == null)
            {
                instance.TabConsole.DisplayNotificationInChat("I dont know how to DeRef " + target + " bieng a  " +
                                                              target.GetType());
                return;
            }
            string outp = username + ", " + aimlBot.Chat("INTERJECTION", username).Output;

            if (outp.Length > 1000)
            {
                outp = outp.Substring(0, 1000);
            }

            Client.Self.Chat(outp, 0, ChatType.Normal);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            _bot = InstantiateBot();
            _user = new User("chris", _bot);
            var input = string.Empty;
            Console.WriteLine("Say somthing to begin teaching me.");
            while (input.ToLower() != "q")
            {
                input = GetUserInput();
                if (input.StartsWith("/"))
                {
                    if (input.StartsWith("/bot"))
                        ProcessBotCommand(input);
                    if (input == "/save")
                    {
                        SaveBot();
                        continue;
                    }
                }

                var request = new Request(input, _user, _bot);
                var response = _bot.Chat(request);
                TellUser(response);

            }
        }
Exemplo n.º 4
0
 static void Main(string[] args)
 {
     AIMLbot.Bot chatBot;
     AIMLbot.User chatUser;
     string channel = args[0];
     string rnick = args[1];
     string rmsg = args[2];
     try
     {
     if (rmsg.StartsWith("!") == false)
     {
     string query = rmsg;
     ObsidianFunctions.Functions ObsidFunc = new ObsidianFunctions.Functions();
     chatBot = new AIMLbot.Bot();
     chatBot.loadSettings();
     chatUser = new AIMLbot.User(rnick, chatBot);
     chatBot.loadAIMLFromFiles();
     chatBot.isAcceptingUserInput = true;
     AIMLbot.Request r = new AIMLbot.Request(query, chatUser, chatBot);
     AIMLbot.Result res = chatBot.Chat(r);
     Console.WriteLine("PRIVMSG " + rnick + " :" + res.Output);
     }
     }
     catch (Exception ex)
     {
     Console.WriteLine("PRIVMSG " + rnick + " :" + ex.ToString());
     }
 }
    /*
     * void OnGUI () {
     *      // Enable Word warp
     *      GUI.skin.label.wordWrap = true;
     *      // Make a background box
     *      GUI.Box(new Rect(10,10,300,150), "Chat with a Chatbot");
     *      // Make output label
     *      GUI.Label (new Rect (20, 30, 280, 40), Output_Text);
     *      // Make a text field that modifies Input_Text.
     *      Input_Text = GUI.TextField (new Rect (20, 100, 280, 20), Input_Text, 100);
     *      // If send button or enter pressed
     *      if(((Event.current.keyCode == KeyCode.Return)||GUI.Button(new Rect(250,130,50,20),"Send")) && (Input_Text != "")) {
     *              // Prepare Variables
     *              // You don't need to care, wether Only Jurassics or only Program #'s Variables
     *              // are changed. This is managed immediate intern every time you change a global
     *              // variable in Program # or Jurassic.
     *              // bot.jscript_engine.SetGlobalValue("abc",15);
     *
     *              request.rawInput = Input_Text;
     *              request.StartedOn = DateTime.Now;
     *              result = bot.Chat(request);
     *              Output_Text = result.Output;
     *              Input_Text = "";
     *
     *              // Gather Variables
     *              // bot.jscript_engine.GetGlobalValue<string>("abc");
     *      }
     * }*/

    public string GetAnswer(string input)
    {
        request.rawInput  = input;
        request.StartedOn = DateTime.Now;
        result            = bot.Chat(request);
        return(result.Output);
    }
Exemplo n.º 6
0
    void OnGUI()
    {
        // Enable Word warp
        GUI.skin.label.wordWrap = true;
        // Make a background box
        GUI.Box(new Rect(10, 10, 300, 500), "Chat with a Chatbot");
        // Make output label
        GUI.Label(new Rect(20, 30, 280, 40), Output_Text);
        // Make a text field that modifies Input_Text.
        Input_Text = GUI.TextField(new Rect(20, 100, 280, 20), Input_Text, 100);
        // If send button or enter pressed
        if (((Event.current.keyCode == KeyCode.Return) || GUI.Button(new Rect(250, 130, 50, 20), "Send")) && (Input_Text != ""))
        {
            // Prepare Variables
            // You don't need to care, wether Only Jurassics or only Program #'s Variables
            // are changed. This is managed immediate intern every time you change a global
            // variable in Program # or Jurassic.
            // bot.jscript_engine.SetGlobalValue("abc",15);

            request.rawInput  = Input_Text;
            request.StartedOn = DateTime.Now;
            result            = bot.Chat(request);
            Output_Text       = result.Output;
            Input_Text        = "";

            // Gather Variables
            // bot.jscript_engine.GetGlobalValue<string>("abc");
        }
    }
Exemplo n.º 7
0
        public string GetResp(string msg, string user)
        {
            try
            {
                myUser = null;
                //GC.Collect();

                myUser = new AIMLbot.User(user, myBot);

                AIMLbot.Request myRequest = new AIMLbot.Request(msg, myUser, myBot);
                AIMLbot.Result  myResult  = myBot.Chat(myRequest);

                string reply = myResult.Output;

                if (reply.Length > 5)
                {
                    if (reply.Substring(0, 5).ToLower(CultureInfo.CurrentCulture) == "error")
                    {
                        return(string.Empty);
                    }

                    return(reply);
                }

                return(reply);
            }
            catch (Exception ex)
            {
                Logger.Log("There has been an error starting AI.", Helpers.LogLevel.Warning, ex);
                return(string.Empty);
            }
        }
Exemplo n.º 8
0
        static void Main(string[] args)
        {
            string settingsPath = Path.Combine(Environment.CurrentDirectory, Path.Combine("config", "Settings.xml"));

            Bot myBot = new Bot();
            myBot.loadSettings(settingsPath);
            User myUser = new User("consoleUser", myBot);
            myBot.isAcceptingUserInput = false;
            myBot.loadAIMLFromFiles();
            myBot.isAcceptingUserInput = true;
            while (true)
            {
                Console.Write("You: ");
                string input = Console.ReadLine();
                if (input.ToLower() == "quit")
                {
                    break;
                }
                else
                {
                    Request r = new Request(input, myUser, myBot);
                    Result res = myBot.Chat(r);
                    Console.WriteLine("Bot: " + res.Output);
                }
            }
        }
Exemplo n.º 9
0
    // Start is called before the first frame update
    // Update is called once per frame
    void OnGUI()
    {
        //Input_Text = CommText.text.ToString();
        // Enable Word warp
        //GUI.skin.label.wordWrap = true;
        // Make a background box
        //GUI.Box(new Rect(10, 10, 300, 500), "Chat with a Chatbot");
        // Make output label
        //GUI.Label(new Rect(20, 30, 280, 40), Output_Text);
        // Make a text field that modifies Input_Text.
        if (Event.current.keyCode == KeyCode.Return)
        {
            // Prepare Variables
            // You don't need to care, wether Only Jurassics or only Program #'s Variables
            // are changed. This is managed immediate intern every time you change a global
            // variable in Program # or Jurassic.
            // bot.jscript_engine.SetGlobalValue("abc",15);

            request.rawInput  = CommText.text.ToString();
            request.StartedOn = DateTime.Now;
            result            = bot.Chat(request);
            ResponseText.text = result.Output;
            Input_Text        = "";
            CommText.text     = "";

            // Gather Variables
            // bot.jscript_engine.GetGlobalValue<string>("abc");
        }
    }
Exemplo n.º 10
0
        private static async void BotOnMessage(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            Bot.Types.Message msg = e.Message;

            if (msg == null)
            {
                return;
            }

            if (msg.Type == Bot.Types.Enums.MessageType.TextMessage)
            {
                AIMLbot.Bot AI = new AIMLbot.Bot();

                AI.loadSettings(); // This loads the settings from the config folder

                AI.loadAIMLFromFiles();

                AIMLbot.User me_aiml = new AIMLbot.User("dd", AI);

                Request r   = new Request(msg.Text, me_aiml, AI);
                Result  res = AI.Chat(r);
                string  s   = res.ToString();
                await bot.SendTextMessageAsync(msg.Chat.Id, s);
            }

            //if (msg.Type == Bot.Types.Enums.MessageType.TextMessage)
            //{
            //    //await bot.SendTextMessageAsync(msg.Chat.Id, "Здарова " + msg.From.FirstName
            //}
        }
Exemplo n.º 11
0
        public void Test()
        {
            var bot = new Bot();

            var user = new User("me", bot);
            var request = new Request("test", user, bot);
            var result = bot.Chat(request);
        }
Exemplo n.º 12
0
 public void chatbotanswer()
 {
     request.rawInput  = _questiontext.text;
     request.StartedOn = DateTime.Now;
     result            = bot.Chat(request);
     _answer.text      = result.Output;
     //  TextToSpeechMark ttsm = gameObject.GetComponent<TextToSpeechMark>();
     // ttsm.Synthesize(_answer.text);
 }
Exemplo n.º 13
0
        public string Ask(string name, string question)
        {
            var sharpBot = new Bot();
            sharpBot.loadSettings(SettingsPath);
            var loader = new AIMLbot.Utils.AIMLLoader(sharpBot);
            loader.loadAIML(aimlPath);
            sharpBot.isAcceptingUserInput = false;
            sharpBot.isAcceptingUserInput = true;

            var patient = new User(name, sharpBot);
            var request = new Request(question, patient, sharpBot);
            var answer = sharpBot.Chat(request);
            return answer.Output;
        }
Exemplo n.º 14
0
        static void getOutput(String input)
        {
            Bot myBot = new Bot();
            User myUser = new User("consoleUser", myBot);

                 myBot.loadSettings();
             myBot.isAcceptingUserInput = false;
             myBot.loadAIMLFromFiles();
             myBot.isAcceptingUserInput = true;

             Request r = new Request(input, myUser, myBot);
             Result res = myBot.Chat(r);
             Console.WriteLine("Bot: " + res.Output);
        }
Exemplo n.º 15
0
 static void Main(string[] args)
 {
     Bot myBot = new Bot();
     myBot.loadSettings();
     User myUser = new User("consoleUser", myBot);
     myBot.isAcceptingUserInput = false;
     myBot.loadAIMLFromFiles();
     myBot.isAcceptingUserInput = true;
     while (true)
     {
         Console.Write("You: ");
         string input = Console.ReadLine();
         if (input.ToLower() == "quit")
         {
             break;
         }
         else
         {
             Request r = new Request(input, myUser, myBot);
             Result res = myBot.Chat(r);
             Console.WriteLine("Bot: " + res.Output);
         }
     }
 }
Exemplo n.º 16
0
        async void do_work(object sender, DoWorkEventArgs e)
        {
            var worker = sender as BackgroundWorker;
            var key    = e.Argument as String;

            try
            {
                var bot = new Telegram.Bot.TelegramBotClient(key);
                await bot.SetWebhookAsync("");

                AIMLbot.Bot lazy = new AIMLbot.Bot();


                lazy.loadSettings();
                lazy.loadAIMLFromFiles();
                lazy.isAcceptingUserInput = false;
                AIMLbot.User us = new AIMLbot.User("Username", lazy);
                lazy.isAcceptingUserInput = true;


                bot.OnCallbackQuery += async(object sc, Telegram.Bot.Args.CallbackQueryEventArgs ev) =>
                {
                    Telegram.Bot.Types.FileToSend s;
                    var message = ev.CallbackQuery.Message;
                    if (ev.CallbackQuery.Data == "callback1")
                    {
                        s = new Telegram.Bot.Types.FileToSend("https://i.pinimg.com/originals/f7/e9/80/f7e980c9700c8395535b835e66f02a59.jpg");
                    }
                    else if (ev.CallbackQuery.Data == "callback2")
                    {
                        s = new Telegram.Bot.Types.FileToSend("https://static.independent.co.uk/s3fs-public/thumbnails/image/2012/02/29/22/pg-28-sloth-cooke.jpg");
                    }
                    await bot.SendPhotoAsync(message.Chat.Id, s, "Sure! But... not today :)");

                    await bot.AnswerCallbackQueryAsync(ev.CallbackQuery.Id);
                };

                bot.OnUpdate += async(object su, Telegram.Bot.Args.UpdateEventArgs evu) =>
                {
                    if (evu.Update.CallbackQuery != null || evu.Update.InlineQuery != null)
                    {
                        return;
                    }
                    var update  = evu.Update;
                    var message = update.Message;
                    if (message == null)
                    {
                        return;
                    }
                    if (message.Type == Telegram.Bot.Types.Enums.MessageType.TextMessage)
                    {
                        if (message.Text[0] == '/')
                        {
                            if (message.Text == "/test")
                            {
                                await bot.SendTextMessageAsync(message.Chat.Id, "Yeah...",
                                                               replyToMessageId : message.MessageId);
                            }

                            if (message.Text == "/sleep")
                            {
                                var s = new Telegram.Bot.Types.FileToSend("https://beano-uploads-production.imgix.net/store/f4046f22dffe92e3f2167accb6942f788159d0f979f970dcda59f1d0e529?auto=compress&w=752&h=423&fit=min");
                                await bot.SendPhotoAsync(message.Chat.Id,
                                                         s, "Yeeeeeeeeeah, sleeeeeeeeep!");
                            }

                            if (message.Text == "/song")
                            {
                                var s = new Telegram.Bot.Types.FileToSend("http://store.naitimp3.ru/download/0/cGR1a0tRTWJwZW8wMlI2aitkT1UzVkxNdXE2dUNiRTAvcGRkeGphMTVFVTdQcGFURWlFOFQyUGZFTXJ6UVo4cWxVSUNza2NOQUpoZkJOU2ozYTJhWUpLSVdiUTRTanQrVmZnN1hQV1U5Tkk9/eels_i_need_some_sleep_(NaitiMP3.ru).mp3");
                                await bot.SendAudioAsync(message.Chat.Id, s, "", 4, "Eels", "I need some sleep...");
                            }

                            if (message.Text == "/work")
                            {
                                var keyboard = new Telegram.Bot.Types.ReplyMarkups.InlineKeyboardMarkup(
                                    new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardButton[][]
                                {
                                    // First row
                                    new [] {
                                        // First column
                                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Work", "callback1"),

                                        // Second column
                                        new Telegram.Bot.Types.InlineKeyboardButtons.InlineKeyboardCallbackButton("Work harder", "callback2")
                                    },
                                }
                                    );

                                await bot.SendTextMessageAsync(message.Chat.Id, "Hmmmm... What should I do?..!", Telegram.Bot.Types.Enums.ParseMode.Default, false, false, 0, keyboard);
                            }
                        }
                        else if ((message.Text[0] >= 'а' && message.Text[0] <= 'я') || (message.Text[0] >= 'А' && message.Text[0] <= 'Я'))
                        {
                            await bot.SendTextMessageAsync(message.Chat.Id, "I'm too lazy to learn russian, sorry...",
                                                           replyToMessageId : message.MessageId);
                        }
                        else
                        {
                            AIMLbot.Request r   = new AIMLbot.Request(message.Text, us, lazy);
                            AIMLbot.Result  res = lazy.Chat(r);

                            await bot.SendTextMessageAsync(message.Chat.Id, res.Output,
                                                           replyToMessageId : message.MessageId);
                        }
                    }
                };

                bot.StartReceiving();
            }
            catch (Telegram.Bot.Exceptions.ApiRequestException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            
            var myBot = new Bot();
            myBot.loadSettings();
            var myUser = new User("consoleUser", myBot);
            myBot.IsAcceptingUserInput = false;
            myBot.LoadAimlFromFiles();
            myBot.IsAcceptingUserInput = true;
            var synth = new SpeechSynthesizer();
            var commandProcessorFactory = new Mock<ICommandProcessorFactory>();
            var innerprocessor = new Mock<ICommandProcessor>();
            
            commandProcessorFactory.Setup(x => x.GetCommandProcessor(It.IsAny<CommandRequest>())).Returns(innerprocessor.Object);
            var processor = new CommandProcessor(commandProcessorFactory.Object, myUser, myBot);
            var results = new[]
            {
                new CommandResult
                {
                    ResultType = CommandResultTypeEnum.Text,
                    Content = "Hello Dude",
                    Pause = 1000
                    
                },
                new CommandResult
                {
                    ResultType = CommandResultTypeEnum.Text,
                    Content = "How are you?"

                },

            };
            var resultQueue = new Queue<CommandResult>(results);
            
            var result = resultQueue.Dequeue();

            while (result != null)
            {
                var sayText = string.Empty;
                switch (result.ResultType)
                {
                    case CommandResultTypeEnum.Text:
                        sayText = result.Content;
                        break;
                    case CommandResultTypeEnum.Bot:
                        var r = new Request(result.Content, myUser, myBot);
                        var res = myBot.Chat(r);
                        sayText = res.Output;
                        break;
                }
                if (!string.IsNullOrEmpty(sayText))
                {
                    Console.WriteLine(sayText);
                    synth.Speak(sayText);
                }
                if (result.WaitInput)
                {
                    var line = Console.ReadLine();
                }
                else if (result.Pause > 0)
                    Thread.Sleep(result.Pause);
                if (resultQueue.Count == 0)
                    break;
                result = resultQueue.Dequeue();
            }
            Console.ReadLine();
        }
Exemplo n.º 18
0
 public string AIMLWhatTypeIs(string FieldName, Bot ChatBot, User ChatUser)
 {
     Request chatRequest = new Request(string.Format("SQLBOT WHAT TYPE IS {0}", FieldName), ChatUser, ChatBot);
     Result chatRes = ChatBot.Chat(chatRequest);
     return FieldName = TrimWord(chatRes.Output);
 }
Exemplo n.º 19
0
        void Self_ChatFromSimulator(object sender, ChatEventArgs e)
        {
            // We ignore everything except normal chat from other avatars
            if (!Enabled || e.SourceType != ChatSourceType.Agent || e.FromName == Client.Self.Name || e.Message.Trim().Length == 0)
            {
                return;
            }

            bool parseForResponse = Alice != null && Alice.isAcceptingUserInput && Enabled;

            if (parseForResponse && respondRange >= 0)
            {
                parseForResponse = Vector3.Distance(Client.Self.SimPosition, e.Position) <= respondRange;
            }
            if (parseForResponse)
            {
                parseForResponse = respondWithoutName || e.Message.ToLower().Contains(FirstName(Client.Self.Name).ToLower());
            }


            if (parseForResponse)
            {
                WorkPool.QueueUserWorkItem(sync =>
                {
                    lock (syncChat)
                    {
                        Alice.GlobalSettings.updateSetting("location", "region " + Client.Network.CurrentSim.Name);
                        string msg = e.Message.ToLower();
                        msg        = msg.Replace(FirstName(Client.Self.Name).ToLower(), "");
                        AIMLbot.User user;
                        if (AliceUsers.ContainsKey(e.FromName))
                        {
                            user = (AIMLbot.User)AliceUsers[e.FromName];
                        }
                        else
                        {
                            user = new User(e.FromName, Alice);
                            user.Predicates.removeSetting("name");
                            user.Predicates.addSetting("name", FirstName(e.FromName));
                            AliceUsers[e.FromName] = user;
                        }

                        Client.Self.Movement.TurnToward(e.Position);
                        if (EnableRandomDelay)
                        {
                            System.Threading.Thread.Sleep(1000 + 1000 * rand.Next(2));
                        }
                        if (!Instance.State.IsTyping)
                        {
                            Instance.State.SetTyping(true);
                        }
                        if (EnableRandomDelay)
                        {
                            System.Threading.Thread.Sleep(2000 + 1000 * rand.Next(5));
                        }
                        else
                        {
                            System.Threading.Thread.Sleep(1000);
                        }
                        Instance.State.SetTyping(false);
                        AIMLbot.Request req = new Request(msg, user, Alice);
                        AIMLbot.Result res  = Alice.Chat(req);
                        string outp         = res.Output;
                        if (outp.Length > 1000)
                        {
                            outp = outp.Substring(0, 1000);
                        }

                        ChatType useChatType = ChatType.Normal;
                        if (shout2shout && e.Type == ChatType.Shout)
                        {
                            useChatType = ChatType.Shout;
                        }
                        else if (whisper2whisper && e.Type == ChatType.Whisper)
                        {
                            useChatType = ChatType.Whisper;
                        }
                        Client.Self.Chat(outp, 0, useChatType);
                    }
                });
            }
        }
Exemplo n.º 20
0
        public bool IsMonth(string FieldName, Bot ChatBot, User ChatUser)
        {
            bool res = false;
            try
            {
                Request chatRequest = new Request(string.Format("SQLBOT WHAT MONTH IS {0}", FieldName), ChatUser, ChatBot);
                Result chatRes = ChatBot.Chat(chatRequest);
                string chatOutput = TrimWord(chatRes.Output);
                int numberValue;

                if (chatOutput != "UNKNOWN" && int.TryParse(chatOutput, out numberValue))
                {
                    this.Number = numberValue;
                    res = true;
                }
            }
            catch(Exception)
            {
                res = false;
            }
            return res;
        }
Exemplo n.º 21
0
        public bool IsNumber(string FieldName, Bot ChatBot, User ChatUser)
        {
            double numberValue;

            if (double.TryParse(FieldName, out numberValue))
            {
                this.Number = numberValue;
                this.CharBeforeNumber = ECharBeforeNumber.Add;
                return true;
            }
            else
            {
                Request chatRequest = new Request(string.Format("SQLBOT WHAT NUMBER IS {0}", FieldName), ChatUser, ChatBot);
                Result chatRes = ChatBot.Chat(chatRequest);
                string chatOutput = TrimWord(chatRes.Output);

                if (chatOutput != "UNKNOWN" && double.TryParse(chatOutput, out numberValue))
                {
                    this.Number = numberValue;

                    chatRequest = new Request(string.Format("SQLBOT WHAT PRECEDES NUMBER {0}", FieldName), ChatUser, ChatBot);
                    chatRes = ChatBot.Chat(chatRequest);
                    chatOutput = TrimWord(chatRes.Output);

                    switch (chatOutput)
                    {
                        case "ADD":
                            this.CharBeforeNumber = ECharBeforeNumber.Add;
                            break;
                        case "MULTIPLY":
                            this.CharBeforeNumber = ECharBeforeNumber.Multiply;
                            break;
                        case "DIVIDE":
                            this.CharBeforeNumber = ECharBeforeNumber.Divide;
                            break;
                        default:
                            this.CharBeforeNumber = ECharBeforeNumber.Unknown;
                            break;
                    };

                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
Exemplo n.º 22
0
        async void launchWorkerAsync(object sender, DoWorkEventArgs e)
        {
            BackgroundWorker worker = sender as BackgroundWorker;
            string           key    = e.Argument as String;

            try
            {
                Bot = new Telegram.Bot.TelegramBotClient(key);
                await Bot.SetWebhookAsync("");

                int offset = 0;
                while (true)
                {
                    var messages = await Bot.GetUpdatesAsync(offset);

                    foreach (var message in messages)
                    {
                        var  msgText = message.Message;
                        User currentUser;
                        if (users.ContainsKey(msgText.Chat.Id))
                        {
                            currentUser = users[msgText.Chat.Id];
                        }
                        else
                        {
                            currentUser = new User("Уважаемый", bot);

                            currentUser.Predicates.addSetting("favouriteanimal", "default");
                            currentUser.Predicates.addSetting("name", "default");

                            users[msgText.Chat.Id] = currentUser;
                        }

                        if (msgText.Type == Telegram.Bot.Types.Enums.MessageType.Text && msgText.Text.Contains("/game"))
                        {
                            string text = msgText.Text;
                            text = text.Replace("/game ", "");
                            string[] clues = text.Split(',');
                            clues = clues.Select(x => x.Trim().ToLower()).ToArray();
                            List <string> games = Program.SetupFacts(clues.ToList(), "");
                            if (games.Count == 0)
                            {
                                await Bot.SendTextMessageAsync(msgText.Chat.Id, "Не знаю таких игра :(");
                            }
                            else
                            {
                                string res = games.Aggregate((i, j) => i + '?' + j);
                                res += '?';
                                await Bot.SendTextMessageAsync(msgText.Chat.Id, "Я что-то такое знаю. " + res);
                            }
                        }
                        else if (msgText.Type == Telegram.Bot.Types.Enums.MessageType.Text)
                        {
                            Console.WriteLine(msgText.Text.ToUpper());
                            Request r   = new Request(msgText.Text, currentUser, bot);
                            Result  res = bot.Chat(r);
                            if (res.Output != "")
                            {
                                if (res.Output.EndsWith(".jpg."))
                                {
                                    await Bot.SendPhotoAsync(msgText.Chat.Id, res.Output.Remove(res.Output.Count() - 1, 1));
                                }
                                else if (res.Output == "time.")
                                {
                                    var time = "У меня " + DateTime.Now.Hour.ToString() + ":" + DateTime.Now.Minute.ToString() + ", сколько у вас - не знаю";
                                    await Bot.SendTextMessageAsync(msgText.Chat.Id, time);
                                }
                                else if (res.Output == "foot.")
                                {
                                    string table = football.getTable();
                                    await Bot.SendTextMessageAsync(msgText.Chat.Id, table);
                                }
                                else if (res.Output == "anec.")
                                {
                                    string anec = Anecdot.anec();
                                    await Bot.SendTextMessageAsync(msgText.Chat.Id, anec);
                                }
                                else if (res.Output == "voice.")
                                {
                                    string anec = Anecdot.anec();

                                    SpeechSynthesizer speaker = new SpeechSynthesizer();

                                    speaker.Rate   = 2;
                                    speaker.Volume = 100;

                                    speaker.Speak(anec);

                                    speaker.SetOutputToWaveFile("soundfile.wav");
                                    speaker.Speak(anec + "\n АХАХАХАХАХАХ");
                                    speaker.SetOutputToDefaultAudioDevice();

                                    var fStream = new FileStream("soundfile.wav", FileMode.OpenOrCreate);
                                    await Bot.SendVoiceAsync(msgText.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(fStream));

                                    fStream.Dispose();
                                }
                                else if (res.Output == "beauty.")
                                {
                                    var fStream = new FileStream("..\\..\\1beauty.jpg", FileMode.OpenOrCreate);
                                    await Bot.SendPhotoAsync(msgText.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(fStream), "Красивее не сыскать");
                                }
                                else if (res.Output.Contains("poetryFlag"))
                                {
                                    var poem = res.Output.Replace("poetryFlag", "");
                                    SpeechSynthesizer speaker = new SpeechSynthesizer();

                                    speaker.Rate   = 2;
                                    speaker.Volume = 100;

                                    speaker.SetOutputToWaveFile("soundfile.wav");
                                    speaker.Speak(poem);
                                    speaker.SetOutputToDefaultAudioDevice();

                                    var fStream = new FileStream("soundfile.wav", FileMode.OpenOrCreate);
                                    await Bot.SendVoiceAsync(msgText.Chat.Id, new Telegram.Bot.Types.InputFiles.InputOnlineFile(fStream));

                                    fStream.Dispose();
                                }
                                else
                                {
                                    await Bot.SendTextMessageAsync(msgText.Chat.Id, res.Output);
                                }
                            }
                        }
                        else if (msgText.Type == Telegram.Bot.Types.Enums.MessageType.Photo)
                        {
                            ProcessImage(msgText.Photo[msgText.Photo.Length - 1].FileId, "", msgText.Chat.Id);
                        }
                        offset = message.Id + 1;
                    }
                }
            }
            catch (Telegram.Bot.Exceptions.ApiRequestException exception)
            {
                Console.WriteLine(exception.Message);
                asyncWorker.RunWorkerAsync("999037946:AAHbd0xIjp5l6iS0aGuVB-jIP2R4a99EUFo");
            }
        }
Exemplo n.º 23
0
 public override void control(bot ircbot, BotConfig Conf, string[] line, string command, int nick_access, string nick, string channel, bool bot_command, string type)
 {
     if ((type.Equals("channel") || type.Equals("query")) && bot_command == true)
     {
         foreach (Command tmp_command in this.Commands)
         {
             bool blocked    = tmp_command.Blacklist.Contains(channel) || tmp_command.Blacklist.Contains(nick);
             bool cmd_found  = false;
             bool spam_check = ircbot.get_spam_check(channel, nick, tmp_command.Spam_Check);
             if (spam_check == true)
             {
                 blocked = blocked || ircbot.get_spam_status(channel);
             }
             cmd_found = tmp_command.Triggers.Contains(command);
             if (blocked == true && cmd_found == true)
             {
                 ircbot.sendData("NOTICE", nick + " :I am currently too busy to process that.");
             }
             if (blocked == false && cmd_found == true)
             {
                 foreach (string trigger in tmp_command.Triggers)
                 {
                     switch (trigger)
                     {
                     case "stopchat":
                         if (spam_check == true)
                         {
                             ircbot.add_spam_count(channel);
                         }
                         if (nick_access >= tmp_command.Access)
                         {
                             foreach (string chat_nick in chatting_nick)
                             {
                                 if (chat_nick.Equals(nick, StringComparison.InvariantCultureIgnoreCase))
                                 {
                                     still_chatting = false;
                                     chatting_nick.Clear();
                                     chat_time.Enabled = false;
                                     chat_time.Stop();
                                     ircbot.sendData("PRIVMSG", line[2] + " :Ok, I will stop.");
                                     break;
                                 }
                             }
                             if (still_chatting == true)
                             {
                                 ircbot.sendData("PRIVMSG", line[2] + " :You are not currently talking to me.");
                             }
                         }
                         else
                         {
                             ircbot.sendData("NOTICE", nick + " :You do not have permission to use that command.");
                         }
                         break;
                     }
                 }
             }
         }
     }
     if ((type.Equals("channel") || type.Equals("query")) && bot_command == false)
     {
         chat_time.Interval = Convert.ToInt32(this.Options["chat_timeout"]) * 1000;
         if (line.GetUpperBound(0) >= 3)
         {
             string msg = "";
             if (line.GetUpperBound(0) > 3)
             {
                 msg = line[3].TrimStart(':') + " " + line[4];
             }
             else
             {
                 msg = line[3].TrimStart(':');
             }
             string[] words = msg.Split(' ');
             bool     me_in = false;
             foreach (string word in words)
             {
                 if (word.Contains(Conf.Nick))
                 {
                     me_in = true;
                     break;
                 }
             }
             if (me_in == true || still_chatting == true)
             {
                 bool nick_found = false;
                 for (int x = 0; x < chatting_nick.Count(); x++)
                 {
                     if (chatting_nick[x].Equals(nick, StringComparison.InvariantCultureIgnoreCase))
                     {
                         nick_found = true;
                     }
                 }
                 if (me_in == true && nick_found == false)
                 {
                     chatting_nick.Add(nick);
                     nick_found = true;
                 }
                 if (nick_found == true)
                 {
                     // Start Chatting
                     still_chatting = false;
                     chat_time.Stop();
                     Request r      = new Request(msg, myUser, myBot);
                     Result  res    = myBot.Chat(r);
                     string  owners = "";
                     foreach (string own in Conf.Owners)
                     {
                         owners += Conf.Owners + ",";
                     }
                     owners = owners.TrimEnd(',').Replace(",", " and ");
                     ircbot.sendData("PRIVMSG", line[2] + " :" + res.Output.Replace("[nick]", nick).Replace("[me]", Conf.Nick).Replace("[owner]", owners).Replace("[version]", Assembly.GetExecutingAssembly().GetName().Version.ToString()).Replace("\n", " "));
                     chat_time.Start();
                     still_chatting = true;
                 }
             }
         }
     }
 }