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); } }
private void _recognizeSpeechAndMakeSureTheComputerSpeaksToYou_SpeechRecognized(object sender, SpeechRecognizedEventArgs e) { var s = bot2session.Think(e.Result.Text); using (var speechSynthesizer = new SpeechSynthesizer()) { speechSynthesizer.Speak(s); } manualResetEvent.Set(); }
public override void Use(SteamID room, SteamID sender, string[] args) { Thread T = new Thread(() => { string response = cleverBotSession.Think(string.Join(" ", args)); Chat.Send(room, response); }); T.Start(); }
public string getResponse(string input) { try { connectedToCleverBot = true; return(session.Think(input)); } catch (Exception e) { connectedToCleverBot = false; return("Error: " + e.Message); } }
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); } }
public string Think(string message) { try { if ((DateTime.Now - lastBotResponse).TotalMinutes > 5) { InitBot(); } return(_chatterBot.Think(message)); } catch (Exception) { return(null); } }
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); }
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..."); } }
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); } }
private string GetMessageNewMethod(Message msg) { lastTry = DateTime.UtcNow; string message = null; try { while (true) { message = WebUtility.HtmlDecode(botSession.Think(msg.Content)); if (badMessages.IsMatch(message)) { Console.WriteLine("Skipped thought: " + message); } else { quotaReached = false; break; } } } catch (Exception ex) { if (ex.Message.Contains("403")) { Console.WriteLine("API quota reached."); quotaReached = true; } else { Console.WriteLine(ex); } return(null); } return(message); }
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; } } }
void CallEvents() { string events = CallEvent(); if (events != "null") { dynamic eventsj = DynamicJson.Parse(events); if ((string)eventsj[0][0] == "connected") { connected = true; l("Connected, waiting for message..."); /*string msg = "Merry Christmas!"; * StartTyping(); * TryUseDelay(msg); * SendMessage(msg); * StopTyping();*/ } while (connected) { events = CallEvent(); eventsj = DynamicJson.Parse(events); if (events != "null") { if (eventsj[0][0] == "gotMessage") { setIsntTyping(); l("Stranger: " + eventsj[0][1]); string response = null; try { response = botsession.Think(eventsj[0][1]); } catch { l("Error! Respond yourself."); } StartTyping(); if (botResponding) { if (eventsj[0][1].Contains("kik")) { response = "I don't have a kik account."; TryUseDelay(response); SendMessage(response); } else if (eventsj[0][1].Contains("whatsapp")) { response = "I don't have whatsapp."; TryUseDelay(response); SendMessage(response); } else if (eventsj[0][1].Contains("snapchat") || eventsj[0][1].Contains("snap chat")) { response = "I don't have a snapchat."; TryUseDelay(response); SendMessage(response); } else if (eventsj[0][1].Contains("skype")) { response = "I don't have a skype."; TryUseDelay(response); SendMessage(response); } else if (eventsj[0][1].Contains("instagram")) { response = "I don't have an instagram."; TryUseDelay(response); SendMessage(response); } else if (eventsj[0][1].Contains("askfm")) { response = "I don't have an askfm."; TryUseDelay(response); SendMessage(response); } else if (eventsj[0][1].Contains("twitter")) { response = "I don't have a twitter."; TryUseDelay(response); SendMessage(response); } else { if (response != null) { response = HtmlRemoval.StripTagsCharArray(response); bool doPrompt = false; foreach (string str in promptList) { if (response.Contains(str)) { doPrompt = true; break; } } if (doPrompt) { AskPrompt(response); } else { for (int i = 0; i < overrideArray.Length; i++) { if (response.Contains(overrideArray[i])) { response = response.Replace(overrideArray[i], overrideArray[i + 1]); } i++; } foreach (string str in afterPromptList) { if (response.Contains(str)) { doPrompt = true; break; } } if (doPrompt) { AskPrompt(response); } else { if (response.Contains(" ")) { List <String> msgs = Regex.Split(response, " ").ToList <String>(); foreach (String msg in msgs) { TryUseDelay(response); SendMessage(msg); } } else { TryUseDelay(response); SendMessage(response); } } } } } StopTyping(); } } else if (eventsj[0][0] == "strangerDisconnected") { setIsntTyping(); connected = false; l("Stranger disconnected."); if (AutoReConnect) { button1.Invoke(new MethodInvoker(delegate() { button1.PerformClick(); })); } } else if (eventsj[0][0] == "typing") { setIsTyping(); } else if (eventsj[0][0] == "stoppedTyping") { setIsntTyping(); } else { l("Unknown events: " + eventsj[0][0]); } } Thread.Sleep(1000); } } }
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 { } } } }
private static async void TBot_OnMessage(object sender, Telegram.Bot.Args.MessageEventArgs messageEventArgs) { var message = messageEventArgs.Message; try { if (message == null || message.Type != MessageType.Text) { return; } Console.WriteLine("Chat ID: " + message.Chat.Id); Console.WriteLine(string.Format("Message from {0} {1} in chat {2}\nMessagee is: {3}", message.From.Username, message.From.Id, message.Chat.Title, message.Text)); if (chatBotEnabled) { bool isNormalchat = true; if (message.Text.StartsWith("!")) { isNormalchat = false; } if (isNormalchat) { try { if (message.Text.ToLower().Contains(botNick.ToLower())) { message.Text = Regex.Replace(message.Text.ToLower(), botNick.ToLower(), "ALICE", RegexOptions.IgnoreCase); } string botReply = chatBotSession.Think(message.Text); // lets mask the bot name shall we if (botReply.Contains("ALICE")) { botReply = Regex.Replace(botReply, "ALICE", botNick, RegexOptions.IgnoreCase); } await SendMsgToTelegram(message.Chat.Id, botReply); Console.WriteLine("chatBotReply to {0}: is {1}", message.Chat.Id, botReply); } catch (Exception ex) { Console.WriteLine(new ExceptionTBotChatBotReply(ex.Message)); await SendMsgToTelegram(message.Chat.Id, (new ExceptionTBotChatBotReply(ex.Message)).ToString()); } } } if (Regex.Match(message.Text.ToLower(), "!" + TBotCommand.HELP.ToString().ToLower()).Success&& listUsers.Exists(x => x.Username == message.From.Username && x.IsAdmin)) { ResourceSet helpResources = HelpResources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); StringBuilder helpMsg = new StringBuilder(); foreach (DictionaryEntry entry in helpResources) { helpMsg.AppendLine(string.Format(entry.Value.ToString() + Environment.NewLine)); } await SendMsgToTelegram(message.Chat.Id, helpMsg.ToString()); } else if (Regex.Match(message.Text.ToLower(), "!" + TBotCommand.CHATBOT.ToString().ToLower()).Success&& listUsers.Exists(x => x.Username == message.From.Username && x.IsAdmin)) { chatBotEnabled = !chatBotEnabled; if (chatBotEnabled) { await SendMsgToTelegram(message.Chat.Id, TBotStrings.EnabledChatBot); } else { await SendMsgToTelegram(message.Chat.Id, TBotStrings.DisabledChatbot); } } else if ((eval = Regex.Match(message.Text, "!" + TBotCommand.GOOGLE.ToString().ToLower() + "\\s{1,}(.{1,100})", RegexOptions.IgnoreCase)) != null && eval.Success) { string query = eval.Groups[1].ToString(); // se nos derem ping, dizemos isso e feio GoogleSearchResults result = await GoogleSearch(query); await SendMsgToTelegram(message.Chat.Id, "You have searched for: " + query); if (result != null) { await SendMsgToTelegram(message.Chat.Id, "Search time was: " + result.SearchTime); await SendMsgToTelegram(message.Chat.Id, "Total items found: " + result.TotalResults); if (result.Results.Count > 0) { foreach (var item in result.Results) { await SendMsgToTelegram(message.Chat.Id, "Title: " + item.Title); await SendMsgToTelegram(message.Chat.Id, "Link: " + item.Link); } } else if (result.Results.Count == 0 && result.TotalResults > 0) { await SendMsgToTelegram(message.Chat.Id, string.Format("Something not right, we have {0} search hits, but the list of results is empty", result.TotalResults)); } } } else if ((eval = Regex.Match(message.Text, "!" + TBotCommand.SQLGETUSERS.ToString().ToLower(), RegexOptions.IgnoreCase)) != null && eval.Success && listUsers.Exists(x => x.Username == message.From.Username && x.IsAdmin)) { listUsers = db.GetUserList(); foreach (TBotUser user in listUsers) { await SendMsgToTelegram(message.Chat.Id, string.Format(TBotStrings.TBotUsersChatMSG, user.ID, Environment.NewLine, user.Username, Environment.NewLine, user.IsAdmin.ToString())); } } else if ((eval = Regex.Match(message.Text, "!" + TBotCommand.SQLINSERTUSER.ToString().ToLower() + "\\s+(.*)\\s+(.*)", RegexOptions.IgnoreCase)) != null && eval.Success && listUsers.Exists(x => x.Username == message.From.Username && x.IsAdmin)) { string user = string.Empty; bool isAdmin = false; if (!string.IsNullOrEmpty(eval.Groups[1].ToString())) { user = eval.Groups[1].ToString(); } else { await SendMsgToTelegram(message.Chat.Id, TBotStrings.TBotNewUserParameterMising); return; } if (!string.IsNullOrEmpty(eval.Groups[2].ToString())) { if (eval.Groups[2].ToString().ToLower().Equals("true")) { isAdmin = true; } await SendMsgToTelegram(message.Chat.Id, string.Format(TBotStrings.TBotNewUserCreted, db.InsertUser(user, isAdmin))); } else { await SendMsgToTelegram(message.Chat.Id, TBotStrings.TBotNewUserParameterMising); return; } listUsers = db.GetUserList(); } else if ((eval = Regex.Match(message.Text, "!" + TBotCommand.SQLREMOVEUSER.ToString().ToLower() + "\\s+(.*)", RegexOptions.IgnoreCase)) != null && eval.Success && listUsers.Exists(x => x.Username == message.From.Username && x.IsAdmin)) { if (!string.IsNullOrEmpty(eval.Groups[1].ToString())) { int id = 0; if (int.TryParse(eval.Groups[1].ToString(), out id)) { await SendMsgToTelegram(message.Chat.Id, string.Format(TBotStrings.TBotUserIDRemoved, id, db.RemoveUser(id).ToString())); } else { string user = eval.Groups[1].ToString(); await SendMsgToTelegram(message.Chat.Id, string.Format(TBotStrings.TBotUserNameRemoved, user, db.RemoveUser(user).ToString())); } } else { await SendMsgToTelegram(message.Chat.Id, TBotStrings.TBotCMDArgumentMissing); return; } listUsers = db.GetUserList(); } else if ((eval = Regex.Match(message.Text, "!" + TBotCommand.SQLUPDATEUSER.ToString().ToLower() + "\\s+(.*)\\s+(.*)", RegexOptions.IgnoreCase)) != null && eval.Success && listUsers.Exists(x => x.Username == message.From.Username && x.IsAdmin)) { if (!string.IsNullOrEmpty(eval.Groups[1].ToString()) && !string.IsNullOrEmpty(eval.Groups[2].ToString())) { int id = 0; if (int.TryParse(eval.Groups[1].ToString(), out id)) { bool isAdmin = false; if (bool.TryParse(eval.Groups[2].ToString(), out isAdmin)) { await SendMsgToTelegram(message.Chat.Id, string.Format(TBotStrings.TBotUserUpdated, db.UpdateUser(id, isAdmin).Result)); } else { await SendMsgToTelegram(message.Chat.Id, string.Format(TBotStrings.TBotUserUpdated, false)); } } } else { await SendMsgToTelegram(message.Chat.Id, TBotStrings.TBotCMDWrongArg); return; } listUsers = db.GetUserList(); } } catch (ExceptionGoogleResultItemsNULL ex) { Console.WriteLine(ex.Message); await SendMsgToTelegram(message.Chat.Id, ex.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); await SendMsgToTelegram(message.Chat.Id, ex.Message); } }
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("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("(true) to get global ranking", ParameterType.Optional) .Do(async e => { List <Data.Individual.User> tempSort = userScores.users.OrderByDescending(u => u.Score).ToList(); string output = ""; if (e.Args[0] == "") { int count = 0; foreach (Data.Individual.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.Individual.User> tempSort = userScores.users.OrderByDescending(u => u.Experience).ToList(); string output = ""; if (e.Args[0] == "") { int count = 0; foreach (Data.Individual.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.Individual.User> tempSort = userScores.users.OrderByDescending(u => u.Level).ToList(); string output = ""; if (e.Args[0] == "") { int count = 0; foreach (Data.Individual.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); }); }); }
}//OnFriendRemove() //GLOBALIZED /// <summary> /// Called when user sends bot a ItemRemovedMsg /// </summary> /// <param name="ItemRemovedMsg">ItemRemovedMsg sent</param> /// <param name="type">type of ItemRemovedMsg</param> public override void OnMessage(string message, EChatEntryType type) { string BackupMessage = message; if (!message.StartsWith(".") && !message.StartsWith("enter")) { message = message.ToLower();//lowercase ItemRemovedMsg }//if (!ItemRemovedMsg.StartsWith(".") && !ItemRemovedMsg.StartsWith("enter")) string MessageHandled;//the sConversionResult of dealing with the ItemRemovedMsg #region AdminCommands // ADMIN commands if (IsAdmin) { MessageHandled = clsFunctions.DealWithAdminCommand(this.Bot, OtherSID, message);//Deal with the ItemRemovedMsg, or receive something back if the bot needs specific things to do. if (MessageHandled == String.Empty) { return;//message was handled like it should of been, so stop code. }//if (MessageHandled == String.Empty) if (MessageHandled == clsFunctions.AdvertiseCMD) { if (Bot.AdvertiseHandler.bStarted) { Bot.SteamFriends.SendChatMessage(OtherSID, type, "Stopping Advertisements..."); Bot.log.Success("Stopping Advertisements."); Bot.AdvertiseHandler.Stop(); } else { Bot.SteamFriends.SendChatMessage(OtherSID, type, "Starting Advertisements."); Bot.log.Success("Starting Advertisements."); Bot.AdvertiseHandler.Start(); } return; } else if (MessageHandled == clsFunctions.MetalCountCMD) { Bot.informHandler.Start(); //count bots inventory Bot.SteamFriends.SendChatMessage(OtherSID, type, Bot.informHandler.AdminStatsMessage()); //Send the results return; //stop code. }// else if (MessageHandled == clsFunctions.MetalCountCMD) }//if (IsAdmin) #endregion AdminCommands #region Responces //since admin commands were not handled or user is not an admin, check regular commands. MessageHandled = clsFunctions.DealWithCommand(Bot, OtherSID, message);//Get command results if (MessageHandled == String.Empty) { return;//message was handled in clsFunctions, so we can stop the code. }//if (MessageHandled == String.Empty) else if (MessageHandled == clsFunctions.UserClearCMD) { Bot.SteamFriends.SendChatMessage(OtherSID, type, "You don't have any items reserved..."); return; }//else if (MessageHandled == clsFunctions.UserClearCMD) else if (MessageHandled == clsFunctions.UserDonateCMD) { ChooseDonate = true; //user is donating return; //stop code }//else if (MessageHandled == clsFunctions.UserDonateCMD) else if (MessageHandled.StartsWith(Bot.BackpackUrl) && MessageHandled.Length > Bot.BackpackUrl.Length) { Bot.SteamFriends.SendChatMessage(OtherSID, type, "You don't have to reserve items! Just invite me to trade and add keys or metal to get started."); return; }//else if (MessageHandled.StartsWith(Bot.BackpackUrl) && MessageHandled.Length > Bot.BackpackUrl.Length) else if (MessageHandled == clsFunctions.UserStatusCMD) { Bot.informHandler.Start(); //Start counting inventory Bot.SteamFriends.SendChatMessage(OtherSID, type, Bot.informHandler.UserStatsMessage()); //Send the stats ItemRemovedMsg for users. return; }//else if (MessageHandled == clsFunctions.UserStatusCMD) else { if (MessageHandled != String.Empty) { string MsgToSend = clsFunctions.DealWithGenericMessage(BackupMessage, OtherSID, Bot);//See if there is a response to the general ItemRemovedMsg //Bot.SteamFriends.SendChatMessage(OtherSID, type, MsgToSend);//Send ItemRemovedMsg response if (MsgToSend == "I'm sorry. I'm a nub bot and haven't been taught to respond to that =C") { try { string BotResponceMessage = chatterBotsession.Think(BackupMessage); int icount = 0; if (BotResponceMessage.Contains("<a href=")) { BotResponceMessage = Regex.Replace(BotResponceMessage, @"<a\b[^>]+>([^<]*(?:(?!</a)<[^<]*)*)</a>", "$1"); } if (BotResponceMessage.Contains("click here!")) { BotResponceMessage = "Uhhh what?"; } if (BotResponceMessage.Contains("http://tinyurl.com/comskybot")) { BotResponceMessage = "By being yourself!"; } if (BotResponceMessage.Contains("Please click here to help protect")) { BotResponceMessage = "Bye bye!"; } if (BotResponceMessage.Contains("<br>")) { string[] splitVars = { "<br>" }; string[] newBotMsg = BotResponceMessage.Split(splitVars, StringSplitOptions.None); BotResponceMessage = newBotMsg[0]; } Bot.SteamFriends.SendChatMessage(OtherSID, type, BotResponceMessage); } catch (Exception ex) { Bot.SteamFriends.SendChatMessage(OtherSID, type, "What...?"); } //Bot.log.Success("Send bot response message of: " + BotResponceMessage); } //if (MsgToSend == "I'm sorry. I'm a nub bot and haven't been taught to respond to that =C") } //if (MessageHandled != String.Empty) } //else #endregion Responces }//OnMessage()
public void ProcessLastChatLine(string chatLine) { if (chatLine.StartsWith(">------>") || chatLine.StartsWith("3======")) { return; } if (privateMode) { string[] lineDivided = System.Text.RegularExpressions.Regex.Split(chatLine, userData.Name + ":"); if (lineDivided.Length != 2 || lineDivided[0].Contains(':')) { return; } lineDivided[0] = lineDivided[0].Trim(); lineDivided[0] = lineDivided[0].Trim('(', ')'); int targetClientNum; if (int.TryParse(lineDivided[0], out targetClientNum) && targetClientNum == userData.ClientNum) { chatLine = lineDivided[1]; } else { return; } } chatLine = chatLine.ToLower(); if (ProcessMinorCommands(chatLine)) { return; } if (chatLine.Contains("!recover")) { GetUserData(); } if (chatLine.Contains("!restrict")) { if (restrictMode) { restrictMode = false; ExecuteConsoleCommand("echo ^1Restrict mode off"); } else { restrictMode = true; ExecuteConsoleCommand("echo ^1Restrict mode on"); } } if (chatLine.Contains("!mode")) { if (privateMode) { privateMode = false; SendChatMessage("^0DU^1 - public mode on"); } else { privateMode = true; SendChatMessage("^0DU^1 - public mode off"); } } if (chatLine.Contains("!telemode")) { if (teleportMode) { teleportMode = false; SendChatMessage("^0DU^1 - teleport mode off"); } else { teleportMode = true; SendChatMessage("^0DU^1 - teleport mode on"); if (privateMode) { ExecuteConsoleCommand("echo ^1Warning! Disable private mode to let teleport mode work!"); } } } if (chatLine.Contains("me")) { if (teleportMode) { string[] lineDivided = chatLine.Split(':'); if (lineDivided.Length == 2 && lineDivided[1] == " me") { string clientIDRaw = lineDivided[0].Split(' ')[0]; string clientID = clientIDRaw.Trim('(', ')'); ExecuteConsoleCommand("gethere " + clientID); } } } if (chatLine.Contains("!translate")) { string[] lineDivided = chatLine.Split(':'); if (lineDivided.Length == 2 && lineDivided[1].StartsWith(" !translate ")) { string rawText = lineDivided[1].Replace(" !translate ", ""); SendChatMessage(EngToNoob(rawText)); } } if (chatLine.Contains("!utility")) { string[] lineDivided = chatLine.Split(':'); if (lineDivided.Length == 2 && lineDivided[1].StartsWith(" !utility ")) { string rawText = lineDivided[1].Replace(" !utility ", ""); try { string response = cleverBotSession.Think(rawText); SendChatMessage("^0DU^1 - " + response); } catch (System.Net.WebException ex) { System.Diagnostics.Debug.Print("Error occured while getting bot response."); SendChatMessage(ex.Message); } } } if (chatLine.Contains("!scaleall")) { string[] prms = chatLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; i < 32; i++) { if (privateMode) { ExecuteConsoleCommand("scale " + i + " " + prms[1]); } else { ExecuteConsoleCommand("scale " + i + " " + prms[3]); } } } if (chatLine.Contains("!forward")) { ExecuteConsoleCommand("-back"); ExecuteConsoleCommand("+forward"); } if (chatLine.Contains("!back")) { ExecuteConsoleCommand("-forward"); ExecuteConsoleCommand("+back"); } if (chatLine.Contains("!left")) { ExecuteConsoleCommand("-right"); ExecuteConsoleCommand("+left"); } if (chatLine.Contains("!right")) { ExecuteConsoleCommand("-left"); ExecuteConsoleCommand("+right"); } if (chatLine.Contains("!jump")) { ExecuteConsoleCommand("+moveup"); System.Threading.Thread.Sleep(50); ExecuteConsoleCommand("-moveup"); } if (chatLine.Contains("!heal")) { ExecuteConsoleCommand("force_heal"); } if (chatLine.Contains("!stop")) { ExecuteConsoleCommand("-forward"); ExecuteConsoleCommand("-back"); ExecuteConsoleCommand("-left"); ExecuteConsoleCommand("-right"); ExecuteConsoleCommand("-attack"); } if (chatLine.Contains("!attack")) { ExecuteConsoleCommand("+attack"); } if (chatLine.Contains("!tour")) { string[] words = chatLine.Split(' '); int cmdStartIndex = Array.FindIndex(words, x => x == "!tour"); if (cmdStartIndex < words.Length - 1) { if (words[cmdStartIndex + 1] == "restrict") { ExecuteConsoleCommand(@"place lmd_restrict 0 spawnflags,48,mins,-1000 -1000 0,maxs,1000 1000 1000"); } else if (words[cmdStartIndex + 1] == "restrict_id") { if (cmdStartIndex < words.Length - 2) { int entityId; if (int.TryParse(words[cmdStartIndex + 2], out entityId)) { duelRestrict = entityId; SendChatMessage("^0DU^3 - ID set"); } else { SendChatMessage("^0DU^1 - Wrong parameter"); } } else { SendChatMessage("^0DU^1 - No parameter specified"); } } else if (words[cmdStartIndex + 1] == "announce") { ExecuteConsoleCommand("announce 10 ^1Saber tournament!^5 Say 'me' for teleport"); } else if (words[cmdStartIndex + 1] == "help") { SendChatMessage("restrict|restrict_id|delrestrict|togglerestrict|announce|add|remove|clear|generate|view"); } else if (words[cmdStartIndex + 1] == "delrestrict") { if (duelRestrict.HasValue) { ExecuteConsoleCommand("delent " + duelRestrict); duelRestrict = null; } else { SendChatMessage("^0DU^1 - Restrict ID not provided, use restrict_id to do this"); } } else if (words[cmdStartIndex + 1] == "togglerestrict") { if (duelRestrict.HasValue) { ExecuteConsoleCommand("disable " + duelRestrict); } else { SendChatMessage("^0DU^1 - Restrict ID not provided, use restrict_id to do this"); } } else if (words[cmdStartIndex + 1] == "add") { if (cmdStartIndex < words.Length - 2) { tournamentParticipants.Add(words[cmdStartIndex + 2]); SendChatMessage("^0DU^3 - " + words[cmdStartIndex + 2] + " added"); } else { SendChatMessage("^0DU^1 - No name specified"); } } else if (words[cmdStartIndex + 1] == "remove") { if (cmdStartIndex < words.Length - 2) { if (tournamentParticipants.Remove(words[cmdStartIndex + 2])) { SendChatMessage("^0DU^3 - " + words[cmdStartIndex + 2] + " successfully removed"); } else { SendChatMessage("^0DU^1 - Name not found"); } } else { SendChatMessage("^0DU^1 - No name specified"); } } else if (words[cmdStartIndex + 1] == "generate") { if (tournamentParticipants.Count % 2 == 0 && tournamentParticipants.Count != 0) { List <string> teams = new List <string>(); while (tournamentParticipants.Count > 0) { int index = RandomSingleton.Next(0, tournamentParticipants.Count); teams.Add(tournamentParticipants[index]); tournamentParticipants.RemoveAt(index); } tournamentParticipants = teams; } else { SendChatMessage("^0DU^1 - Wrong number of players - impaired or zero"); } } else if (words[cmdStartIndex + 1] == "view") { StateMsg = ""; if (tournamentParticipants.Count % 2 == 0 && tournamentParticipants.Count != 0) { for (int i = 0; i < tournamentParticipants.Count; i++) { if (i % 2 == 1) { StateMsg += "vs "; } StateMsg += tournamentParticipants[i] + " "; if (i % 2 == 1) { StateMsg += " | "; } } SendChatMessage(StateMsg); } else { SendChatMessage("^0DU^1 - Cannot list teams - unpaired or zero players"); } } else if (words[cmdStartIndex + 1] == "clear") { tournamentParticipants.Clear(); } else { SendChatMessage("^0DU^1 - Unknown task"); } } else { SendChatMessage("^0DU^1 - No task specified"); } } }
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); }); }); }
static Task ClientTask(DiscordClient client) { return(Task.Run(() => { Console.WriteLine("WELCOME TO DISCORD BOT" + "\n============================="); // voice messages client.MessageReceived += (sender, e) => { // Joining a voice channel if (e.message.content.StartsWith("!joinvoice")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (!String.IsNullOrEmpty(split[1])) { DiscordChannel toJoin = e.Channel.parent.channels.Find(x => (x.Name.ToLower() == split[1].ToLower()) && (x.Type == ChannelType.Voice)); if (toJoin != null) { DiscordVoiceConfig voiceCfg = new DiscordVoiceConfig() { Bitrate = null, Channels = 1, FrameLengthMs = 60, OpusMode = Discord.Audio.Opus.OpusApplication.LowLatency, SendOnly = false }; audio = new AudioPlayer(voiceCfg); client.ConnectToVoiceChannel(toJoin); } } } else if (e.message.content.StartsWith("!addsong")) { string[] split = e.message.content.Split(new char[] { ' ' }, 3); if (split.Count() >= 3 && !String.IsNullOrEmpty(split[1]) && !String.IsNullOrEmpty(split[2])) { DoVoiceURL(client.GetVoiceClient(), split[1], split[2]); } else { client.SendMessageToChannel("Incorrect add song syntax.", e.Channel); } } else if (e.message.content.StartsWith("!play")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (File.Exists(split[1])) { DoVoiceMP3(client.GetVoiceClient(), split[1]); } else { client.SendMessageToChannel("Song does not exist.", e.Channel); } } else if (e.message.content.StartsWith("!disconnect")) { client.DisconnectFromVoice(); } }; // other messages client.MessageReceived += (sender, e) => { Console.WriteLine($"[" + e.Channel.Name.ToString() + "] " + e.message.author.Username + ": " + e.message.content.ToString()); if (e.Channel.Name == "thatbelikeitis" || e.Channel.Name == "newtestchannel") { mainText = e.Channel; quoteMuseum = client.GetChannelByName("quotes"); } if (e.message.content.StartsWith("!help")) { string helpMsg = "Welcome to DiscordBot! The following commands are available:\n" + "help, hello, joinvoice [channelname], play [mp3 path], addsong [youtube url] [song name], roll [XdX] [+/-] [mod]"; client.SendMessageToChannel(helpMsg, e.Channel); } // Text detection if (e.message.content.Contains("Kappa") || e.message.content.Contains("kappa")) { client.SendMessageToChannel("We don't use that word here.", e.Channel); } else if (e.message.content.Contains("I'm back") || e.message.content.Contains("im back")) { client.SendMessageToChannel("I'm front", e.Channel); } else if (e.message.content.Contains("ryan") || e.message.content.Contains("Ryan") || e.message.content.Contains("jimmy")) { client.AttachFile(e.Channel, "", "jimmyneukong.jpg"); //client.SendMessageToChannel("ryan", e.Channel); } else if (e.message.content.Contains("f14")) { client.AttachFile(e.Channel, "", "f14.jpg"); } // Commands! if (e.message.content.StartsWith("!hello")) { client.SendMessageToChannel("Hello World!", e.Channel); } else if (e.message.content.StartsWith("!quote")) { string quote = GetRandomQuote(client); client.SendMessageToChannel(quote, e.Channel); } else if (e.message.content.StartsWith("!addquote")) { char[] newQuote = e.message.content.Skip(9).ToArray(); client.SendMessageToChannel(new string(newQuote), quoteMuseum); } else if (e.message.content.StartsWith("!roll")) { string[] split = e.message.content.Split(new char[] { ' ' }, 4); if (split.Count() >= 2 && !String.IsNullOrEmpty(split[1])) { string[] split2 = split[1].Split(new char[] { 'd' }, 2); int roll = 0; if (split.Count() >= 4 && !String.IsNullOrEmpty(split[2]) && !String.IsNullOrEmpty(split[3])) { if (split[2] == "+") { roll = Roll(Int32.Parse(split2[0]), Int32.Parse(split2[1]), Int32.Parse(split[3])); } else if (split[2] == "-") { roll = Roll(Int32.Parse(split2[0]), Int32.Parse(split2[1]), Int32.Parse(split[3]) * -1); } else { client.SendMessageToChannel("Can only mod by + or -! Result invalid.", e.Channel); } } else { roll = Roll(Int32.Parse(split2[0]), Int32.Parse(split2[1]), 0); } string msg = split2[0] + "d" + split2[1] + ": " + roll; client.SendMessageToChannel(msg, e.Channel); } else { client.SendMessageToChannel("Missing arguments!", e.Channel); } } else if (e.message.content.StartsWith("!chat")) { char[] chatMsg = e.message.content.Skip(6).ToArray(); string reply = chatBot.Think(new string(chatMsg)); Console.WriteLine(new string(chatMsg)); Console.WriteLine(reply); client.SendMessageToChannel(reply, e.Channel); } else if (e.message.content.StartsWith("!supersecretshutdowncommand")) { System.Environment.Exit(0); } }; client.Connected += (sender, e) => { Console.WriteLine($"Connected! User: {e.user.Username}"); }; client.Connect(); })); }
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(); } } }
private void HandlePrivmsg(IRCMessage sIRCMessage) { var sIgnoreNickName = sIrcBase.Networks[sIRCMessage.ServerName].sIgnoreNickName; var sSendMessage = sIrcBase.Networks[sIRCMessage.ServerName].sSendMessage; var sMyChannelInfo = sIrcBase.Networks[sIRCMessage.ServerName].sMyChannelInfo; if (sIgnoreNickName.IsIgnore(sIRCMessage.Nick)) { return; } if (!Rfc2812Util.IsValidChannelName(sIRCMessage.Channel)) { sIRCMessage.Channel = sIRCMessage.Nick; } if (sMyChannelInfo.FSelect(IFunctions.Chatterbot) && sMyChannelInfo.FSelect(IChannelFunctions.Chatterbot, sIRCMessage.Channel)) { Task.Factory.StartNew(() => sSendMessage.SendChatMessage(sIRCMessage, HttpUtility.HtmlDecode(session.Think(sIRCMessage.Args)))); } }
public async Task <string> ThinkAsync(string text) { return(await session.Think(text)); }