//password from twitchapps.com/tmi static void Main(string[] args) { var irc = new IrcClient("irc.twitch.tv",6667, "cogwheelbot", "oauth:ffiiryof5w501xlz43qbk75k9xcmv1"); irc.JoinRoom("faddei"); var stopWatch = Stopwatch.StartNew(); while (true) { string message = irc.ReadMessage(); if(!string.IsNullOrEmpty(message)) { Console.WriteLine(message); if (message.ToLower().Contains("!hallo")) { irc.SendChatMessage("Testing Testing"); } if (message.ToLower().Contains("!add")) { string[] html = message.Split('!'); Console.WriteLine("open link: "+html[1].Substring(4)); System.Diagnostics.Process.Start(html[1].Substring(4)); } if (message.ToLower().Contains("!uptime")) { DateTime time = new DateTime(stopWatch.ElapsedTicks); string uptime = time.ToString("HH:mm:ss"); irc.SendChatMessage(time.Hour+ " hours "+ time.Minute + " mins"); irc.SendChatMessage(uptime); } } } }
public Bot(IrcClient irc) { joinedUsers = new List<string>(); vipUsers = new List<string>(); rand = new Random(); this.irc = irc; slots = new Slots(); }
static void Main(string[] args) { bool.TryParse(ConfigurationManager.AppSettings["testmode"], out _testMode); string password = ConfigurationManager.AppSettings["oauth"]; //password from www.twitchapps.com/tmi //include the "oauth:" portion irc = new IrcClient("irc.twitch.tv", 6667, "mrsheila", password); //join channel irc.JoinRoom("voxdavis"); CommandManager.AddCommand("!hype", "Used to generate hype!", (message) => { return "HYPE HYPE HYPE!!!!"; }); CommandManager.AddCommand("!name", "Used to generate a random name. Give a username afterwards to assign it to someone.", (message) => { Regex r = new Regex(@"!name @[\w_\-]+"); NameGenerator ng = new NameGenerator(); if (r.IsMatch(message)) { string u = message.Substring(7); return u + "'s new name is " + ng.GetName(); } else { return ng.GetName(); } }); CommandManager.AddCommand("!source", "Gets a link to the source code!", (message) => { return @"https://github.com/AronDavis/TwitchBot"; }); if (_testMode) { while (true) { string message = irc.readMessage(); if (message == null || message.Length == 0) continue; if (message[0] == '!') { handleCommand("TestUser", message); } } } else { while (true) { string message = irc.readMessage(); if (message == null || message.Length == 0) continue; Console.WriteLine(message); if (message.IndexOf("!") >= 0) handleChatMessage(message); else if (message.StartsWith("PING")) irc.sendIrcMessage("PONG"); } } }
public TwitchChatConnection(IrcClient ircClient, bool isWhisperConnection) { this.ircClient = ircClient; this.ircClient.Connect(); if (isWhisperConnection) { ircClient.SendIrcString("CAP REQ :twitch.tv/commands"); } }
//takes oauth password from twitch static void Main(string[] args) { IrcClient irc = new IrcClient("irc.twitch.tv", 6667, "nightlurk", "oauth:p9znoj3v2mm3niyxd42o6n4ae5zmgs"); irc.joinRoom("nightlurk"); Mod mod = new Mod(); Random rand = new Random(); while (true) { string message = irc.readMessage(); string curUser = irc.getUserName(message); // if (message != "") // irc.sendChatMessage(message); if (message.Contains("!banRoulette")) { int random = rand.Next(); string result; if (random % 6 == 0) { result = "RIP"; mod.timeout(curUser, irc); } else { result = "nothing happens."; } irc.sendChatMessage(curUser + " spins the barrel and shoots ... 1 second later and " + result); } mod.containsBannedWord(message, curUser, irc); } //end of while } //end of main
private void Initialization() { infoDisplayTimer = new DispatcherTimer(); infoDisplayTimer.Tick += infoDisplayTimer_Tick; infoDisplayTimer.Interval = new TimeSpan(0, InfoInterval, 0); infoDisplayTimer.Start(); irc = new IrcClient("irc.twitch.tv", 6667, "hap_pybot", "oauth:" + oauth); bot = new Bot(irc); info = bot.LoadTextFile("_info"); scroll.VerticalScrollBarVisibility = ScrollBarVisibility.Hidden; if (irc.Connected) { irc.JoinRoom(ChannelToJoin); StartThread(); } else { Application.Current.Shutdown(); } }
}//end of mod() //returns 1 if the message has a word that is banned //if recording is set to 1 it will write to a file whenever someone is timed out public int containsBannedWord(string message, string user, IrcClient irc) { string[] banned = bannedWords.ToArray(); for (int i = 0; i < banned.Length; i++) { if (message.Contains(banned[i])) { irc.sendChatMessage("record = " + record); if (record == 1) { char[] spil = { ':' }; string[] userMessage = message.Split(spil); string write = "TimedOut: " + user + " Word Used = " + banned[i] + " Complete text = " + userMessage[2]; irc.sendChatMessage("write = " + write); timeoutRecord.Flush(); } timeout(user, irc); return(1); } } return(0); }//end of isBanned
public Pinger(IrcClient client) { this.client = client; sender = new Thread(new ThreadStart(Run)); }
static void Main(string[] args) { bool.TryParse(ConfigurationManager.AppSettings["testmode"], out _testMode); string password = ConfigurationManager.AppSettings["oauth"]; //password from www.twitchapps.com/tmi //include the "oauth:" portion irc = new IrcClient("irc.twitch.tv", 6667, "mrsheila", password); //join channel irc.JoinRoom("voxdavis"); CommandManager.AddCommand("!hype", "Used to generate hype!", (message) => { return("HYPE HYPE HYPE!!!!"); }); CommandManager.AddCommand("!name", "Used to generate a random name. Give a username afterwards to assign it to someone.", (message) => { Regex r = new Regex(@"!name @[\w_\-]+"); NameGenerator ng = new NameGenerator(); if (r.IsMatch(message)) { string u = message.Substring(7); return(u + "'s new name is " + ng.GetName()); } else { return(ng.GetName()); } }); CommandManager.AddCommand("!source", "Gets a link to the source code!", (message) => { return(@"https://github.com/AronDavis/TwitchBot"); }); if (_testMode) { while (true) { string message = irc.readMessage(); if (message == null || message.Length == 0) { continue; } if (message[0] == '!') { handleCommand("TestUser", message); } } } else { while (true) { string message = irc.readMessage(); if (message == null || message.Length == 0) { continue; } Console.WriteLine(message); if (message.IndexOf("!") >= 0) { handleChatMessage(message); } else if (message.StartsWith("PING")) { irc.sendIrcMessage("PONG"); } } } }
}//end of isBanned public void timeout(string user, IrcClient irc) { irc.sendChatMessage(".timeout " + user); irc.sendChatMessage(".unban " + user); }
static void Main(string[] args) { // Twitch variables string twitchOAuth = ""; string twitchClientID = ""; string twitchAccessToken = ""; // used for channel editing // Twitter variables bool hasTwitterInfo = true; string twitterConsumerKey = ""; string twitterConsumerSecret = ""; string twitterAccessToken = ""; string twitterAccessSecret = ""; bool isSongRequestAvail = false; // check song request status (disabled by default) /* Connect to database or exit program on connection error */ try { // Grab connection string (production or test) if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.conn)) { _connStr = Properties.Settings.Default.conn; // production database only Console.WriteLine("Connecting to database..."); } else if (!string.IsNullOrWhiteSpace(Properties.Settings.Default.connTest)) { _connStr = Properties.Settings.Default.connTest; // test database only Console.WriteLine("<<<< WARNING: Connecting to local database (testing only) >>>>"); } else { Console.WriteLine("Internal Error: Connection string to database not provided!"); Console.WriteLine("Shutting down now..."); Thread.Sleep(3500); Environment.Exit(1); } // Check if server is connected if (!IsServerConnected(_connStr)) { // clear sensitive data _connStr = null; Console.WriteLine("Datebase connection failed. Please try again"); Console.WriteLine(); Console.WriteLine("-- Common technical issues: --"); Console.WriteLine("1: Check if firewall settings has your client IP address."); Console.WriteLine("2: Double check the connection string under 'Properties' inside 'Settings'"); Console.WriteLine(); Console.WriteLine("Shutting down now..."); Thread.Sleep(5000); Environment.Exit(1); } } catch (Exception ex) { Console.WriteLine("Error Message: " + ex.Message); Console.WriteLine("Local troubleshooting needed by author of this bot"); Console.WriteLine(); Console.WriteLine("Shutting down now..."); Thread.Sleep(3000); Environment.Exit(1); } /* Try to grab the info needed for the bot to connect to the channel */ try { Console.WriteLine("Database connection successful!"); Console.WriteLine(); Console.WriteLine("Checking if user settings has all necessary info..."); // Grab settings _strBotName = Properties.Settings.Default.botName; _strBroadcasterName = Properties.Settings.Default.broadcaster; twitchOAuth = Properties.Settings.Default.twitchOAuth; twitchClientID = Properties.Settings.Default.twitchClientID; twitchAccessToken = Properties.Settings.Default.twitchAccessToken; twitterConsumerKey = Properties.Settings.Default.twitterConsumerKey; twitterConsumerSecret = Properties.Settings.Default.twitterConsumerSecret; twitterAccessToken = Properties.Settings.Default.twitterAccessToken; twitterAccessSecret = Properties.Settings.Default.twitterAccessSecret; _strDiscordLink = Properties.Settings.Default.discordLink; _strCurrencyType = Properties.Settings.Default.currencyType; _isAutoDisplaySong = Properties.Settings.Default.enableDisplaySong; _isAutoPublishTweet = Properties.Settings.Default.enableTweet; _intStreamLatency = Properties.Settings.Default.streamLatency; // Check if program has client ID (developer needs to provide this inside the settings) if (string.IsNullOrWhiteSpace(twitchClientID)) { Console.WriteLine("Error: MISSING Twitch Client ID"); Console.WriteLine("Please contact the author of this bot to re-release this application with the client ID"); Console.WriteLine(); Console.WriteLine("Shutting down now..."); Thread.Sleep(3000); Environment.Exit(1); } // Check if user has the minimum info in order to run the bot // Tell user to input essential info while (string.IsNullOrWhiteSpace(_strBotName) && string.IsNullOrWhiteSpace(_strBroadcasterName) && string.IsNullOrWhiteSpace(twitchOAuth) && string.IsNullOrWhiteSpace(twitchAccessToken)) { Console.WriteLine("You are missing essential info"); if (string.IsNullOrWhiteSpace(_strBotName)) { Console.WriteLine("Enter your bot's username: "******"Enter your Twitch username: "******"Enter your Twitch OAuth: "); Properties.Settings.Default.twitchOAuth = Console.ReadLine(); twitchOAuth = Properties.Settings.Default.twitchOAuth; } if (string.IsNullOrWhiteSpace(twitchAccessToken)) { Console.WriteLine("Enter your Twitch Access Token: "); Properties.Settings.Default.twitchAccessToken = Console.ReadLine(); twitchAccessToken = Properties.Settings.Default.twitchAccessToken; } Properties.Settings.Default.Save(); Console.WriteLine("Saved Settings!"); Console.WriteLine(); } // Option to edit settings before running it Console.WriteLine("Do you want to edit your essential bot settings (y/n or yes/no)?"); string strResponse = Console.ReadLine().ToLower(); // Check if user inserted a valid option while (!(strResponse.Equals("y") || strResponse.Equals("yes") || strResponse.Equals("n") || strResponse.Equals("no"))) { Console.WriteLine("Please insert a valid option (y/n or yes/no)"); strResponse = Console.ReadLine().ToLower(); } // Change some settings if (strResponse.Equals("y") || strResponse.Equals("yes")) { int intOption = 0; Console.WriteLine(); /* Loop until user is finished making changes */ do { // Display bot settings Console.WriteLine("---> Here are your essential bot settings <---"); Console.WriteLine("1. Bot's username: "******"2. Your main Twitch username: "******"3. Twitch OAuth: " + Properties.Settings.Default.twitchOAuth); Console.WriteLine("4. Twitch Access Token: " + Properties.Settings.Default.twitchAccessToken); Console.WriteLine(); Console.WriteLine("From the options 1-4 (or 0 to exit editing), which option do you want to edit?"); // Edit an option if (int.TryParse(Console.ReadLine(), out intOption) && intOption < 5 && intOption >= 0) { Console.WriteLine(); switch (intOption) { case 1: Console.WriteLine("Enter your bot's new username: "******"Enter your new Twitch username: "******"Enter your new Twitch OAuth (include 'oauth:' along the 30 character phrase): "); Properties.Settings.Default.twitchOAuth = Console.ReadLine(); twitchOAuth = Properties.Settings.Default.twitchOAuth; break; case 4: Console.WriteLine("Enter your new Twitch access token: "); Properties.Settings.Default.twitchAccessToken = Console.ReadLine(); twitchAccessToken = Properties.Settings.Default.twitchAccessToken; break; } Properties.Settings.Default.Save(); Console.WriteLine("Saved Settings!"); Console.WriteLine(); } else { Console.WriteLine("Please write a valid option between 1-4 (or 0 to exit editing)"); Console.WriteLine(); } } while (intOption != 0); Console.WriteLine("Finished with editing settings"); } else // No need to change settings Console.WriteLine("Essential settings confirmed!"); Console.WriteLine(); // Extra settings menu Console.WriteLine("Do you want to edit your extra bot settings [twitter/discord/currency] (y/n or yes/no)?"); strResponse = Console.ReadLine().ToLower(); // Check if user inserted a valid option while (!(strResponse.Equals("y") || strResponse.Equals("yes") || strResponse.Equals("n") || strResponse.Equals("no"))) { Console.WriteLine("Please insert a valid option (y/n or yes/no)"); strResponse = Console.ReadLine().ToLower(); } // Change some settings if (strResponse.Equals("y") || strResponse.Equals("yes")) { int intOption = 0; Console.WriteLine(); /* Loop until user is finished making changes */ do { // Display bot settings Console.WriteLine("---> Here are your extra bot settings <---"); Console.WriteLine("1. Twitter consumer key: " + Properties.Settings.Default.twitterConsumerKey); Console.WriteLine("2. Twitter consumer secret: " + Properties.Settings.Default.twitterConsumerSecret); Console.WriteLine("3. Twitter access token: " + Properties.Settings.Default.twitterAccessToken); Console.WriteLine("4. Twitter access secret: " + Properties.Settings.Default.twitterAccessSecret); Console.WriteLine("5. Discord link: " + Properties.Settings.Default.discordLink); Console.WriteLine("6. Currency type: " + Properties.Settings.Default.currencyType); Console.WriteLine("7. Enable Auto Tweets: " + Properties.Settings.Default.enableTweet); Console.WriteLine("8. Enable Auto Display Songs: " + Properties.Settings.Default.enableDisplaySong); Console.WriteLine("9. Stream Latency: " + Properties.Settings.Default.streamLatency); Console.WriteLine(); Console.WriteLine("From the options 1-9 (or 0 to exit editing), which option do you want to edit?"); // Edit an option string strOption = Console.ReadLine(); if (int.TryParse(strOption, out intOption) && intOption < 10 && intOption >= 0) { Console.WriteLine(); switch (intOption) { case 1: Console.WriteLine("Enter your new Twitter consumer key: "); Properties.Settings.Default.twitterConsumerKey = Console.ReadLine(); twitterConsumerKey = Properties.Settings.Default.twitterConsumerKey; break; case 2: Console.WriteLine("Enter your new Twitter consumer secret: "); Properties.Settings.Default.twitterConsumerSecret = Console.ReadLine(); twitterConsumerSecret = Properties.Settings.Default.twitterConsumerSecret; break; case 3: Console.WriteLine("Enter your new Twitter access token: "); Properties.Settings.Default.twitterAccessToken = Console.ReadLine(); twitterAccessToken = Properties.Settings.Default.twitterAccessToken; break; case 4: Console.WriteLine("Enter your new Twitter access secret: "); Properties.Settings.Default.twitterAccessSecret = Console.ReadLine(); twitterAccessSecret = Properties.Settings.Default.twitterAccessSecret; break; case 5: Console.WriteLine("Enter your new Discord link: "); Properties.Settings.Default.discordLink = Console.ReadLine(); _strDiscordLink = Properties.Settings.Default.discordLink; break; case 6: Console.WriteLine("Enter your new currency type: "); Properties.Settings.Default.currencyType = Console.ReadLine(); _strCurrencyType = Properties.Settings.Default.currencyType; break; case 7: Console.WriteLine("Want to enable (true) or disable (false) auto tweets: "); Properties.Settings.Default.enableTweet = Convert.ToBoolean(Console.ReadLine()); _isAutoPublishTweet = Properties.Settings.Default.enableTweet; break; case 8: Console.WriteLine("Want to enable (true) or disable (false) display songs from Spotify: "); Properties.Settings.Default.enableDisplaySong = Convert.ToBoolean(Console.ReadLine()); _isAutoDisplaySong = Properties.Settings.Default.enableDisplaySong; break; case 9: Console.WriteLine("Enter your new stream latency (in seconds): "); Properties.Settings.Default.streamLatency = int.Parse(Console.ReadLine()); _intStreamLatency = Properties.Settings.Default.streamLatency; break; } Properties.Settings.Default.Save(); Console.WriteLine("Saved Settings!"); Console.WriteLine(); } else { Console.WriteLine("Please write a valid option between 1-9 (or 0 to exit editing)"); Console.WriteLine(); } } while (intOption != 0); Console.WriteLine("Finished with editing settings"); } else // No need to change settings Console.WriteLine("Extra settings confirmed!"); Console.WriteLine(); // Get broadcaster ID so the user can only see their data from the db _intBroadcasterID = getBroadcasterID(_strBroadcasterName.ToLower()); // Add broadcaster as new user to database if (_intBroadcasterID == 0) { string query = "INSERT INTO tblBroadcasters (username) VALUES (@username)"; using (SqlConnection conn = new SqlConnection(_connStr)) using (SqlCommand cmd = new SqlCommand(query, conn)) { cmd.Parameters.Add("@username", SqlDbType.VarChar, 30).Value = _strBroadcasterName; conn.Open(); cmd.ExecuteNonQuery(); conn.Close(); } _intBroadcasterID = getBroadcasterID(_strBroadcasterName.ToLower()); } // Try looking for the broadcaster's ID again if (_intBroadcasterID == 0) { Console.WriteLine("Cannot find a broadcaster ID for you. " + "Please contact the author with a detailed description of the issue"); Thread.Sleep(3000); Environment.Exit(1); } /* Connect to local Spotify client */ _spotify = new SpotifyControl(); _spotify.Connect(); Console.WriteLine(); Console.WriteLine("Time to get to work!"); Console.WriteLine(); /* Make sure usernames are set to lowercase for the rest of the application */ _strBotName = _strBotName.ToLower(); _strBroadcasterName = _strBroadcasterName.ToLower(); // Password from www.twitchapps.com/tmi/ // include the "oauth:" portion // Use chat bot's oauth /* main server: irc.twitch.tv, 6667 */ _irc = new IrcClient("irc.twitch.tv", 6667, _strBotName, twitchOAuth, _strBroadcasterName); // Update channel info _intFollowers = TaskJSON.GetChannel().Result.followers; _strBroadcasterGame = TaskJSON.GetChannel().Result.game; /* Make new thread to get messages */ Thread thdIrcClient = new Thread(() => TwitchBotApp.GetChatBox(isSongRequestAvail, twitchAccessToken, hasTwitterInfo)); thdIrcClient.Start(); /* Whisper broadcaster bot settings */ Console.WriteLine("---> Extra Bot Settings <---"); Console.WriteLine("Discord link: " + _strDiscordLink); Console.WriteLine("Currency type: " + _strCurrencyType); Console.WriteLine("Enable Auto Tweets: " + _isAutoPublishTweet); Console.WriteLine("Enable Auto Display Songs: " + _isAutoDisplaySong); Console.WriteLine("Stream latency: " + _intStreamLatency + " second(s)"); Console.WriteLine(); /* Start listening for delayed messages */ DelayMsg delayMsg = new DelayMsg(); delayMsg.Start(); /* Get list of mods */ _mod = new Moderator(); setListMods(); /* Get list of timed out users */ _timeout = new Timeout(); setListTimeouts(); /* Ping to twitch server to prevent auto-disconnect */ PingSender ping = new PingSender(); ping.Start(); /* Remind viewers of bot's existance */ PresenceReminder preRmd = new PresenceReminder(); preRmd.Start(); /* Authenticate to Twitter if possible */ if (hasTwitterInfo) { Auth.ApplicationCredentials = new TwitterCredentials( twitterConsumerKey, twitterConsumerSecret, twitterAccessToken, twitterAccessSecret ); } } catch (Exception ex) { LogError(ex, "Program", "Main(string[])", true); } }
public CommandHandler(IrcClient irc) { this.irc = irc; }
static void Whisper(string user, string message, IrcClient whisperClient) { string toSend = ".w " + user + " " + message; whisperClient.sendChatMessage(toSend); }
static void Main(string[] args) { //RC-Channel-ID 30773965 //ChatRoom 1a1bd140-55b3-4a63-815c-077b094ffba1 try { ///Load bot configuration Config = new BotConfiguration(Storage = new WindowsStorage("FoxBot")); Channel = Config.GetBindable <string>(BotSetting.Channel); ChatBotChannel = Config.GetBindable <string>(BotSetting.BotChatRoom); ///Set log folder Logger.Storage = Storage.GetStorageForDirectory("logs"); ///Create if not exist Directory.CreateDirectory("./Modues"); ///Create client instance client = new IrcClient() { //Username = Nick, //AuthToken = ServerPass, }; ///Initialize command service commands = new CommandService(new CommandServiceConfig() { CaseSensitiveCommands = false, DefaultRunMode = RunMode.Sync, }); ///Create form instance Form = new DialogWindow(); ///------------------------------================= bool interrupt = false; ///Modules update thread. Please, use async func for long timed work in case not blocking other modules Thread updateThread = new Thread(() => { while (!interrupt) { ///update if (DateTimeOffset.Now > GetUserListTimout) { var req = new JsonWebRequest <ChatData>($"https://tmi.twitch.tv/group/user/{Channel.Value.Replace("#", "")}/chatters"); req.Finished += () => { DialogWindow.UpdateChattersList(req.ResponseObject); if (BotEntry.ChannelsChatters.ContainsKey(BotEntry.Channel)) { BotEntry.ChannelsChatters[BotEntry.Channel] = req.ResponseObject.chatters; } else { BotEntry.ChannelsChatters.Add(BotEntry.Channel, req.ResponseObject.chatters); } }; ///In case not block current thread req.PerformAsync(); GetUserListTimout = GetUserListTimout.AddMinutes(5); } OnTickActions?.Invoke(); Thread.Sleep(50); } }); ///Load dust data using (var file = new StreamReader(Storage.GetStream($"Dust/{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite))) { if (!file.EndOfStream) { BotEntry.RedstoneDust = JsonConvert.DeserializeObject <SortedDictionary <string, RedstoneData> >(file.ReadToEnd()); } if (BotEntry.RedstoneDust == null) { BotEntry.RedstoneDust = new SortedDictionary <string, RedstoneData> { } } ; } ///Start update thread updateThread.Start(); ///Load some configs in form Form.Load(Storage); services = new ServiceCollection() .AddSingleton(client) .AddSingleton(commands) .AddSingleton(Form) .BuildServiceProvider(); client.ChannelMessage += HandleMessage; client.OnConnect += Client_OnConnect; commands.AddModulesAsync(Assembly.GetEntryAssembly(), services); ///Try load all module in /Modules folder var dll = Directory.GetFiles(Directory.GetCurrentDirectory() + "\\Modues", "*.dll", SearchOption.TopDirectoryOnly); foreach (var it in dll) { try { Logger.Log($"Loading {it} module..."); commands.AddModulesAsync(Assembly.LoadFile(it), services); } catch { continue; } } ///Load items metadata foreach (var data in RedstoneDust) { data.Value.ReadJsonData(); } PostInit?.Invoke(); ///Run form Application.Run(Form); ///Save any config changes inside form Logger.Log($"Unloading form data..."); Form.Unload(Storage); ///Interrupt a thread interrupt = true; Thread.Sleep(1000); ///Unload all data and exit Logger.Log($"====================UNLOADING SERVICES====================="); OnExiting?.Invoke(); client.Disconnect(); ///Commands.CommandsService.Unload(Storage); Logger.Log($"=================UNLOADING SERVICES ENDED=================="); ///Prepare item metadata to unloading foreach (var data in RedstoneDust) { data.Value.PrepareJsonData(); } ///Unload dust data using (var file = new StreamWriter(Storage.GetStream($"Dust/{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite, FileMode.Truncate))) { file.Write(JsonConvert.SerializeObject(BotEntry.RedstoneDust, Formatting.Indented)); } Thread.Sleep(1000); } catch (Exception e) { Logger.GetLogger(LoggingTarget.Stacktrace).Add($"FATAL ERROR: {e.Message}. SEE STACKTRACE FOR DETAIL"); Logger.GetLogger(LoggingTarget.Stacktrace).Add(e.StackTrace); Thread.Sleep(50); foreach (var data in RedstoneDust) { data.Value.PrepareJsonData(); } using (var file = new StreamWriter(Storage.GetStream($"Dust/{BotEntry.Channel}#RedstoneData.json", FileAccess.ReadWrite, FileMode.Truncate))) { file.Write(JsonConvert.SerializeObject(BotEntry.RedstoneDust, Formatting.Indented)); } } }
private void Initialize() { settings = Settings.Load("settings.xml"); account = Account.Load(settings.AccountFile); WebClient client = new WebClient(); string cluster = client.DownloadString("https://decapi.me/twitch/clusters?channel=" + settings.Channel); Console.WriteLine("cluster: " + cluster); string server = cluster == "main" ? "irc.twitch.tv" : "irc.chat.twitch.tv"; ircClient = new IrcClient(server, 6667, account.Username, account.Password); SetupCommands(); LoadCommands(); }
public MessageHandler(IrcClient irc) { this.irc = irc; commandHandler = new CommandHandler(irc); landmine = new Random(); }
// Empty constructor makes instance of Thread public PingSender(IrcClient irc) { _irc = irc; pingSender = new Thread(new ThreadStart(this.Run)); }
static void Main(string[] args) { //Survey survey = new Survey(); // Initialize and connect to Twitch chat IrcClient irc = new IrcClient("irc.chat.twitch.tv", 6667, _botName, _twitchOAuth, _broadcasterName); // Ping to the server to make sure this bot stays connected to the chat // Server will respond back to this bot with a PONG (without quotes): // Example: ":tmi.twitch.tv PONG tmi.twitch.tv :irc.twitch.tv" PingSender ping = new PingSender(irc); ping.Start(); // Listen to the chat until program exits while (true) { if (survey.IsActive && survey.End < DateTime.Now) { irc.SendPublicChatMessage(survey.ReportResults()); } // Read any message from the chat room string message = irc.ReadMessage(); Console.WriteLine(message); // Print raw irc messages if (message.Contains("PRIVMSG")) { // Messages from the users will look something like this (without quotes): // Format: ":[user]![user]@[user].tmi.twitch.tv PRIVMSG #[channel] :[message]" // Modify message to only retrieve user and message int intIndexParseSign = message.IndexOf('!'); string userName = message.Substring(1, intIndexParseSign - 1); // parse username from specific section (without quotes) // Format: ":[user]!" // Get user's message intIndexParseSign = message.IndexOf(" :"); message = message.Substring(intIndexParseSign + 2).Trim(); Console.WriteLine(message); // Print parsed irc message (debugging only) // Broadcaster commands if (userName.Equals(_broadcasterName)) { if (message.Equals("!exitbot")) { irc.SendPublicChatMessage("Bye! Have a beautiful time!"); Environment.Exit(0); // Stop the program } if (message.Contains("!umfrage ") || message.Contains("!Umfrage ")) { if (message.Contains("--s")) { irc.SendPublicChatMessage(survey.ReportResults()); } else { surveyEndOffset = 2; if (message.Contains("--t ")) { surveyEndOffset = Int32.Parse(message.Substring(message.LastIndexOf(' ') + 1)); } survey = new SurveyCommand() { Title = message.Substring(message.IndexOf(' ') + 1), AnsweredMaybe = 0, AnsweredNo = 0, AnsweredYes = 0, Start = DateTime.Now, End = DateTime.Now.AddMinutes(surveyEndOffset), IsActive = true, Participants = new List <string>() }; irc.SendPublicChatMessage(survey.GetSurveyStartedMessage()); } } } else { // General commands anyone can use if (survey.IsActive) { if (!survey.Participants.Contains(userName)) { if (message.ToLower().Equals("+")) { survey.AnsweredYes += 1; survey.Participants.Add(userName); } if (message.ToLower().Equals("-")) { survey.AnsweredNo += 1; survey.Participants.Add(userName); } if (message.ToLower().Equals("+-") || message.ToLower().Equals("+/-")) { survey.AnsweredMaybe += 1; survey.Participants.Add(userName); } } else { irc.SendPublicChatMessage($"/w {userName} Du kannst nur ein mal pro Umfrage abstimmen. Die aktuelle Umfrage läuft noch bis {survey.End.ToString("hh:mm:ss")}"); } } if (message.Equals("!hello")) { irc.SendPublicChatMessage("Hello World!"); } } } } }
static void Main(string[] args) { restrt: Console.WriteLine("Welcome to the Pok" + '\u00E9' + "bot console application!"); Console.WriteLine("**Make sure to connect your bot via the LoginInfo.txt file**"); Console.WriteLine("The bot works in chat and on the console (!pokedex not required for console)\n"); //start a new thread to find any keyboard input Thread t = new Thread(readKeyboard); t.Start(); Thread.Sleep(1); //Scan "LoginInfo.txt "file for user login info string channelMain = "", passMain = "", channel = ""; string targetFile = Directory.GetCurrentDirectory() + @"\LoginInfo.txt"; StreamReader file = new StreamReader(targetFile, true); for (int i = 0; i < 3; i++) { if (i == 0) { channelMain = file.ReadLine(); } if (i == 1) { passMain = file.ReadLine(); } if (i == 2) { channel = file.ReadLine(); } } file.Close(); refresh: //jump to here if null message is received from stream DateTime lastMessage = DateTime.Now; //Used to delay messages to counter bans GC.Collect(); //Connect to twitch irc server with login info IrcClient irc = new IrcClient("irc.twitch.tv", 6667, channelMain, passMain); irc.joinRoom(channel); //Infinite loop to check any keyboard or stream input while (true) { bool enter = false; bool advance = false; //Used to know if a picture was updated string message = irc.readMessage(); //Restart program if boolean value changes mid-loop if (restart == true) { restart = false; t.Join(); Console.Clear(); goto restrt; } //Now check for any irc messages and respond appropriately if (message == null) { //Caught this stupid guy giving me problems! //Console.Clear(); //Console.WriteLine("We hit a null message"); GC.Collect(); goto refresh; } if (message.Contains("!pokedex add")) { irc.sendChatMessage("Adding name to database..."); lastMessage = DateTime.Now; addName(message, lastMessage);//add name to data base enter = true; } if ((message.Contains("!pokedex") || message.Contains("!pdx")) && enter == false) { lastMessage = DateTime.Now; advance = updatePic(message, lastMessage);//update pokemon.png if pokemon is found if (advance == false) { advance = checkNames(message); //Look for a nickname and update } if (advance == true) { irc.sendChatMessage("Pok" + '\u00E9' + "dex updated"); //Let chat know we found the nickname } } GC.Collect(); } }
public SystemVote(IrcClient irc) { this.Irc = irc; }