示例#1
0
        static void Main(string[] args)
        {
            try
            {
                botConfig = new TBotConfigParser().ParseAPIConf("TBotConf.json");

                db = new TBotDataBase();
                db.InitDBAsync().Wait();

                if (db.UsersCount() == 0)
                {
                    Console.WriteLine(TBotStrings.TBotNoUsersOnDB);
                    db.InsertUser(botConfig.BotMaster, true);
                }
                else
                {
                    TBotUser admin = db.GetUser(1);
                    if (!admin.Username.Equals(botConfig.BotMaster))
                    {
                        Console.WriteLine(string.Format(TBotStrings.TBotNotThisBotAdmin, db.GetDBName()));
                    }
                }

                listUsers = db.GetUserListAsync().Result;

                chatBot = factory.Create(ChatterBotType.PANDORABOTS, "f5d922d97e345aa1");

                chatBotSession = chatBot.CreateSession();

                tBot = new TelegramBotClient(botConfig.TelegramBotAPIKEY);

                var me = tBot.GetMeAsync().Result;
                botNick         = me.FirstName;
                Console.Title   = botNick;
                tBot.OnMessage += TBot_OnMessage;

                tBot.StartReceiving(Array.Empty <UpdateType>());

                if (botConfig.ChatGroupID != 0)
                {
                    Task <bool> callTask = Task.Run(() => SendMsgToTelegram(botConfig.ChatGroupID, string.Format(TBotStrings.TBotGreetingMSG, me.FirstName)));

                    callTask.Wait();
                    bool greetingSent = callTask.Result;

                    if (greetingSent)
                    {
                        Console.WriteLine("Greetings sent");
                    }
                }

                Console.WriteLine($"I am user {me.Id} and my Username is {me.Username}.\nStart listening for @{me.FirstName}");
                Console.ReadLine();
                tBot.StopReceiving();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
示例#2
0
 public void Cleverbot(string cmd)
 {
     if (_bot == null) _bot = _factory.Create(ChatterBotType.JABBERWACKY);
     if (_botSession == null) _botSession = _bot.CreateSession();
     var thought = _botSession.Think(cmd);
     WriteMsg(WebUtility.HtmlDecode(thought));
 }
示例#3
0
 private void InitializeChatBots()
 {
     factory = new ChatterBotFactory();
     manualResetEvent = new ManualResetEvent(false);
     ChatterBot bot2 = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
     bot2session = bot2.CreateSession();
 }
示例#4
0
        public static void Main(string[] args)
        {
            ChatterBotFactory factory = new ChatterBotFactory();

            ChatterBot        bot1        = factory.Create(ChatterBotType.CLEVERBOT);
            ChatterBotSession bot1session = bot1.CreateSession();

            ChatterBot        bot2        = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
            ChatterBotSession bot2session = bot2.CreateSession();

            var f = new SpeechSynthesizer();

            f.SelectVoiceByHints(VoiceGender.Female);

            var m = new SpeechSynthesizer();

            m.SelectVoiceByHints(VoiceGender.Male);

            string s = "Hi";

            while (true)
            {
                Console.WriteLine("bot1> " + s);
                m.Speak(s);

                s = bot2session.Think(s);
                Console.WriteLine("bot2> " + s);
                f.Speak(s);

                s = bot1session.Think(s);
            }
        }
示例#5
0
        private void InitializeChatBots()
        {
            factory          = new ChatterBotFactory();
            manualResetEvent = new ManualResetEvent(false);
            ChatterBot bot2 = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");

            bot2session = bot2.CreateSession();
        }
 /// <summary>
 /// Called when a new user handler is created.
 /// </summary>
 /// <param name="bot">Bot assigned to</param>
 /// <param name="sid">SteamID of the other user</param>
 public KeybankHandler(Bot bot, SteamID sid)
     : base(bot, sid)
 {
     chatterBot              = clsFunctions.factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
     chatterBotsession       = chatterBot.CreateSession();
     this.FriendAddedHandler = new SteamBot.FriendAddedHandler(bot, bot.BotControlClass.Substring(9), OtherSID);
     bot.GetInventory();
 }//KeybankHandler()
示例#7
0
文件: Utils.cs 项目: Zhangerr/pulse
 public static void initThink(ChatterBotSession s, string m, string target)
 {
     List<object> o = new List<object>();
     o.Add(target);
     o.Add(s);
     o.Add(m);
     new Thread(new ParameterizedThreadStart(threadThink)).Start(o);
 }
示例#8
0
        public CleverAI()
        {
            factory     = new ChatterBotFactory();
            bot1        = factory.Create(ChatterBotType.CLEVERBOT);
            bot1session = bot1.CreateSession();

            InitStats(100, 100, 25);
            Title = "the town blabber";
            Hue   = Utility.RandomSkinHue();

            if (!Core.AOS)
            {
                NameHue = 0x35;
            }

            if (this.Female = Utility.RandomBool())
            {
                this.Body = 0x191;
                this.Name = NameList.RandomName("female");
            }
            else
            {
                this.Body = 0x190;
                this.Name = NameList.RandomName("male");
            }

            AddItem(new FancyShirt(Utility.RandomBlueHue()));

            Item skirt;

            switch (Utility.Random(2))
            {
            case 0: skirt = new Skirt(); break;

            default:
            case 1: skirt = new Kilt(); break;
            }

            skirt.Hue = Utility.RandomGreenHue();

            AddItem(skirt);

            AddItem(new FeatheredHat(Utility.RandomGreenHue()));

            Item boots;

            switch (Utility.Random(2))
            {
            case 0: boots = new Boots(); break;

            default:
            case 1: boots = new ThighBoots(); break;
            }

            AddItem(boots);

            Utility.AssignRandomHair(this);
        }
示例#9
0
        public static void initThink(ChatterBotSession s, string m, string target)
        {
            List <object> o = new List <object>();

            o.Add(target);
            o.Add(s);
            o.Add(m);
            new Thread(new ParameterizedThreadStart(threadThink)).Start(o);
        }
示例#10
0
        public async Task InitializeAsync()
        {
            ready = false;
            ChatterBotFactory factory = new ChatterBotFactory();

            bot     = factory.Create(ChatterBotType.PANDORABOTS, "...");
            session = bot.CreateSession();
            await session.Initialize();

            ready = true;
        }
示例#11
0
 public ChatForm()
 {
     InitializeComponent();
     factory = new ChatterBotFactory();
     //God
     //bot1 = factory.Create(ChatterBotType.PANDORABOTS, "923c98f3de35606b");
     //Chompsky
     //bot1 = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
     ChatterBot bot1 = factory.Create(ChatterBotType.CLEVERBOT);
     bot1session = bot1.CreateSession();
 }
示例#12
0
 public JKAChatSession()
 {
     try
     {
         ChatterBotFactory factory = new ChatterBotFactory();
         session = factory.Create(ChatterBotType.CLEVERBOT).CreateSession();
     }
     catch
     {
         session = null;
     }
 }
示例#13
0
        void InitiateBot()
        {
            if (BotToUse == 0)
            {
                bot = botfactory.Create(ChatterBotType.CLEVERBOT);
            }
            else if (BotToUse == 1)
            {
                bot = botfactory.Create(ChatterBotType.PANDORABOTS, PandoraBotID);
            }

            botsession = bot.CreateSession();
        }
示例#14
0
        public override void Deserialize(GenericReader reader)
        {
            base.Deserialize(reader);

            int version = reader.ReadInt();

            factory     = new ChatterBotFactory();
            bot1        = factory.Create(ChatterBotType.CLEVERBOT);
            bot1session = bot1.CreateSession();
            if (Core.AOS && NameHue == 0x35)
            {
                NameHue = -1;
            }
        }
示例#15
0
        static async Task Run()
        {
            var Bot = new Api("Your API key here.");

            var me = await Bot.GetMe();

            Console.WriteLine("Hello my name is {0}", me.Username);

            var offset = 0;


            while (true)
            {
                var updates = await Bot.GetUpdates(offset);

                foreach (var update in updates)
                {
                    if (update.Message.Type == MessageType.TextMessage)
                    {
                        FileStream   fs     = new FileStream("log.txt", FileMode.Append, FileAccess.Write);
                        StreamWriter writer = new StreamWriter(fs);
                        {
                            await Bot.SendChatAction(update.Message.Chat.Id, ChatAction.Typing);

                            await Task.Delay(1000);

                            string s = update.Message.Text;
                            Console.ForegroundColor = ConsoleColor.White;
                            Console.WriteLine("@{1} ({2}): {0}", s, update.Message.From.Username, update.Message.From.FirstName);
                            writer.WriteLine("@{1} ({2}): {0}\r\n", s, update.Message.From.Username, update.Message.From.FirstName);
                            ChatterBotFactory factory     = new ChatterBotFactory();
                            ChatterBot        bot1        = factory.Create(ChatterBotType.CLEVERBOT);
                            ChatterBotSession bot1session = bot1.CreateSession();
                            s = bot1session.Think(s);
                            var t = await Bot.SendTextMessage(update.Message.Chat.Id, s);

                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Bot: {0}", s);
                            writer.WriteLine("Bot: {0}\r\n", s);
                            s = update.Message.Text;
                            writer.Close();
                            fs.Close();
                        }

                        offset = update.Id + 1;
                    }
                }
                await Task.Delay(500);
            }
        }
示例#16
0
            public static async Task <bool> TryAsk(ChatterBotSession cleverbot, ITextChannel channel, string message)
            {
                await channel.TriggerTypingAsync().ConfigureAwait(false);

                var response = await cleverbot.Think(message).ConfigureAwait(false);

                try
                {
                    await channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false);
                }
                catch
                {
                    await channel.SendConfirmAsync(response.SanitizeMentions()).ConfigureAwait(false); // try twice :\
                }
                return(true);
            }
示例#17
0
        public Utility()
        {
            ChatterBotFactory botFactory = new ChatterBotFactory();
            ChatterBot        bot        = botFactory.Create(ChatterBotType.CLEVERBOT);

            cleverBotSession = bot.CreateSession();

            if (File.Exists("commands.json"))
            {
                using (FileStream commandsFile = new FileStream("commands.json", FileMode.Open, FileAccess.Read))
                {
                    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(BonusCommandList));
                    BonusCommandList           output       = deserializer.ReadObject(commandsFile) as BonusCommandList;
                    customCommands = output?.CommandList;
                }
            }
        }
示例#18
0
 public void on_think(object s)
 {
     if (s is thoughargs && bot1session != null)
     {
         thoughargs args = (thoughargs)s;
         string     ss   = bot1session.Think(args.Text);
         //Console.WriteLine(bot1session.Think(args.Text));
         this.Say("" + ss);
         //this.Say("[You Said: " + args.Text + "]");
     }
     else
     {
         factory     = new ChatterBotFactory();
         bot1        = factory.Create(ChatterBotType.CLEVERBOT);
         bot1session = bot1.CreateSession();
         this.Say("No.. no.. More lemon pledge...");
     }
 }
示例#19
0
            public static string PrepareMessage(IUserMessage msg, out ChatterBotSession cleverbot)
            {
                var channel = msg.Channel as ITextChannel;

                cleverbot = null;

                if (channel == null)
                {
                    return(null);
                }

                Lazy <ChatterBotSession> lazyCleverbot;

                if (!CleverbotGuilds.TryGetValue(channel.Guild.Id, out lazyCleverbot))
                {
                    return(null);
                }

                cleverbot = lazyCleverbot.Value;

                var    nadekoId      = NadekoBot.Client.CurrentUser.Id;
                var    normalMention = $"<@{nadekoId}> ";
                var    nickMention   = $"<@!{nadekoId}> ";
                string message;

                if (msg.Content.StartsWith(normalMention))
                {
                    message = msg.Content.Substring(normalMention.Length).Trim();
                }
                else if (msg.Content.StartsWith(nickMention))
                {
                    message = msg.Content.Substring(nickMention.Length).Trim();
                }
                else
                {
                    return(null);
                }

                return(message);
            }
示例#20
0
        public static void Main(string[] args)
        {
            ChatterBotFactory factory = new ChatterBotFactory();

            ChatterBot        bot1        = factory.Create(ChatterBotType.CLEVERBOT);
            ChatterBotSession bot1session = bot1.CreateSession();

            ChatterBot        bot2        = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
            ChatterBotSession bot2session = bot2.CreateSession();

            string s = "Hi";

            while (true)
            {
                Console.WriteLine("bot1> " + s);

                s = bot2session.Think(s);
                Console.WriteLine("bot2> " + s);

                s = bot1session.Think(s);
            }
        }
示例#21
0
        static void Main(string[] args)
        {
            ChatterBotFactory f   = new ChatterBotFactory();
            ChatterBot        bot = f.Create(ChatterBotType.CLEVERBOT);

            chatBot = bot.CreateSession();

            DiscordClient client = new DiscordClient();

            using (StreamReader sr = new StreamReader("userinfo.txt"))
            {
                client.ClientPrivateInformation          = new DiscordUserInformation();
                client.ClientPrivateInformation.email    = sr.ReadLine();
                client.ClientPrivateInformation.password = sr.ReadLine();
            }

            client.SendLoginRequest();
            Thread t = new Thread(client.Connect);

            t.Start();

            Console.ReadLine();
        }
示例#22
0
        static void OnChatMessage(SteamFriends.FriendMsgCallback callback)
        {
            if (callback.EntryType == EChatEntryType.ChatMsg)
            {
                var msg  = callback.Message.Trim();
                var msg2 = msg.Split(' ');
                senderName = steamFriends.GetFriendPersonaName(callback.Sender);

                Console.WriteLine($"[SteamBot] Message received: {senderName}: {callback.Message}");
                string[] args;
                switch (msg2[0].ToLower())
                {
                case "Hello":
                    steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Hello");
                    break;

                default:
                    string            botReply;
                    ChatterBotFactory factory = new ChatterBotFactory();
                    ChatterBot        bot     = factory.Create(ChatterBotType.CLEVERBOT);
                    botSession = bot.CreateSession();
                    try
                    {
                        botReply = botSession.Think(callback.Message);
                    }
                    catch (Exception)
                    {
                        return;
                    }

                    steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, botReply);
                    Console.WriteLine($"[SteamBot] Responded to {senderName}: {botReply}");

                    break;
                }
            }
        }
示例#23
0
        public static void Main(string[] args)
        {
            captcha.Hide();
            Console.Title = "CleverOmegle";
            if (!Directory.Exists(@"logs/"))
            {
                Directory.CreateDirectory(@"logs/");
            }
            ChatterBot cake = factory.Create(ChatterBotType.CLEVERBOT);
            day = now.Day.ToString();
            month = now.Month.ToString();
            year = now.Year.ToString();
            fileLocation = @"logs\" + String.Format("{0}-{1}-{2}.txt", day, month, year);
            bot = cake.CreateSession();

            omegle.MessageReceived += new MessageReceivedEvent(omegle_MessageReceived);
            omegle.StrangerTyping += new EventHandler(omegle_StrangerTyping);
            omegle.StrangerDisconnected += new EventHandler(omegle_StrangerDisconnected);
            omegle.WaitingForPartner += new EventHandler(omegle_WaitingForPartner);
            omegle.Connected += new EventHandler(omegle_Connected);
            omegle.UnhandledResponse += new UnhandledResponseEvent(omegle_UnhandledResponse);
            omegle.WebException += new WebExceptionEvent(omegle_WebException);
            omegle.CaptchaRequired += new CaptchaRequiredEvent(omegle_CaptchaRequired);
            omegle.CaptchaRefused += new EventHandler(omegle_CaptchaRefused);
            Console.WriteLine("Should the bot start conversations? (y/n)");
            string answerBool = Console.ReadLine();
            if (string.Equals(answerBool, "y", StringComparison.CurrentCultureIgnoreCase)) //y and Y will both yield true
            {
                BotInitiates = true;
            }
            else
            {
                BotInitiates = false;
            }
            Console.Clear();
            omegle.Connect();
        }
示例#24
0
文件: Game.cs 项目: deoxysjr/MopsBot
        void IModule.Install(ModuleManager manager)
        {
            Random random = new Random();

            userScores = new UserScore();

            ChatterBotFactory factory = new ChatterBotFactory();

            ChatterBot        _Cleverbot        = factory.Create(ChatterBotType.CLEVERBOT);
            ChatterBotSession Cleverbot1session = _Cleverbot.CreateSession();

            ChatterBot        bot2        = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
            ChatterBotSession bot2session = bot2.CreateSession();

            _manager = manager;
            _client  = manager.Client;

            _client.MessageReceived += _client_MessageReceived;

            manager.CreateCommands("", group =>
            {
                group.PublicOnly();

                group.CreateCommand("kawush")
                .Description("Makes Kabooom")
                .Parameter("User")
                .Do(async e =>
                {
                    e.Args[0] = e.Args[0].Replace("!", "");
                    if (bomb == null || !bomb.active && e.Server.FindUsers(e.Args[0], false).FirstOrDefault().Status.Value.Equals("online"))
                    {
                        bomb = new Data.Session.Bomb(e.User, e.Server.FindUsers(e.Args[0]).FirstOrDefault());

                        await e.Channel.SendMessage($"{e.Server.FindUsers(e.Args[0]).FirstOrDefault().Name} is being bombed!\n" +
                                                    "Quick, find the right wire to cut!\n" +
                                                    $"({String.Join(", ", bomb.wires)})\n");
                    }
                    else
                    {
                        await e.Channel.SendMessage("Either the User is not online, or the Command is already in use!");
                    }
                });

                group.CreateCommand("rollDice")
                .Description("Rolls a random Number between Min and Max")
                .Parameter("Min")
                .Parameter("Max")
                .Do(async e =>
                {
                    await e.Channel.SendMessage($"[{random.Next(int.Parse(e.Args[0]), int.Parse(e.Args[1]) + 1)}]");
                });

                group.CreateCommand("Slotmachine")
                .Description("Costs 5$")
                .Do(e =>
                {
                    if (findDataUser(e.User).Score < 5)
                    {
                        e.Channel.SendMessage("Not enough money");
                        return;
                    }
                    Random rnd = new Random();
                    int[] num  = { rnd.Next(0, 6), rnd.Next(0, 6), rnd.Next(0, 6) }; //0=Bomb, 1=Cherry, 2= Free, 3= cookie, 4= small, 5= big
                    bool won   = true;
                    int amount = 0;

                    if (num[0] == num[1] && num[1] == num[2])
                    {
                        switch (num[0])
                        {
                        case 0:
                            won    = false;
                            amount = 250;
                            break;

                        case 1:
                            amount = 40;
                            break;

                        case 2:
                            amount = 50;
                            break;

                        case 3:
                            amount = 100;
                            break;

                        case 4:
                            amount = 200;
                            break;

                        case 5:
                            amount = 500;
                            break;
                        }
                    }
                    else if ((num[0] == num[1] && num[0] == 1) || (num[0] == num[2] && num[0] == 1) || (num[1] == num[2] && num[1] == 1))
                    {
                        won    = true;
                        amount = 20;
                    }
                    else if (num[0] == 1 || num[1] == 1 | num[2] == 1)
                    {
                        amount = 5;
                    }
                    if (won)
                    {
                        addToBase(e.User, amount - 5);
                    }
                    else
                    {
                        addToBase(e.User, (5 + amount) * -1);
                    }
                    e.Channel.SendMessage("––––––––––––––––––––\n ¦   " + ((num[0] == 0) ? "💣" : ((num[0] == 1) ? "🆓" : ((num[0] == 2) ? "🍒" : ((num[0] == 3) ? "🍪" : ((num[0] == 4) ? "🔹" : "🔷"))))) + "   ¦  " + ((num[1] == 0) ? "💣" : ((num[1] == 1) ? "🆓" : ((num[1] == 2) ? "🍒" : ((num[1] == 3) ? "🍪" : ((num[1] == 4) ? "🔹" : "🔷"))))) + "   ¦  " + ((num[2] == 0) ? "💣" : ((num[2] == 1) ? "🆓" : ((num[2] == 2) ? "🍒" : ((num[2] == 3) ? "🍪" : ((num[2] == 4) ? "🔹" : "🔷"))))) + "  ¦\n ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\n 🆓=5$   🆓🆓=20$   🆓🆓🆓=40$\n 🍒🍒🍒=50$ 🍪🍪🍪=100$\n 🔹🔹🔹=200$ 🔷🔷🔷=500$\n 💣💣💣=-250$\n\n You " + ((won) ? "won " : "lost ") + amount + "$" +
                                          $"\nYou now have {findDataUser(e.User).Score}$");
                });

                // group.CreateCommand("1-")
                // .Description("Let's you talk to Chomsky")
                // .Parameter("Message", ParameterType.Unparsed)
                // .Do(async e =>
                // {
                //     await e.Channel.SendMessage($"{bot2session.Think(e.Args[0])}");
                // });

                // group.CreateCommand("2-")
                // .Description("Let's you talk to CleverBot")
                // .Parameter("Message", ParameterType.Unparsed)
                // .Do(async e =>
                // {
                //     await e.Channel.SendMessage($"{HttpUtility.HtmlDecode(Cleverbot1session.Think(e.Args[0]))}");
                // });

                // group.CreateCommand("cleverCeption")
                //.Description("Bots talk to each other for a fixed amount of messages. Try not to abuse!")
                //.Parameter("Message Count", ParameterType.Required)
                //.Parameter("Starting Message", ParameterType.Unparsed)
                //.Do(async e =>
                //{
                //    ChatterBot _Cleverbot2 = factory.Create(ChatterBotType.CLEVERBOT);
                //    ChatterBotSession Cleverbot2session = _Cleverbot2.CreateSession();

                //    string message = e.Args[1] != "" ? e.Args[1] : "Hello";
                //    await e.Channel.SendMessage("A: " + message);

                //    for(int count = 0; count < int.Parse(e.Args[0]); count++)
                //    {
                //        if(count % 2 != 0)
                //        {
                //            message = HttpUtility.HtmlDecode(Cleverbot1session.Think(message));
                //            await e.Channel.SendMessage("A: " + message);
                //        }
                //        else if(count % 2 == 0)
                //        {
                //            message = HttpUtility.HtmlDecode(Cleverbot2session.Think(message));
                //            await e.Channel.SendMessage("B: " + message);
                //        }
                //    }
                //});
            });

            manager.CreateCommands("hangman", group =>
            {
                group.CreateCommand("start")
                .Description("Create a game of hangman")
                .Parameter("Word")
                .Parameter("Attempts")
                .Parameter("Server-ID")
                .Parameter("Channel-ID")
                .PrivateOnly()
                .Do(async e =>
                {
                    if (hangman == null || !hangman.active)
                    {
                        hangman = new Data.Session.Hangman(e.Args[0], int.Parse(e.Args[1]));
                        await e.User.SendMessage("Done!");
                        Channel message = _client.GetServer(ulong.Parse(e.Args[2])).GetChannel(ulong.Parse(e.Args[3]));
                        await message.SendMessage($"{e.User.Name} started a session of hangman!\n\nParticipate by using the **!hangman guess** command!\n\n{hangman.hidden} ({e.Args[1]} false tries allowed)");
                    }
                    else
                    {
                        await e.User.SendMessage("Currently in use, sorry!");
                    }
                });

                group.CreateCommand("guess")
                .Description("Guess a character")
                .Parameter("Guess")
                .Do(async e =>
                {
                    if (hangman.active)
                    {
                        string output = "";

                        if (e.Args[0].Length == hangman.word.Length)
                        {
                            output = hangman.solve(e.Args[0], e.User);
                        }

                        else
                        {
                            output = hangman.input(e.Args[0].ToCharArray()[0], e.User);
                        }

                        await e.Channel.SendMessage(output);
                    }
                    else
                    {
                        await e.Channel.SendMessage("No session of hangman running, sorry!");
                    }
                });
            });

            manager.CreateCommands("blackjack", group =>
            {
                group.CreateCommand("start")
                .Description("Set up a table of blackjack")
                .Do(async e =>
                {
                    await e.Channel.SendMessage(blackjack.showCards() + "\n\n" + blackjack.endRound());
                });

                group.CreateCommand("join")
                .Description("Join the table")
                .Parameter("Bet amount")
                .Do(async e =>
                {
                    if (blackjack == null || !blackjack.active)
                    {
                        blackjack = new Data.Session.Blackjack(e.Server.GetUser(_client.CurrentUser.Id));
                        await e.Channel.SendMessage("Table set up. Woof.\n\n");
                    }
                    if (int.Parse(e.GetArg("Bet amount")) <= findDataUser(e.User).Score&& int.Parse(e.GetArg("Bet amount")) > 0)
                    {
                        await e.Channel.SendMessage(blackjack.userJoin(e.User, int.Parse(e.GetArg("Bet amount"))));
                    }
                    else
                    {
                        await e.Channel.SendMessage("You can't bet that much.");
                    }
                });

                group.CreateCommand("hit")
                .Description("Draw a card")
                .Do(async e =>
                {
                    await e.Channel.SendMessage(blackjack.drawCard(e.User, true));
                });

                group.CreateCommand("skip")
                .Description("Skip for the round")
                .Do(async e =>
                {
                    await e.Channel.SendMessage(blackjack.skipRound(e.User));
                });
            });

            manager.CreateCommands("scramble", group =>
            {
                group.CreateCommand("start")
                .Description("Scramble a word up and guess what it is")
                .Parameter("Word")
                .Parameter("Attempts")
                .Parameter("Server-ID")
                .Parameter("Channel-ID")
                .PrivateOnly()
                .Do(async e =>
                {
                    if (scramble == null || !scramble.active)
                    {
                        scramble = new Data.Session.Scramble(e.Args[0], int.Parse(e.Args[1]));
                        await e.User.SendMessage("Done :smiley_cat:");
                        Channel message = _client.GetServer(ulong.Parse(e.Args[2])).GetChannel(ulong.Parse(e.Args[3]));
                        await message.SendMessage($"{e.User.Name} started a session of word scrambler!\n\nParticipate by using the **!scramble guess** command!\n\n{scramble.hidden} ({e.Args[1]} false tries allowed)");
                    }
                    else
                    {
                        await e.User.SendMessage("Currently in use, sorry :frowning:");
                    }
                });

                group.CreateCommand("guess")
                .Description("Guess the word")
                .Parameter("Guess")
                .Do(async e =>
                {
                    if (scramble.active)
                    {
                        string output = scramble.solve(e.Args[0], e.User);
                        await e.Channel.SendMessage(output);
                    }
                    else
                    {
                        await e.Channel.SendMessage("No session of word scrambler running, sorry :frowning:");
                    }
                });
            });

            manager.CreateCommands("salad", group =>
            {
                group.CreateCommand("start")
                .Description("Create a game of word-salad")
                .Parameter("Words", ParameterType.Unparsed)
                .Do(async e =>
                {
                    string[] words = e.GetArg(0).Split(' ');
                    salad          = new Data.Session.Salad(words.ToList());

                    await e.Channel.SendMessage(salad.drawMap());
                });

                group.CreateCommand("guess")
                .Description("Guess the words x/y start and end point. Example: !salad guess 1;1 1;4")
                .Parameter("Guess", ParameterType.Unparsed)
                .Do(async e =>
                {
                    await e.Channel.SendMessage(salad.guessWord(e.User, e.GetArg(0)));
                });
            });

            manager.CreateCommands("ranking", group =>
            {
                group.PublicOnly();

                group.CreateCommand("Score")
                .Description("get the top scoreboard")
                .Parameter("limit", ParameterType.Optional)
                .Parameter("global", ParameterType.Optional)
                .Do(async e =>
                {
                    List <Data.Individual.User> tempSort = userScores.users.OrderByDescending(u => u.Score).ToList();

                    int limit = 10;

                    if (e.GetArg("limit").Length > 0)
                    {
                        limit = int.Parse(e.GetArg("limit"));
                    }

                    string output = "";

                    if (e.GetArg("global") == "")
                    {
                        int count = 0;

                        foreach (Data.Individual.User curUser in tempSort)
                        {
                            if (count >= limit)
                            {
                                break;
                            }
                            count++;
                            try
                            {
                                output += $"#{count} ``$ {curUser.Score} $`` by {e.Server.GetUser(curUser.ID).Name}\n";
                            }
                            catch (NullReferenceException ex)
                            {
                                count--;
                            }
                        }
                    }
                    else if (e.GetArg("global") == "true")
                    {
                        await e.Channel.SendMessage(userScores.drawDiagram(int.Parse(e.GetArg("limit")), UserScore.DiagramType.Score));
                    }

                    await e.Channel.SendMessage(output);
                });

                group.CreateCommand("Experience")
                .Description("get the top expboard")
                .Parameter("limit", ParameterType.Optional)
                .Parameter("global", ParameterType.Optional)
                .Do(async e =>
                {
                    List <Data.Individual.User> tempSort = userScores.users.OrderByDescending(u => u.Experience).ToList();

                    int limit = 10;

                    if (e.GetArg("limit").Length > 0)
                    {
                        limit = int.Parse(e.GetArg("limit"));
                    }

                    string output = "";

                    if (e.GetArg("global") == "")
                    {
                        int count = 0;

                        foreach (Data.Individual.User curUser in tempSort)
                        {
                            if (count >= limit)
                            {
                                break;
                            }
                            count++;
                            try
                            {
                                output += $"#{count} ``{curUser.Experience} EXP`` by {e.Server.GetUser(curUser.ID).Name}\n";
                            }
                            catch (NullReferenceException ex)
                            {
                                count--;
                            }
                        }
                    }
                    else if (e.GetArg("global") == "true")
                    {
                        await e.Channel.SendMessage(userScores.drawDiagram(int.Parse(e.GetArg("limit")), UserScore.DiagramType.Experience));
                    }

                    await e.Channel.SendMessage(output);
                });

                group.CreateCommand("Level")
                .Description("get the top levelboard")
                .Parameter("limit", ParameterType.Optional)
                .Parameter("global", ParameterType.Optional)
                .Do(async e =>
                {
                    List <Data.Individual.User> tempSort = userScores.users.OrderByDescending(u => u.Level).ToList();

                    int limit = 10;

                    if (e.GetArg("limit").Length > 0)
                    {
                        limit = int.Parse(e.GetArg("limit"));
                    }

                    string output = "";

                    if (e.GetArg("global") == "")
                    {
                        int count = 0;

                        foreach (Data.Individual.User curUser in tempSort)
                        {
                            if (count >= limit)
                            {
                                break;
                            }
                            count++;
                            try
                            {
                                output += $"#{count} ``Level {curUser.Level}`` by {e.Server.GetUser(curUser.ID).Name}\n";
                            }
                            catch (NullReferenceException ex)
                            {
                                count--;
                            }
                        }
                    }
                    else if (e.GetArg("global") == "true")
                    {
                        await e.Channel.SendMessage(userScores.drawDiagram(int.Parse(e.GetArg("limit")), UserScore.DiagramType.Level));
                    }

                    await e.Channel.SendMessage(output);
                });
            });
        }
示例#25
0
        static void Main(string[] args)
        {
            try
            {
                Utils.loadPlugin();

                /*Console.WriteLine("try");
                 * Console.WriteLine(Commands.commands.Count);
                 * Console.ReadKey();
                 * Utils.loadPlugin();
                 * Console.WriteLine("loading again");
                 * Console.WriteLine(Commands.commands.Count);
                 * Console.ReadKey();*/
                NetworkStream stream;
                TcpClient     irc;
                string        inputLine;
                StreamReader  reader;
                //   try
                //  {
                irc              = new TcpClient(SERVER, PORT);
                stream           = irc.GetStream();
                reader           = new StreamReader(stream);
                writer           = new StreamWriter(stream);
                writer.AutoFlush = true;
                writer.WriteLine(USER);
                writer.WriteLine("NICK " + NICK);
                //   Utils.join(CHANNEL);
                ChatterBotFactory factory = new ChatterBotFactory();
                ChatterBot        clever  = factory.Create(ChatterBotType.CLEVERBOT);
                ChatterBot        jabber  = factory.Create(ChatterBotType.JABBERWACKY);
                ChatterBot        panda   = factory.Create(ChatterBotType.PANDORABOTS, "d689f7b8de347251");
                jab = jabber.CreateSession();
                pan = panda.CreateSession();
                ses = clever.CreateSession();
                //Thread t = new Thread(new ThreadStart(oper));
                //   t.Start();
                Commands.init();
                opered = false;
                while (true)
                {
                    while ((inputLine = reader.ReadLine()) != null)
                    {
                        int      numeric;
                        string   noinit   = inputLine.Substring(1);
                        string   text     = noinit.Substring(noinit.IndexOf(':') + 1);
                        string[] splitted = text.Split(' ');
                        string[] param    = inputLine.Split(' ');
                        if (param.Length > 3 && (param[3].Equals("=") || param[3].Equals("@")))
                        {
                            parseUsers(param[4], inputLine);
                        }
                        // :[email protected] MODE #pulse +v Sync
                        else if (param.Length > 4 && param[1] == "MODE")
                        {
                            writer.WriteLine("WHOIS " + param[4]);
                        }
                        else if (param.Length > 1 && param[1] == "NICK")
                        {
                            string user = inputLine.Substring(1, inputLine.IndexOf('!') - 1);
                            if (users.ContainsKey(user))
                            {
                                var temp = users[user];
                                users.Remove(user);
                                users.Add(text, temp);
                                //  users.Add()
                            }
                        }
                        else if (param.Length > 3 && param[1] == "KICK")
                        {
                            string chan = param[2];
                            string user = param[3];
                            channels.Remove(chan);
                            if (user == NICK)
                            {
                                Utils.join(chan);
                            }
                            else
                            {
                                if (users.ContainsKey(user))
                                {
                                    if (users[user].ContainsKey(chan))
                                    {
                                        users[user].Remove(chan);
                                    }
                                }
                            }
                        }
                        else if (inputLine.ToLower().Contains("privmsg"))
                        {
                            string channel = inputLine.Split(' ')[2];
                            string user    = inputLine.Substring(1, inputLine.IndexOf('!') - 1);
                            if (!Directory.Exists("chatlog"))
                            {
                                Directory.CreateDirectory("chatlog");
                            }
                            string date = DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year;
                            File.AppendAllText("chatlog\\" + date + ";" + channel + ".txt", "[" + DateTime.Now.ToString() + "] <" + user + ">: " + text + "\r\n");
                            bool ispm = false;
                            if (inputLine.Split(' ')[2].Equals(NICK)) //private message
                            {
                                if (!splitted[0].StartsWith("!"))
                                {
                                    if (!pms.ContainsKey(user)) //cool bot mode but useless
                                    {
                                        pms.Add(user, panda.CreateSession());
                                    }
                                    //   writer.WriteLine("PRIVMSG " + user + " :" + pms[user].Think(text));
                                    Utils.initThink(pan, text, user);
                                }
                                ispm = true;
                            }
                            string command = splitted[0];
                            if (command.StartsWith("!"))
                            {
                                string rest = "";

                                if (command.Length > 1 && splitted.Length > 1)
                                {
                                    rest = text.Substring(command.Length + 1);
                                }
                                else
                                {
                                    rest = text;
                                }
                                command = command.ToLower();


                                //  else
                                {
                                    var cmds = Commands.commands;
                                    if (cmds.ContainsKey(command))
                                    {
                                        CommandPair cp = cmds[command];
                                        // if (users.ContainsKey(user))
                                        UserLevel lvl = Utils.getUserLevel(user, ispm ? "#pulse" : channel);
                                        if (lvl >= cp.ci.level)
                                        {
                                            if (splitted.Length >= cp.ci.args)
                                            {
                                                cp.exe(new CommandParams(ispm ? user : channel, user, rest, inputLine, splitted, writer, lvl));
                                                msg("#services", command + " executed by " + user + " on " + (ispm ? user : channel));
                                            }
                                            else
                                            {
                                                msg(ispm ? user : channel, "Not enough parameters! " + command + " requires " + cp.ci.args + " arguments");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else if (inputLine.StartsWith("PING"))
                        {
                            writer.WriteLine("PONG " + inputLine.Split(' ')[1]);
                        }
                        else if (param.Length > 2 && (param[1] == "JOIN" || param[1] == "PART"))
                        {
                            if (inputLine.Split('!')[0].Substring(1).Equals(NICK))
                            {
                                string channel = param[2].Substring(1);
                                if (param[1] == "JOIN")
                                {
                                    Utils.admin(channel);
                                    channels.Add(channel.ToLower());
                                }
                                else
                                {
                                    channels.Remove("#" + channel.ToLower()); //for some reason no leading : when part
                                }
                            }
                        }
                        else if (param.Length > 3 && Int32.TryParse(param[1], out numeric))
                        {
                            if (numeric == 322) //channel listing
                            {
                                if (!noJoin.Contains(param[3].ToLower()))
                                {
                                    Utils.join(param[3]);
                                }
                            }
                            else if (numeric == 376) //end of motd
                            {
                                if (!opered)
                                {
                                    oper();
                                    opered = true;
                                }
                                //>> :exp.ulse.net 319 alex Sync :+#pulse #touhou ~#sync #minecraft
                            }
                            else if (numeric == 319) //whois channel list
                            {
                                string   user     = param[3];
                                string[] channels = text.Split(' ');
                                foreach (string s in from i in channels where !string.IsNullOrWhiteSpace(i) select i)
                                {
                                    UserLevel toAdd = UserLevel.NORMAL;
                                    switch (s[0])
                                    {
                                    case '+':
                                        toAdd = UserLevel.VOICE;
                                        break;

                                    case '%':
                                        toAdd = UserLevel.HOP;
                                        break;

                                    case '@':
                                        toAdd = UserLevel.OP;
                                        break;

                                    case '~':
                                        toAdd = UserLevel.OWNER;
                                        break;

                                    case '&':
                                        toAdd = UserLevel.ADMIN;
                                        break;
                                    }
                                    string channame = s;
                                    if (toAdd != UserLevel.NORMAL)
                                    {
                                        channame = channame.Substring(1); //getrid of symbol if  special status
                                        if (users.ContainsKey(user))
                                        {
                                            if (users[user].ContainsKey(channame))
                                            {
                                                users[user][channame] = toAdd;
                                            }
                                            else
                                            {
                                                users[user].Add(channame, toAdd);
                                            }
                                        }
                                        else
                                        {
                                            users.Add(user, new Dictionary <string, UserLevel>());
                                            users[user].Add(channame, toAdd);
                                        }
                                    }
                                    else
                                    {
                                        if (users.ContainsKey(user))
                                        {
                                            if (users[user].ContainsKey(channame))
                                            {
                                                users[user].Remove(channame);
                                                if (users[user].Count == 0)
                                                {
                                                    users.Remove(user);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //if (!(inputLine.EndsWith("JOIN :" + CHANNEL) || inputLine.EndsWith("QUIT")))
                        {
                            Console.WriteLine(inputLine);
                        }
                    }
                    // Close all streams
                    writer.Close();
                    reader.Close();
                    irc.Close();
                }
            }
            catch (Exception e)
            {
                // Show the exception, sleep for a while and try to establish a new connection to irc server
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.InnerException);
                Console.WriteLine(e);
                Thread.Sleep(5000);
                string[] argv = { };
                Console.WriteLine("restarting");
                Main(argv);
            }
        }
示例#26
0
        void IModule.Install(ModuleManager manager)
        {
            aTimer          = new Timer();
            aTimer.Elapsed += ATimer_Elapsed;
            wires           = new string[] { "salmon", "purple", "aquamarine", "emerald", "apricot", "cerulean", "peach", "blue", "red", "yellow", "black", "white", "green", "orange", "cyan", "beige", "grey", "gold", "buff", "monza", "rose", "tan", "brown", "flax", "pink" };

            Random random = new Random();

            userScores = new UserScore();

            ChatterBotFactory factory = new ChatterBotFactory();

            ChatterBot        _Cleverbot        = factory.Create(ChatterBotType.CLEVERBOT);
            ChatterBotSession Cleverbot1session = _Cleverbot.CreateSession();

            ChatterBot        bot2        = factory.Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477");
            ChatterBotSession bot2session = bot2.CreateSession();

            _manager = manager;
            _client  = manager.Client;

            _client.MessageReceived += _client_MessageReceived;

            manager.CreateCommands("", group =>
            {
                group.PublicOnly();

                group.CreateCommand("kawush")
                .Description("Makes Kabooom")
                .Parameter("User")
                .Do(async e =>
                {
                    e.Args[0] = e.Args[0].Replace("!", "");
                    if (victim == null && e.Server.FindUsers(e.Args[0], false).FirstOrDefault().Status.Value.Equals("online") && status == 0)
                    {
                        status = 1;

                        aTimer.Interval = random.Next(30000, 60000);
                        aTimer.Start();

                        int wiresrandom = random.Next(2, 11);
                        string output   = "";
                        wiresUsed       = new string[wiresrandom];

                        for (int i = 0; i < wiresrandom; i++)
                        {
                            int innerrandom = random.Next(0, wires.Length);
                            if (!wiresUsed.Contains(wires[innerrandom]))
                            {
                                wiresUsed[i] = wires[innerrandom];
                                output      += $" {wiresUsed[i]} ";
                            }
                            else
                            {
                                i--;
                            }
                        }
                        wire   = wiresUsed[random.Next(0, wiresUsed.Length)];
                        victim = e.Server.FindUsers(e.Args[0]).FirstOrDefault();

                        if (victim.IsBot)
                        {
                            await e.Channel.SendMessage("How dare you attack a Bot like this? How about you taste your own medicine?");
                            victim = e.User;
                        }
                        if (victim != e.User)
                        {
                            culprit = e.User;
                        }
                        beenSearch = e.Channel;
                        await e.Channel.SendMessage($"{victim.Name} is being bombed!\n" +
                                                    "Quick, find the right wire to cut!\n" +
                                                    $"({output})\n" +
                                                    $"You have got {(int)(aTimer.Interval / 1000)} seconds before the bomb explodes!");
                    }
                    else
                    {
                        await e.Channel.SendMessage("Either the User is not online, or the Command is already in use!");
                    }
                });

                group.CreateCommand("rollDice")
                .Description("Rolls a random Number between Min and Max")
                .Parameter("Min")
                .Parameter("Max")
                .Do(async e =>
                {
                    await e.Channel.SendMessage($"[{random.Next(int.Parse(e.Args[0]), int.Parse(e.Args[1]) + 1)}]");
                });

                group.CreateCommand("Slotmachine")
                .Description("Costs 5$")
                .Do(e =>
                {
                    if (findDataUser(e.User).Score < 5)
                    {
                        e.Channel.SendMessage("Not enough money");
                        return;
                    }
                    Random rnd = new Random();
                    int[] num  = { rnd.Next(0, 6), rnd.Next(0, 6), rnd.Next(0, 6) }; //0=Bomb, 1=Cherry, 2= Free, 3= cookie, 4= small, 5= big
                    bool won   = true;
                    int amount = 0;

                    if (num[0] == num[1] && num[1] == num[2])
                    {
                        switch (num[0])
                        {
                        case 0:
                            won    = false;
                            amount = 250;
                            break;

                        case 1:
                            amount = 40;
                            break;

                        case 2:
                            amount = 50;
                            break;

                        case 3:
                            amount = 100;
                            break;

                        case 4:
                            amount = 200;
                            break;

                        case 5:
                            amount = 500;
                            break;
                        }
                    }
                    else if ((num[0] == num[1] && num[0] == 1) || (num[0] == num[2] && num[0] == 1) || (num[1] == num[2] && num[1] == 1))
                    {
                        won    = true;
                        amount = 20;
                    }
                    else if (num[0] == 1 || num[1] == 1 | num[2] == 1)
                    {
                        amount = 5;
                    }
                    if (won)
                    {
                        addToBase(e.User, amount - 5);
                    }
                    else
                    {
                        addToBase(e.User, (5 + amount) * -1);
                    }
                    e.Channel.SendMessage("––––––––––––––––––––\n ¦   " + ((num[0] == 0) ? "💣" : ((num[0] == 1) ? "🆓" : ((num[0] == 2) ? "🍒" : ((num[0] == 3) ? "🍪" : ((num[0] == 4) ? "🔹" : "🔷"))))) + "   ¦  " + ((num[1] == 0) ? "💣" : ((num[1] == 1) ? "🆓" : ((num[1] == 2) ? "🍒" : ((num[1] == 3) ? "🍪" : ((num[1] == 4) ? "🔹" : "🔷"))))) + "   ¦  " + ((num[2] == 0) ? "💣" : ((num[2] == 1) ? "🆓" : ((num[2] == 2) ? "🍒" : ((num[2] == 3) ? "🍪" : ((num[2] == 4) ? "🔹" : "🔷"))))) + "  ¦\n ¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯\n 🆓=5$   🆓🆓=20$   🆓🆓🆓=40$\n 🍒🍒🍒=50$ 🍪🍪🍪=100$\n 🔹🔹🔹=200$ 🔷🔷🔷=500$\n 💣💣💣=-250$\n\n You " + ((won) ? "won " : "lost ") + amount + "$" +
                                          $"\nYou now have {findDataUser(e.User).Score}$");
                });

                group.CreateCommand("1-")
                .Description("Let's you talk to Chomsky")
                .Parameter("Message", ParameterType.Unparsed)
                .Do(async e =>
                {
                    await e.Channel.SendMessage($"{bot2session.Think(e.Args[0])}");
                });

                group.CreateCommand("2-")
                .Description("Let's you talk to CleverBot")
                .Parameter("Message", ParameterType.Unparsed)
                .Do(async e =>
                {
                    await e.Channel.SendMessage($"{HttpUtility.HtmlDecode(Cleverbot1session.Think(e.Args[0]))}");
                });

                group.CreateCommand("cleverCeption")
                .Description("Bots talk to each other for a fixed amount of messages. Try not to abuse!")
                .Parameter("Message Count", ParameterType.Required)
                .Parameter("Starting Message", ParameterType.Unparsed)
                .Do(async e =>
                {
                    ChatterBot _Cleverbot2 = factory.Create(ChatterBotType.CLEVERBOT);
                    ChatterBotSession Cleverbot2session = _Cleverbot2.CreateSession();

                    string message = e.Args[1] != "" ? e.Args[1] : "Hello";
                    await e.Channel.SendMessage("A: " + message);

                    for (int count = 0; count < int.Parse(e.Args[0]); count++)
                    {
                        if (count % 2 != 0)
                        {
                            message = HttpUtility.HtmlDecode(Cleverbot1session.Think(message));
                            await e.Channel.SendMessage("A: " + message);
                        }
                        else if (count % 2 == 0)
                        {
                            message = HttpUtility.HtmlDecode(Cleverbot2session.Think(message));
                            await e.Channel.SendMessage("B: " + message);
                        }
                    }
                });
            });

            manager.CreateCommands("hangman", group =>
            {
                group.CreateCommand("start")
                .Description("Create a game of hangman")
                .Parameter("Word")
                .Parameter("Attempts")
                .Parameter("Server-ID")
                .Parameter("Channel-ID")
                .PrivateOnly()
                .Do(async e =>
                {
                    if (hangman == null || !hangman.active)
                    {
                        hangman = new Data.Session.Hangman(e.Args[0], int.Parse(e.Args[1]));
                        await e.User.SendMessage("Done!");
                        Channel message = _client.GetServer(ulong.Parse(e.Args[2])).GetChannel(ulong.Parse(e.Args[3]));
                        await message.SendMessage($"{e.User.Name} started a session of hangman!\n\nParticipate by using the **!hangman guess** command!\n\n{hangman.hidden} ({e.Args[1]} false tries allowed)");
                    }
                    else
                    {
                        await e.User.SendMessage("Currently in use, sorry!");
                    }
                });

                group.CreateCommand("guess")
                .Description("Guess a character")
                .Parameter("Guess")
                .Do(async e =>
                {
                    if (hangman.active)
                    {
                        string output = "";

                        if (e.Args[0].Length == hangman.word.Length)
                        {
                            output = hangman.solve(e.Args[0], e.User);
                        }

                        else
                        {
                            output = hangman.input(e.Args[0].ToCharArray()[0], e.User);
                        }

                        await e.Channel.SendMessage(output);
                    }
                    else
                    {
                        await e.Channel.SendMessage("No session of hangman running, sorry!");
                    }
                });
            });

            manager.CreateCommands("ranking", group =>
            {
                group.PublicOnly();

                group.CreateCommand("Score")
                .Description("get the top scoreboard")
                .Parameter("(true) to get global ranking", ParameterType.Optional)
                .Do(async e =>
                {
                    List <Data.User.User> tempSort = userScores.users.OrderByDescending(u => u.Score).ToList();

                    string output = "";

                    if (e.Args[0] == "")
                    {
                        int count = 0;

                        foreach (Data.User.User curUser in tempSort)
                        {
                            if (count >= 10)
                            {
                                break;
                            }
                            count++;
                            try
                            {
                                output += $"#{count} ``$ {curUser.Score} $`` by {e.Server.GetUser(curUser.ID).Name}\n";
                            }
                            catch (NullReferenceException ex)
                            {
                                count--;
                            }
                        }
                    }
                    else if (e.Args[0] == "true")
                    {
                        for (int i = 0; i < tempSort.Count; i++)
                        {
                            try
                            {
                                output += $"#{i + 1} ``$ {tempSort[i].Score} $`` by {e.Server.GetUser(tempSort[i].ID).Name}\n";
                            }
                            catch (NullReferenceException ex)
                            {
                                output += $"#{i + 1} ``$ {tempSort[i].Score} $`` by **global** {findUser(tempSort[i].ID, _client)}\n";
                            }
                        }
                    }

                    await e.Channel.SendMessage(output);
                });

                group.CreateCommand("Experience")
                .Description("get the top expboard")
                .Parameter("(true) to get global ranking", ParameterType.Optional)
                .Do(async e =>
                {
                    List <Data.User.User> tempSort = userScores.users.OrderByDescending(u => u.Experience).ToList();

                    string output = "";

                    if (e.Args[0] == "")
                    {
                        int count = 0;

                        foreach (Data.User.User curUser in tempSort)
                        {
                            if (count >= 10)
                            {
                                break;
                            }
                            count++;
                            try
                            {
                                output += $"#{count} ``{curUser.Experience} EXP`` by {e.Server.GetUser(curUser.ID).Name}\n";
                            }
                            catch (NullReferenceException ex)
                            {
                                count--;
                            }
                        }
                    }
                    else if (e.Args[0] == "true")
                    {
                        for (int i = 0; i < tempSort.Count; i++)
                        {
                            try
                            {
                                output += $"#{i + 1} ``{tempSort[i].Experience} EXP`` by {e.Server.GetUser(tempSort[i].ID).Name}\n";
                            }
                            catch (NullReferenceException ex)
                            {
                                output += $"#{i + 1} ``{tempSort[i].Experience} EXP`` by **global** {findUser(tempSort[i].ID, _client)}\n";
                            }
                        }
                    }

                    await e.Channel.SendMessage(output);
                });

                group.CreateCommand("Level")
                .Description("get the top levelboard")
                .Parameter("(true) to get global ranking", ParameterType.Optional)
                .Do(async e =>
                {
                    List <Data.User.User> tempSort = userScores.users.OrderByDescending(u => u.Level).ToList();

                    string output = "";

                    if (e.Args[0] == "")
                    {
                        int count = 0;

                        foreach (Data.User.User curUser in tempSort)
                        {
                            if (count >= 10)
                            {
                                break;
                            }
                            count++;
                            try
                            {
                                output += $"#{count} ``Level {curUser.Level}`` by {e.Server.GetUser(curUser.ID).Name}\n";
                            }
                            catch (NullReferenceException ex)
                            {
                                count--;
                            }
                        }
                    }
                    else if (e.Args[0] == "true")
                    {
                        for (int i = 0; i < tempSort.Count; i++)
                        {
                            try
                            {
                                output += $"#{i + 1} ``Level {tempSort[i].Level}`` by {e.Server.GetUser(tempSort[i].ID).Name}\n";
                            }
                            catch (NullReferenceException ex)
                            {
                                output += $"#{i + 1} ``Level {tempSort[i].Level}`` by **global** {findUser(tempSort[i].ID, _client)}\n";
                            }
                        }
                    }

                    await e.Channel.SendMessage(output);
                });
            });
        }
示例#27
0
        private void FollowRest()
        {
            ChatterBotFactory factory = new ChatterBotFactory();

            ChatterBot        CleverBot      = factory.Create(ChatterBotType.CLEVERBOT);
            ChatterBotSession ChatBotSession = CleverBot.CreateSession();
            string            s;
            string            a;
            string            b;
            string            from;
            int marker;

            while (Globals.gamedata.running)
            {
                breaktotop = false;
                //moved sleep to the top for when breaking to top
                Thread.Sleep(Globals.SLEEP_FollowRestThread); //500, this thread don't need to be very responsive.


                //check if botting is on, and we are in game by having sent the EW packet.
                if (Globals.gamedata.BOTTING && Globals.enterworld_sent)
                {
                    if (!breaktotop && Script_Ops.COUNT("NPC_TARGETME") == 0 && Script_Ops.COUNT("NPC_PARTYTARGETED") == 0 && (Globals.gamedata.botoptions.FollowRest == 1) && (Globals.gamedata.botoptions.FollowRestID != 0))
                    {
                        FollowRestInternal();
                    }

                    if (!breaktotop && Globals.gamedata.botoptions.SendParty == 1)
                    {
                        AutoInvitePartyMembers();
                    }
                    if (!breaktotop && Globals.gamedata.botoptions.LeavePartyOnLeader == 1)
                    {
                        CheckPartyLeader();
                    }
                }


                if (Globals.gamedata.LocalChatQueue.Count > 0)
                {
                    if (Globals.gamedata.autoreply)
                    {
                        s      = Globals.gamedata.LocalChatQueue.Dequeue().ToString();
                        marker = s.IndexOf(':');
                        try
                        {
                            from = s.Substring(0, marker);
                        }
                        catch
                        {
                            from = "";
                        }

                        if (from.CompareTo(Globals.gamedata.my_char.Name) != 0)
                        {
                            s = s.Remove(0, marker + 2); //string message = from + ": " + text;

                            a = ChatBotSession.Think(s);

                            b = a.ToUpperInvariant();


                            if ((!String.IsNullOrEmpty(a)) && !b.Contains("CLEVERBOT"))
                            {
                                ServerPackets.Send_Text(0, ChatBotSession.Think(s));
                            }
                        }
                    }
                    else
                    {
                        //clear queue in case it wasn't empty when toggle autoreply button was clicked
                        Globals.gamedata.LocalChatQueue.Dequeue();
                    }
                }

                if (Globals.gamedata.PrivateMsgQueue.Count > 0)
                {
                    try
                    {
                        if (Globals.gamedata.autoreplyPM)
                        {
                            s      = Globals.gamedata.PrivateMsgQueue.Dequeue().ToString();
                            marker = s.IndexOf(':');
                            try
                            {
                                from = s.Substring(0, marker);
                            }
                            catch
                            {
                                from = "";
                            }
                            if (from.CompareTo(Globals.gamedata.my_char.Name) != 0)
                            {
                                s = s.Remove(0, marker + 2);

                                a = ChatBotSession.Think(s);

                                b = a.ToUpperInvariant();

                                if ((!String.IsNullOrEmpty(a)) && !b.Contains("CLEVERBOT"))
                                {
                                    ServerPackets.Send_Text(2, from + " " + a);
                                }
                            }
                        }
                        else
                        {
                            //clear queue in case it wasn't empty when toggle autoreply button was clicked
                            Globals.gamedata.PrivateMsgQueue.Dequeue();
                        }
                    }
                    catch
                    {
                    }
                }
            }
        }
示例#28
0
 private void InitBot()
 {
     _chatterBot = new ChatterBotFactory().Create(ChatterBotType.PANDORABOTS, "b0dafd24ee35a477").CreateSession();
 }
示例#29
0
        static void Main(string[] args)
        {
            Console.WriteLine("Started!!");
            Console.Title = "Skype Toolkit";

            Skype skype = new Skype();

            skype.Attach(7, false);

            List <string> allcontacts = new List <string>();
            List <string> blacklist;

            bool containsuser;

            //add all contacts to a list
            foreach (User user in skype.Friends)
            {
                allcontacts.Add(user.Handle);
            }

            //check if the blacklist file exists. If it does not, it creates it and loads its contents into a list
            try
            {
                blacklist = File.ReadLines("blacklist.txt").ToList();
            }
            catch
            {
                Console.WriteLine("Blacklist failed to load!\nCreating new one");
                using (StreamWriter sw = File.CreateText("blacklist.txt"))
                    sw.Close();
            }
            finally
            {
                blacklist = File.ReadLines("blacklist.txt").ToList();
                Console.WriteLine("Blacklist loaded");
                Thread.Sleep(1000);
            }
            #region s
            while (1 < 2)
            {
                Console.Clear();
                Console.WriteLine("watdo?\n1. Send Message\n2. Clever Responses\n3. Change Mood\n4. Spam status\n5. Add user to blacklist\n6. Remove user from blacklist\n7. Show blacklist\n8. List Contacts\n9. Interpret commands\n\n99. Exit");
                int choice;
                if (int.TryParse(Console.ReadLine(), out choice))
                {
                    switch (choice)
                    {
                    case 1:
                        //send message
                        Console.WriteLine("You have selected \"Send Message\"\nPlease enter a contact: ");
                        string contacttosend = Console.ReadLine();
                        Console.WriteLine("Please enter message: ");
                        string messagetosend = Console.ReadLine();
                        SendMessage(contacttosend, messagetosend);
                        break;

                    case 2:
                        //respond to unread messages with cleverbot's replies
                        Console.WriteLine("You have selected \"Cleverbot Replies\"\n\nPress any key to stop.");
                        //TODO: add option to choose whcih service to use
                        ChatterBotFactory factory     = new ChatterBotFactory();
                        ChatterBot        bot1        = factory.Create(ChatterBotType.CLEVERBOT);
                        ChatterBotSession bot1session = bot1.CreateSession();

                        while (!Console.KeyAvailable)
                        {
                            foreach (IChatMessage msg in skype.MissedMessages)
                            {
                                if (!blacklist.Contains(msg.Sender.Handle))
                                {
                                    try
                                    {
                                        Console.WriteLine("Message received from [" + msg.Sender.Handle + "]\n");
                                        msg.Seen = true;
                                        Console.WriteLine("Message: [" + msg.Body + "]\n");
                                        string reply = "bot> " + bot1session.Think(msg.Body);
                                        Console.WriteLine("Reply: [" + reply + "]\n");
                                        SendMessage(msg.Sender.Handle, reply);
                                    }
                                    catch (Exception e)
                                    {
                                        //usually a timeout
                                        Console.WriteLine("Timed out..\n\n" + e);
                                    }
                                }
                                else
                                {
                                    Console.WriteLine("\nUser is on blacklist. ABORT!!1\n");         //ext0
                                    msg.Seen = true;
                                }
                            }
                        }
                        break;

                    case 3:
                        //change skype mood
                        Console.WriteLine("You have selected \"Change Mood\"\nPlease enter new status:");
                        string status = Console.ReadLine();
                        skype.CurrentUserProfile.MoodText = status;
                        break;

                    case 4:
                        //spam skype status
                        Console.WriteLine("You have selected \"Spam Status\"\nPress any key to stop.");
                        int c = 0;
                        while (!Console.KeyAvailable)
                        {
                            if (c == 0)
                            {
                                skype.ChangeUserStatus(TUserStatus.cusOnline);
                            }
                            else if (c == 1)
                            {
                                skype.ChangeUserStatus(TUserStatus.cusAway);
                            }
                            else if (c == 2)
                            {
                                skype.ChangeUserStatus(TUserStatus.cusDoNotDisturb);
                            }
                            else if (c == 3)
                            {
                                skype.ChangeUserStatus(TUserStatus.cusInvisible); c = -1;
                            }

                            c++;        //hehehehehe
                        }
                        break;

                    case 5:
                        //add user to blacklist
                        Console.WriteLine("You have selected \"Add user to blacklist\".\nPlease enter username:"******"blacklist.txt").Contains(usertoadd);

                        if (!containsuser == true)
                        {
                            TextWriter tw = new StreamWriter("blacklist.txt");
                            blacklist.ForEach(tw.WriteLine);
                            tw.Close();
                            Console.WriteLine("Added user to blacklist.");
                        }
                        else
                        {
                            Console.WriteLine("User is already blacklisted.");
                        }

                        break;

                    case 6:
                        //remove user from blacklist
                        Console.WriteLine("You have selected \"Remove user from blacklist\".\nPlease enter username:"******"blacklist.txt").Contains(usertoremove);
                        if (containsuser == true)
                        {
                            blacklist.Remove(usertoremove);
                            File.WriteAllLines(("blacklist.txt"), blacklist.ToList());
                            Console.WriteLine("User removed from blacklist.");
                        }
                        else
                        {
                            Console.WriteLine("User is not on blacklist.");
                        }
                        break;

                    case 7:
                        //display blacklist to user
                        Console.WriteLine("\n");
                        blacklist.ForEach(i => Console.WriteLine("{0}", i));
                        Console.WriteLine("\n");
                        break;

                    case 8:
                        //display all contacts to user


                        int n = 1;
                        Console.WriteLine("\n");
                        allcontacts.ForEach(i => Console.WriteLine("{0} {1}", n++, i));
                        Console.WriteLine("\n");
                        break;

                    case 9:
                        //commands
                        Console.Clear();
                        Console.WriteLine("Waiting for commands.");
                        while (!Console.KeyAvailable)
                        {
                            foreach (IChatMessage msg in skype.MissedMessages)
                            {
                                string trigger = "!";

                                if (!blacklist.Contains(msg.Sender.Handle) && msg.Body.IndexOf(trigger) == 0)
                                {
                                    msg.Seen = true;
                                    string command = msg.Body.Remove(0, trigger.Length).ToLower();
                                    string message;

                                    if (command == "time")
                                    {
                                        message = DateTime.Now.ToLongTimeString();
                                    }
                                    else if (command == "date")
                                    {
                                        message = DateTime.Now.ToLongDateString();
                                    }
                                    else if (command == "about")
                                    {
                                        message = "made by yars 2016 and such and such. https://rootme.tk";
                                    }
                                    else if (command == "help")
                                    {
                                        message = "Commands include:\n!help - Shows this message\n!time - shows current time (local to this program)\n!date - Shows current date\n!about - Shows about info\n!int2binary - Convert integers to binary\n!binary2int - Convert binary to integers\n!catfacts\n!blacklist - Add yourself to blacklist\n!collatzcon - THE SYNTAX IS !collatzcon number\n!stallman";
                                    }
                                    #endregion
                                    else if (command == "stallman")
                                    {
                                        //get a list of rms qoutes and tell them to the user
                                        List <String> stallman = File.ReadAllLines("stallman.txt").ToList();
                                        Random        r        = new Random();
                                        int           i        = r.Next(stallman.Count);
                                        message = stallman[i];
                                    }
                                    else if (command == "blacklist")
                                    {
                                        usertoadd    = msg.Sender.Handle;
                                        containsuser = File.ReadLines("blacklist.txt").Contains(usertoadd);
                                        if (!containsuser == true)
                                        {
                                            blacklist.Add(msg.Sender.Handle);
                                            message = "Added to blacklist.";
                                            TextWriter tw = new StreamWriter("blacklist.txt");
                                            blacklist.ForEach(tw.WriteLine);
                                            tw.Close();
                                            Console.WriteLine("Added user to blacklist.");
                                        }
                                        else
                                        {
                                            message = "This should never be seen by user..";
                                        }
                                    }
                                    else if (command == "catfact")
                                    {
                                        CatFacts(msg.Sender.Handle);
                                        message = " ";
                                    }
                                    else                                                  //magic dont touch. seriously.
                                    {
                                        try                                               //not the most elegant solution
                                        {
                                            if (command.Substring(0, 10) == "int2binary") //this usually breaks so dont scare it
                                            {
                                                string inttoconvert = command.Substring(10, command.Length - 10);
                                                string binary       = Convert.ToString(Convert.ToInt32(inttoconvert), 2);

                                                message = inttoconvert + " in binary is: " + binary;
                                            }
                                            else if (command.Substring(0, 10) == "binary2int")     //dont scare this guy too
                                            {
                                                string bits            = command.Substring(11, command.Length - 11);
                                                int    convertedbinary = Convert.ToInt32(bits, 2);
                                                message = bits + " in decimal is: " + convertedbinary.ToString();
                                            }
                                            else if (command.Substring(0, 10) == "collatzcon")     //Collatz conjecture
                                            {
                                                int number = int.Parse(command.Substring(11, command.Length - 11));
                                                c = 1;
                                                string premessage = number.ToString();

                                                if (number > 0)
                                                {
                                                    do
                                                    {
                                                        if (number % 2 == 0)     //even
                                                        {
                                                            number = number / 2;
                                                        }
                                                        else     //odd
                                                        {
                                                            number = number * 3 + 1;
                                                        }
                                                        c++;     //hehehe i gotta stop
                                                        premessage += ", " + number;
                                                    } while (number != 1);

                                                    message = premessage + "\nThat took " + c + " iterations.";
                                                }
                                                else
                                                {
                                                    message = "Input must be a positive integer.";
                                                }
                                            }
                                            else
                                            {
                                                message = "Unknown Command";
                                            }
                                        }
                                        catch (Exception)
                                        {
                                            message = "Unknown Command";
                                        }
                                    }

                                    Console.WriteLine(msg.Sender.Handle + " >> " + command);
                                    SendMessage(msg.Sender.Handle, message);
                                }
                            }
                        }
                        break;

                    case 99:
                        Environment.Exit(0);
                        break;
                    }
                    Console.WriteLine("Press Any Key to Continue...");
                    Console.ReadKey();
                }
            }
        }
示例#30
0
        private void talkToBotToolStripButton_Click(object sender, EventArgs e)
        {
            session = bot.CreateSession();

            if (currentConversation == null)
                beginConversation();
        }
示例#31
0
 /// <summary>
 /// Handles the Click event of the restartBotToolStripMenuItem control.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 private void restartBotToolStripMenuItem_Click(object sender, EventArgs e)
 {
     session = bot.CreateSession();
 }
示例#32
0
        /// <summary>
        /// Handles the Connected event of the omegle class.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void omegle_Connected(object sender, EventArgs e)
        {
            SetStatus("Connected.", false);

            session = bot.CreateSession();

            beginConversation();

            if (botStartsConversationToolStripMenuItem.Checked)
            {
                omegle_MessageReceived(null, new MessageReceivedArgs(string.Empty));
            }
        }
示例#33
0
        /// <summary>
        /// Handles the Click event of the botsSeltPandoraBotToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void botsSeltPandoraBotToolStripMenuItem_Click(object sender, EventArgs e)
        {
            using (PandoraBotSelectionForm sel_form = new PandoraBotSelectionForm())
            {
                sel_form.ShowDialog(this);

                if (sel_form.BotId == null || sel_form.BotName == null)
                    return;

                bot = factory.Create(ChatterBotType.PANDORABOTS, sel_form.BotId);
                session = bot.CreateSession();

                currentbotToolStripButton.Image = botSelPandoraBotToolStripMenuItem.Image;
                currentbotToolStripButton.Text = sel_form.BotName;

                botStartsConversationToolStripMenuItem.Checked = false;
                botStartsConversationToolStripMenuItem.Enabled = false;
            }
        }
示例#34
0
        /// <summary>
        /// Handles the Click event of the botSelSensationBotToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void botSelSensationBotToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (sender != null && sender != botSelSensationBotToolStripMenuItem)
            {
                ToolStripItem control = sender as ToolStripItem;

                switch (control.Tag.ToString())
                {
                    case "general": bot = new SensationBot(SensationBot.BotType.GeneralChat); break;
                    case "romantic": bot = new SensationBot(SensationBot.BotType.Romantic, 0); break;
                    case "romantic2": bot = new SensationBot(SensationBot.BotType.Romantic, 1); break;
                    case "smacktalk": bot = new SensationBot(SensationBot.BotType.SmackTalk); break;
                    case "adult1": bot = new SensationBot(SensationBot.BotType.AdultM2F); break;
                    case "adult2": bot = new SensationBot(SensationBot.BotType.AdultF2M); break;
                    case "adult3": bot = new SensationBot(SensationBot.BotType.AdultL); break;
                    case "adult4": bot = new SensationBot(SensationBot.BotType.AdultG); break;
                    default: break;
                }

                currentbotToolStripButton.Image = botSelSensationBotToolStripMenuItem.Image;
                currentbotToolStripButton.Text = botSelSensationBotToolStripMenuItem.Text.TrimEnd('.');

                session = bot.CreateSession();
            }
        }
示例#35
0
文件: Main.cs 项目: dfk789/dot-omegle
        /// <summary>
        /// Handles the Click event of the botSelCleverbotToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void botSelCleverbotToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bot = factory.Create(ChatterBotType.CLEVERBOT);
            session = bot.CreateSession();

            currentbotToolStripButton.Image = botSelCleverbotToolStripMenuItem.Image;
            currentbotToolStripButton.Text = botSelCleverbotToolStripMenuItem.Text;
        }
示例#36
0
 public BotHandler()
 {
     bot     = null;
     session = null;
     ready   = false;
 }
示例#37
0
 public void startCleverbot()
 {
     factory = new ChatterBotFactory();
     robot   = factory.Create(ChatterBotType.CLEVERBOT);
     session = robot.CreateSession();
 }
示例#38
0
 public RynoxxUserHandler(Bot bot, SteamID sid)
     : base(bot, sid)
 {
     Bot.GetInventory();
     Bot.GetOtherInventory(OtherSID);
     CleverBot = BotFactory.Create(ChatterBotType.CLEVERBOT);
     CleverBotSession = CleverBot.CreateSession();
 }
示例#39
0
文件: Chatbot.cs 项目: GGulati/IRCBot
 public ConversationState(Chatbot bot, ChatterBotType type)
 {
     botType = type;
     session = bot.CreateSession(type);
     this.bot = bot;
 }
示例#40
0
文件: Chatbot.cs 项目: GGulati/IRCBot
 public Reply(IPluginHost host, Meebey.SmartIrc4net.IrcMessageData msg, ChatterBotSession session, string query)
 {
     this.host = host;
     this.msg = msg;
     this.session = session;
     this.query = query;
 }
示例#41
0
文件: IrcBot.cs 项目: Zhangerr/pulse
        static void Main(string[] args)
        {
            try
            {
                Utils.loadPlugin();
                /*Console.WriteLine("try");
                Console.WriteLine(Commands.commands.Count);
                Console.ReadKey();
                Utils.loadPlugin();
                Console.WriteLine("loading again");
                Console.WriteLine(Commands.commands.Count);
                Console.ReadKey();*/
                NetworkStream stream;
                TcpClient irc;
                string inputLine;
                StreamReader reader;
                //   try
                //  {
                irc = new TcpClient(SERVER, PORT);
                stream = irc.GetStream();
                reader = new StreamReader(stream);
                writer = new StreamWriter(stream);
                writer.AutoFlush = true;
                writer.WriteLine(USER);
                writer.WriteLine("NICK " + NICK);
                //   Utils.join(CHANNEL);
                ChatterBotFactory factory = new ChatterBotFactory();
                ChatterBot clever = factory.Create(ChatterBotType.CLEVERBOT);
                ChatterBot jabber = factory.Create(ChatterBotType.JABBERWACKY);
                ChatterBot panda = factory.Create(ChatterBotType.PANDORABOTS, "d689f7b8de347251");
                jab = jabber.CreateSession();
                pan = panda.CreateSession();
                ses = clever.CreateSession();
                //Thread t = new Thread(new ThreadStart(oper));
                //   t.Start();
                Commands.init();
                opered = false;
                while (true)
                {
                    while ((inputLine = reader.ReadLine()) != null)
                    {

                        int numeric;
                        string noinit = inputLine.Substring(1);
                        string text = noinit.Substring(noinit.IndexOf(':') + 1);
                        string[] splitted = text.Split(' ');
                        string[] param = inputLine.Split(' ');
                        if (param.Length > 3 && (param[3].Equals("=") || param[3].Equals("@")))
                        {
                            parseUsers(param[4], inputLine);
                        }
                        // :[email protected] MODE #pulse +v Sync
                        else if (param.Length > 4 && param[1] == "MODE")
                        {
                            writer.WriteLine("WHOIS " + param[4]);
                        }
                        else if (param.Length > 1 && param[1] == "NICK")
                        {
                            string user = inputLine.Substring(1, inputLine.IndexOf('!') - 1);
                            if (users.ContainsKey(user))
                            {
                                var temp = users[user];
                                users.Remove(user);
                                users.Add(text, temp);
                                //  users.Add()
                            }
                        }
                        else if (param.Length > 3 && param[1] == "KICK")
                        {
                            string chan = param[2];
                            string user = param[3];
                            channels.Remove(chan);
                            if (user == NICK)
                            {
                                Utils.join(chan);
                            }
                            else
                            {
                                if (users.ContainsKey(user))
                                {
                                    if (users[user].ContainsKey(chan))
                                    {
                                        users[user].Remove(chan);
                                    }
                                }
                            }
                        }
                        else if (inputLine.ToLower().Contains("privmsg"))
                        {

                            string channel = inputLine.Split(' ')[2];
                            string user = inputLine.Substring(1, inputLine.IndexOf('!') - 1);
                            if (!Directory.Exists("chatlog"))
                            {
                                Directory.CreateDirectory("chatlog");
                            }
                            string date = DateTime.Now.Month + "-" + DateTime.Now.Day + "-" + DateTime.Now.Year;
                            File.AppendAllText("chatlog\\" + date + ";" + channel + ".txt", "[" + DateTime.Now.ToString() + "] <" + user + ">: " + text + "\r\n");
                            bool ispm = false;
                            if (inputLine.Split(' ')[2].Equals(NICK)) //private message
                            {
                                if (!splitted[0].StartsWith("!"))
                                {
                                    if (!pms.ContainsKey(user)) //cool bot mode but useless
                                    {
                                        pms.Add(user, panda.CreateSession());
                                    }
                                    //   writer.WriteLine("PRIVMSG " + user + " :" + pms[user].Think(text));
                                    Utils.initThink(pan, text, user);
                                }
                                ispm = true;
                            }
                            string command = splitted[0];
                            if (command.StartsWith("!"))
                            {

                                string rest = "";

                                if (command.Length > 1 && splitted.Length > 1)
                                {
                                    rest = text.Substring(command.Length + 1);
                                }
                                else
                                {
                                    rest = text;
                                }
                                command = command.ToLower();

                                //  else
                                {
                                    var cmds = Commands.commands;
                                    if (cmds.ContainsKey(command))
                                    {
                                        CommandPair cp = cmds[command];
                                        // if (users.ContainsKey(user))
                                        UserLevel lvl = Utils.getUserLevel(user, ispm ? "#pulse" : channel);
                                        if (lvl >= cp.ci.level)
                                        {
                                            if (splitted.Length >= cp.ci.args)
                                            {
                                                cp.exe(new CommandParams(ispm ? user : channel, user, rest, inputLine, splitted, writer, lvl));
                                                msg("#services", command + " executed by " + user + " on " + (ispm ? user : channel));
                                            }
                                            else
                                            {
                                                msg(ispm ? user : channel, "Not enough parameters! " + command + " requires " + cp.ci.args + " arguments");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        else if (inputLine.StartsWith("PING"))
                        {
                            writer.WriteLine("PONG " + inputLine.Split(' ')[1]);
                        }
                        else if (param.Length > 2 && (param[1] == "JOIN" || param[1] == "PART"))
                        {

                            if (inputLine.Split('!')[0].Substring(1).Equals(NICK))
                            {
                                string channel = param[2].Substring(1);
                                if (param[1] == "JOIN")
                                {

                                    Utils.admin(channel);
                                    channels.Add(channel.ToLower());
                                }
                                else
                                {
                                    channels.Remove("#" + channel.ToLower()); //for some reason no leading : when part
                                }
                            }
                        }
                        else if (param.Length > 3 && Int32.TryParse(param[1], out numeric))
                        {
                            if (numeric == 322) //channel listing
                            {
                                if (!noJoin.Contains(param[3].ToLower()))
                                {
                                    Utils.join(param[3]);
                                }
                            }
                            else if (numeric == 376) //end of motd
                            {
                                if (!opered)
                                {
                                    oper();
                                    opered = true;
                                }
                                //>> :exp.ulse.net 319 alex Sync :+#pulse #touhou ~#sync #minecraft
                            }
                            else if (numeric == 319) //whois channel list
                            {
                                string user = param[3];
                                string[] channels = text.Split(' ');
                                foreach (string s in from i in channels where !string.IsNullOrWhiteSpace(i) select i)
                                {
                                    UserLevel toAdd = UserLevel.NORMAL;
                                    switch (s[0])
                                    {
                                        case '+':
                                            toAdd = UserLevel.VOICE;
                                            break;
                                        case '%':
                                            toAdd = UserLevel.HOP;
                                            break;
                                        case '@':
                                            toAdd = UserLevel.OP;
                                            break;
                                        case '~':
                                            toAdd = UserLevel.OWNER;
                                            break;
                                        case '&':
                                            toAdd = UserLevel.ADMIN;
                                            break;
                                    }
                                    string channame = s;
                                    if (toAdd != UserLevel.NORMAL)
                                    {
                                        channame = channame.Substring(1); //getrid of symbol if  special status
                                        if (users.ContainsKey(user))
                                        {
                                            if (users[user].ContainsKey(channame))
                                            {
                                                users[user][channame] = toAdd;
                                            }
                                            else
                                            {
                                                users[user].Add(channame, toAdd);
                                            }
                                        }
                                        else
                                        {
                                            users.Add(user, new Dictionary<string, UserLevel>());
                                            users[user].Add(channame, toAdd);
                                        }
                                    }
                                    else
                                    {
                                        if (users.ContainsKey(user))
                                        {
                                            if (users[user].ContainsKey(channame))
                                            {
                                                users[user].Remove(channame);
                                                if (users[user].Count == 0)
                                                {
                                                    users.Remove(user);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        //if (!(inputLine.EndsWith("JOIN :" + CHANNEL) || inputLine.EndsWith("QUIT")))
                        {
                            Console.WriteLine(inputLine);
                        }
                    }
                    // Close all streams
                    writer.Close();
                    reader.Close();
                    irc.Close();
                }
            }
            catch (Exception e)
            {
                // Show the exception, sleep for a while and try to establish a new connection to irc server
                Console.WriteLine(e.StackTrace);
                Console.WriteLine(e.InnerException);
                Console.WriteLine(e);
                Thread.Sleep(5000);
                string[] argv = { };
                Console.WriteLine("restarting");
                Main(argv);
            }
        }
示例#42
0
        /// <summary>
        /// Handles the Click event of the botSelJabberwackyToolStripMenuItem control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void botSelJabberwackyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bot = factory.Create(ChatterBotType.JABBERWACKY);
            session = bot.CreateSession();

            currentbotToolStripButton.Image = botSelJabberwackyToolStripMenuItem.Image;
            currentbotToolStripButton.Text = botSelJabberwackyToolStripMenuItem.Text;

            botStartsConversationToolStripMenuItem.Enabled = true;
        }