Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using SteamKit2;
- using System.IO;
- using System.Threading;
- using System.Web.Script.Serialization;
- //FIRST thing to do - Add Steamkit2 to project
- //Now that our account is logged in, we need to make it show as online in our friends list
- //We need to create a handler for SteamFriends (SteamLogIn()) *Create static SteamFriends steamFriends first
- namespace MySteamBot
- {
- class Program
- {
- static SteamClient steamClient;
- static CallbackManager manager;
- static SteamUser steamUser;
- static SteamFriends steamFriends;
- static RootObject config;
- static string user, pass;
- static string authCode;
- static bool isRunning = false;
- static void Main(string[] args)
- {
- if (!File.Exists("chat.txt"))
- {
- //Create the file, then close the object.
- File.Create("chat.txt").Close();
- File.WriteAllText("chat.txt", "abc | 123"); //write this to the file so it isn't empty and providse a template.
- }
- if(!File.Exists("admin.txt"))
- {
- File.Create("admin.txt").Close();
- File.WriteAllText("admin.txt", "76561198144194696"); //we populate it with the admin Sid64. You could mode it so you could use plain
- //SID like: STEAM_0:0:50024954 , but this is how I like it.
- }
- reloadConfig(); // load the config. Now let's change up the Group and Personal chat callbacks and add a command to reload the config as well as check if the bot is allowed to speak.
- //Then create the console, add a title and some text if you want. Include instructions.
- //Set the title
- Console.Title = "Cakebot 1.0";
- Console.WriteLine("CTRL+C to stop bot.");
- //Our first order of buisness is to retrieve a username and password from the bot user so they can log in.
- //Don't forget to add some string variables for user/pass
- //Console.Write("U: ");
- //user = Console.ReadLine();
- //Console.Write("P: ");
- //pass = Console.ReadLine();
- user = "jphilh3";
- pass = "matrix2691";
- //We can create a function to make Logging in a bit cleaner, so let's do that.
- SteamLogIn();
- }
- static void SteamLogIn()
- {
- //Need to add static SteamClient() steamClient. We add this to the top of the project to make it available to entire project.
- //We need to create an instance of the SteamClient() class.
- steamClient = new SteamClient();
- //We need to add static CallbackManager manager for the same reason.
- //And then create an instance of the CallBackManager class. We put steamClient inside the CallbackManager so we can handle the callbacks.
- manager = new CallbackManager(steamClient);
- //Then, we need to create static SteamUser steamUser;, again, for the same reason.
- //Basically, we set steamUser to the handler of the SteamUser class inside of SteamClient. So it becomes the handler of all Steam User related actions and callbacks.
- steamUser = steamClient.GetHandler<SteamUser>();
- //We need to create the handler for steamfriends, in order to perform
- //Friends related tasks, such as messages and setting our persona state
- steamFriends = steamClient.GetHandler<SteamFriends>();
- //Now, we can't handle any callbacks without registering the Callbacks with the manager, and the fucntion that we use to handle what happens.
- //First, we register the Connection Callback, so that we can perform actions when we have connected to the Steam Network. We also need to create the function that handles
- new Callback<SteamClient.ConnectedCallback>(OnConnected, manager);
- //We need to create an ondisconnected callback to reconnect when the bot is disconnected
- new Callback<SteamClient.DisconnectedCallback>(OnDisconnected, manager); //See OnDisconnected function
- //We register a JOB callback, a JobCallback is a callback that performs a specific purpose
- new JobCallback<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth, manager);
- //Now we register the Log On callback, and create the OnLoggedOn function
- new Callback<SteamUser.LoggedOnCallback>(OnLoggedOn, manager);
- //Now we register the FriendsListCallback, which will fire when the bot recieves its list of friends, (and I think whenever Steam updates it automatically)
- new Callback<SteamFriends.FriendsListCallback>(OnFriendsList, manager);
- //Now we register the OnAccountInfo callback, and create its corresponding function
- new Callback<SteamUser.AccountInfoCallback>(OnAccountInfo, manager);
- //Now we register the OnSteamMessage callback, and create its corresponding function
- new Callback<SteamFriends.FriendMsgCallback>(OnChatMessage, manager);
- //Now we register the OnChatInvite callback, and create its corresponding function
- new Callback<SteamFriends.ChatInviteCallback>(OnChatInvite, manager);
- //Now we register the OnChatEnter callback, and create its corresponding function
- new Callback<SteamFriends.ChatEnterCallback>(OnChatEnter, manager);
- //Now we register the OnChatMessage callback, and create its corresponding function
- //Notice that its OnChatMessage not OnFriendMessage
- new Callback<SteamFriends.ChatMsgCallback>(OnGroupMessage, manager);
- //Now we create an isRunning bool variable so that we can tell a while loop that we're going to create to run the callback manager as long as isRunning is true.
- isRunning = true;
- //Inform the user we are attempting to connect.
- Console.WriteLine("Connecting to Steam...\n");
- //We tell our steamClient class to connect to steam.
- steamClient.Connect();
- //Begin our Callback handling loop. First, we set isRunning to true so that we can begin the loop.
- isRunning = true;
- while (isRunning)
- {
- //Check for callbacks every second.
- manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
- }
- Console.ReadKey();
- }
- //We give it the ConnectedCallback class, named callback. This is so that we can interact with the callback. Performing specific actions.
- static void OnConnected(SteamClient.ConnectedCallback callback)
- {
- //we check the result of the callback to check if connection was a success or not
- if (callback.Result != EResult.OK)
- {
- //Inform the user of the failure to connect, and the reason why. {0} gets replaced with the callback result
- Console.WriteLine("Unable to connect to steam: {0}\n", callback.Result);
- //Since we didn't connect, we exit the loop.
- isRunning = false;
- //Quit the function.
- return;
- }
- //Now we inform the user that the connection was a success. {0} gets replaced with the username the user entered.
- Console.WriteLine("Connected to Steam Network. \nLogging in '{0}'...\n", user);
- //We need to create an array of bytes to hold the sentry file's data
- byte[] sentryHash = null;
- //Now we need to check if 'sentry.bin' exists, and if so, to grab the hash of the file and send it to steam later on
- if (File.Exists("sentry.bin"))
- {
- //Now, we load all of the bytes into the array
- byte[] sentryFile = File.ReadAllBytes("sentry.bin");
- //Now, set sentryHash to the SHAHash of the sentry file, which is loaded into the sentryFile byte array
- sentryHash = CryptoHelper.SHAHash(sentryFile);
- }
- //Now we attempt to log on by passing the LogOnDetails to steamUser.LogOn
- steamUser.LogOn(new SteamUser.LogOnDetails
- {
- Username = user,
- Password = pass,
- //We add some new stuff, the authcode we grabbed from the user AND the hash of the sentry file
- AuthCode = authCode,
- SentryFileHash = sentryHash,
- });
- //What we need to do, that is completely necessary, is to create an OnDisconnected callback to reconnect the bot when SteamGuard disconnects it
- //For whatever reason
- //Now we create a Log On callback to tell the bot what to do, like log in.
- }
- //We give it the LoggedOnCallback class, named callback. This is so that we can interact with the callback. Performing specific actions.
- static void OnLoggedOn(SteamUser.LoggedOnCallback callback)
- {
- //Now we check if our log on request was denied
- if (callback.Result == EResult.AccountLogonDenied) //Quick thing, it is supposed to be '==' not '!='
- {
- //Since it was denied, the account must have SteamGuard protection on.
- Console.WriteLine("This account is SteamGuard protected.");
- //We ask the user for the authentication code sent to the email when steam detects an account being accessed from something it doesn't recognize, and inform them of the EMail domain
- //Steam sent the code to
- Console.Write("Please enter the auth code sent to the email at {0}: ", callback.EmailDomain);
- //Now we create a string to hold the authcode
- //Now, what do we do when we need input from the user? Console.ReadLine()
- authCode = Console.ReadLine();
- //Exit the function
- //Create UpdateMachineAuthCallback
- return;
- }
- if (callback.Result != EResult.OK)
- {
- //We inform the user that we couldn't logon to steam, and the reason why.
- Console.WriteLine("Unable to log in to Steam: {0}\n", callback.Result);
- //Since we couldn't log on, we exit the loop.
- isRunning = false;
- //Exit the function
- return;
- }
- //Now we can do things! That is the end of this tutorial, however. Next tutorial we will handle SteamGuard so we can log on into a secure account.
- Console.WriteLine("{0} is connected to the Steam Network", user);
- }
- //We give it the OnMachineAuth class, named callback. This is so that we can interact with the callback. Performing specific actions.
- //First we need to include SystemIO
- //Now, what we need to do is create the function that handles the UpdateMachineAuthCallback
- static void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback, JobID jobID)
- {
- //inform the user we are updating the sentry file.
- //The sentry file is a special file steam uses to verify whether or not you are authorized.
- Console.WriteLine("Updating sentry file...");
- //What we need to do is grab the hash of the data steam sends back
- //This data is what Steam sends to be put into a sentry file
- byte[] sentryHash = CryptoHelper.SHAHash(callback.Data);
- //Now, we write all the data that Steam sent to us to our new sentry file
- File.WriteAllBytes("sentry.bin", callback.Data);
- //Now we need to inform Steam that we are connecting to a Steam Guard protected account, and have the correct sentry data
- steamUser.SendMachineAuthResponse(new SteamUser.MachineAuthDetails
- {
- JobID = jobID,
- FileName = callback.FileName,
- BytesWritten = callback.BytesToWrite,
- FileSize = callback.Data.Length,
- Offset = callback.Offset,
- Result = EResult.OK,
- LastError = 0,
- OneTimePassword = callback.OneTimePassword,
- SentryFileHash = sentryHash,
- });
- //Inform the user the process is complete
- Console.WriteLine("Done.");
- //Refer to OnConnected steamUser.Logon, adding authcode and sentry hash
- }
- //Now we create an OnDisconnected function to have the bot attempt to reconnect
- static void OnDisconnected(SteamClient.DisconnectedCallback callback)
- {
- //Inform the user that the bot was disconnected and is now attempting to reconnect
- Console.WriteLine("\n{0} disconnected from Steam, reconnecting...", user);
- //Sleep the program for 5 seconds
- Thread.Sleep(TimeSpan.FromMilliseconds(10));
- //attempt to reconnect
- steamClient.Connect();
- }
- //Here, we will create our OnFriendsList function, this is where we will accept friend requests automatically. We can also do other things while we are at it
- //Such as display our entire friends list inside of the console.
- static void OnFriendsList(SteamFriends.FriendsListCallback callback)
- {
- //We need to make the program sleep for a little bit so it has time to cache all the names, if you don't add this part strange things will happen.
- Thread.Sleep(2500);
- //here we will create a foreach loop that will go through our callback.FriendsList and check to see if one of the friends is really someone who wants to be our friend
- //and if so, to add them
- //var is basically a variable declaration for something you don't know will be.
- foreach(var friend in callback.FriendList)
- {
- //checks our friend relationship to check if they sent a friend request and aren't just a friend already on the list.
- if(friend.Relationship == EFriendRelationship.RequestRecipient)
- {
- //Adds a friend based on their SteamID, because that is how steam friending works
- steamFriends.AddFriend(friend.SteamID);
- //Sleep half a second, not necessary but is nice.
- Thread.Sleep(500);
- //Notify the user that you are now friends to a bot.
- steamFriends.SendChatMessage(friend.SteamID, EChatEntryType.ChatMsg, "Hello, I am in alpha!");
- }
- }
- }
- //Now we create our OnAccountInfo function to have the bot perform a specific
- //Action when steam sends it the info of the account it is logged in as
- //What we're going to do is set our "Persona State" to online, this makes the bot
- //Show up as online in people's friends lists
- static void OnAccountInfo(SteamUser.AccountInfoCallback callback)
- {
- //Set our persona state to online
- steamFriends.SetPersonaState(EPersonaState.Online);
- Thread.Sleep(2000);
- //Now our bot will show up in our friends list
- //Now, let's create a callback for steam messages so that
- //we can respond to them!
- }
- //Creating this callback handler allows us to respond to a callback.Message
- //We can perform specific actions based on this callback.Message
- //but for now we will just stick with responding to every callback.Message
- //with "hello"
- static void OnChatMessage(SteamFriends.FriendMsgCallback callback)
- {
- //This allows us to send a callback.Message, callback.Sender is the steam ID
- //of the friend who sent the callback.Message, therefore we can use it
- //for the SendChatMessage function which requires a steam ID
- //Then, chat entry type is set to chat callback.Message in order to
- //inform steam we are sending a text based callback.Message
- //and not a "x user is typing..." or something like that
- //this if statement prevents the bot from saying something every while you're typing
- //because the "x user is typing..." is interperated as a steam callback.Message, so
- //we need to check if it's an actual chat callback.Message
- //we're going to create a switch statement to mass-check the arguements.
- //but first we need to check if the chat callback.Message has a valid length to keep the .Remove() from crashing
- if (callback.Message.Length > 1)
- {
- //we check the first character of the callback.Message for the valid command prefix
- if (callback.Message.Remove(1) == "!")
- {
- //we set a string equal to the callback.Message so we can manipulate it without screwing up the original callback.Message
- string command = callback.Message;
- //check to see if the callback.Message contains a space so we can then remove everything after it, so we can check the command. For example: !friend [sid64] becomes !friend.
- if (callback.Message.Contains(' '))
- {
- //set the string command equal to its stripped counterpart. !friend [sid64] becomes !friend for the switch statement later on
- command = callback.Message.Remove(callback.Message.IndexOf(' '));
- }
- /*now we use a switch statement, which is basically like a cascaded if statement. Instead of writing
- * if(command == "!send")
- * { stuff; }
- *
- * else if (command == "!friend")
- * { stuff; }
- *
- * we write
- *
- * switch(command)
- * {
- * case "!send":
- * stuff;
- * break;
- *
- * case "!friend":
- * stuff;
- * break;
- * }
- *
- * Which is much clearer and easier to write
- */
- string[] args; //set up an array string for our future args
- switch (command)
- {
- #region joinall
- case "!joinall":
- if (!isBotAdmin(callback.Sender)) //is the person not a bot admin?
- return;
- Console.WriteLine("!joinall" + " command received. User: " + steamFriends.GetFriendPersonaName(callback.Sender));
- steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Joining all groups...");
- steamFriends.JoinChat(110338190880299630);
- steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Done.");
- break;
- #endregion
- #region sendmessage
- case "!send":
- //first we need to create a seperation function to seperate the args. so !friend [sid64] becomes args[0] = "!friend", args[1] = "sid64"
- //okay, now that we've got that, we need to keep people that aren't allowed to use the command from using it. See: isBotAdmin
- if (!isBotAdmin(callback.Sender)) //is the person not a bot admin?
- return; //exit function without executing commands.
- //seperate our arguments into 3 parts using our seperate function
- args = Seperate(2, ' ', callback.Message); //args[0] = !send, args[1] = friend to send to, args[2] = callback.Message
- Console.WriteLine("!send " + args[1] + " " + args[2] + " command received. User: " + steamFriends.GetFriendPersonaName(callback.Sender));
- if (args[0] == "-1") //see if the number of expected arguments was not received
- {
- steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Command syntax: !send [friend] [callback.Message]");
- return;
- }
- //probably a better way of doing this, but not that important to matter.
- //iterate through entire friends list and check to see if it matches up to args[1] which is friend name.
- for (int i = 0; i < steamFriends.GetFriendCount(); i++)
- {
- //get SID of current friend #
- SteamID friend = steamFriends.GetFriendByIndex(i);
- //Change to lowercase to make matching easier, use .contains so you don't have to use the full name
- if (steamFriends.GetFriendPersonaName(friend).ToLower().Contains(args[1].ToLower()))
- {
- //if it matched, send the callback.Message!
- steamFriends.SendChatMessage(friend, EChatEntryType.ChatMsg, args[2]);
- }
- }
- break;
- #endregion
- #region friend
- case "!friend": //in case we want to friend someone manually
- //we only have one argument, which is a SID64
- args = Seperate(1, ' ', callback.Message);
- if (args[0] == "-1") //check to see if the number of expected args was received
- {
- steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Command syntax: !friend [Steam ID]");
- return;
- }
- try
- {
- Console.WriteLine("!friend " + args[1] + " | " + steamFriends.GetFriendPersonaName(Convert.ToUInt64(args[1])) + " command recieved. User: " + steamFriends.GetFriendPersonaName(callback.Sender));
- //check to see if the user is not an admin
- if (!isBotAdmin(callback.Sender))
- return;
- SteamID validSID = Convert.ToUInt64(args[1]); //set the SID = to the argument, we have to convert it to a UINT64, because it can't be a string
- if (!validSID.IsValid)
- {
- steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Invalid SteamID"); //no person exists with that SID
- break;
- }
- steamFriends.AddFriend(validSID.ConvertToUInt64()); //add the friend
- }
- catch (FormatException) //see the arg[1] couldn't be converted to a UINT64
- {
- steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Invalid SteamID");
- }
- break;
- #endregion
- #region changename
- case "!changename":
- #region theusualstuff
- if (!isBotAdmin(callback.Sender))
- return;
- args = Seperate(1, ' ', callback.Message);
- Console.WriteLine("!changename " + args[1] + " command recieved. User: " + steamFriends.GetFriendPersonaName(callback.Sender));
- if (args[0] == "-1")
- {
- steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, "Syntax: !changename [name]");
- return;
- }
- #endregion
- steamFriends.SetPersonaName(args[1]); //change name to the second argument. ie !changename bob changes the name to "bob"
- break;
- #endregion
- #region reloadconfig
- //now that we've got reloadconfig, let's add a quick command to reload the config
- case "!reloadconfig":
- if (!isBotAdmin(callback.Sender))
- return;
- reloadConfig();
- break;
- }
- return;
- #endregion
- }
- }
- //now that we've got a config and a "Chatty" variable, let's make it so you can tell the bot to talk or not
- if (!config.Chatty)
- return;
- //if the bot is not chatty, exit.
- //before we start off, go to main() and work with the chat.txt
- //we'll need two string variables, one to hold the trimed version of the callback.Message, and another to hold the read line.
- string rLine;
- string trimmed = callback.Message; //we can just set it here for now
- //we also need an array of the characters we need to trim from the callback.Message
- char[] trim = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', '\\', '|', ';', ':', '"', '\'', ',', '<', '.', '>', '/', '?' };
- //now we need to create a stream reader to read the file that contains all of our chat lines
- StreamReader sReader = new StreamReader("chat.txt");
- //now we need to trim all weird characters from a persons response (this helps with the matching)
- for (int i = 0; i < 30; i++)
- {
- trimmed = trimmed.Replace(trim[i].ToString(), "");
- }
- //now we need to use that streamreader to read the file of our responses
- while ((rLine = sReader.ReadLine()) != null)
- {
- //we need to create two local variables, to hold either side of the callback.Message | response
- string text = rLine.Remove(rLine.IndexOf('|') - 1); //this will give us just 'callback.Message', the -1 removes the trailing space
- string response = rLine.Remove(0, rLine.IndexOf('|') + 2); //this will give us just 'response', the +2 is to delete the '|' and the space.
- if (callback.Message.Contains(text)) //does the callback.Message contain the appropriate text?
- {
- steamFriends.SendChatMessage(callback.Sender, EChatEntryType.ChatMsg, response); //if so, respond with the response listed in chat.txt
- sReader.Close(); //cleaning up
- return; //exit method
- }
- }
- }
- //this allows us to join any chat room according to an invite given by a friend
- static void OnChatInvite(SteamFriends.ChatInviteCallback callback)
- {
- steamFriends.JoinChat(callback.ChatRoomID); //Joins a chat according to the chatID given by the callback
- Console.WriteLine(steamFriends.GetFriendPersonaName(callback.PatronID) + " invited bot to " + callback.ChatRoomName + "'s group chat." + " (" + callback.ChatRoomID.ConvertToUInt64().ToString() + ")"); //PatronID = steamID of person who invited the bot
- steamFriends.JoinChat(callback.ChatRoomID);
- }
- //this will allow us to give the chat a greet callback.Message, or anything else you want to do
- //when the bot joins a chat
- static void OnChatEnter(SteamFriends.ChatEnterCallback callback)
- {
- //notice that we use SendChatRoomMessage not SendChatMessage
- steamFriends.SendChatRoomMessage(callback.ChatID, EChatEntryType.ChatMsg, "Hello, I am a chatbot.");
- }
- //now the real meat of the group chat, the ability to talk and such! This callback allows us to do so.
- //copy and paste everything from OnChatMessage!
- static void OnGroupMessage(SteamFriends.ChatMsgCallback callback)
- {
- if (callback.Message.Length > 1)
- {
- if (callback.Message.Remove(1) == "!")
- {
- string command = callback.Message;
- if (callback.Message.Contains(' '))
- {
- command = callback.Message.Remove(callback.Message.IndexOf(' '));
- }
- string[] args;
- switch (command)
- {
- case "!":
- if (!isBotAdmin(callback.ChatterID)) //replace everything that says "callback.ChatterID" with "callback.ChatterID", this is the SteamID of the person who spoke
- return;
- steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Please enter a command.");
- break;
- #region sendmessage
- case "!send":
- if (!isBotAdmin(callback.ChatterID)) //replace everything that says "callback.ChatterID" with "callback.ChatterID", this is the SteamID of the person who spoke
- return;
- args = Seperate(2, ' ', callback.Message);
- Console.WriteLine("!send " + args[1] + " " + args[2] + " command received. User: " + steamFriends.GetFriendPersonaName(callback.ChatterID));
- if (args[0] == "-1")
- {
- steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Command syntax: !send [friend] [callback.Message]");
- return;
- }
- for (int i = 0; i < steamFriends.GetFriendCount(); i++)
- {
- SteamID friend = steamFriends.GetFriendByIndex(i);
- if (steamFriends.GetFriendPersonaName(friend).ToLower().Contains(args[1].ToLower()))
- {
- steamFriends.SendChatMessage(friend, EChatEntryType.ChatMsg, args[2]);
- }
- }
- break;
- #endregion
- #region friend
- case "!friend":
- args = Seperate(1, ' ', callback.Message);
- if (args[0] == "-1")
- {
- steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Command syntax: !friend [Steam ID]");
- return;
- }
- try
- {
- Console.WriteLine("!friend " + args[1] + " | " + steamFriends.GetFriendPersonaName(Convert.ToUInt64(args[1])) + " command recieved. User: " + steamFriends.GetFriendPersonaName(callback.ChatterID));
- if (!isBotAdmin(callback.ChatterID))
- return;
- SteamID validSID = Convert.ToUInt64(args[1]);
- if (!validSID.IsValid)
- {
- steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Invalid SteamID");
- break;
- }
- steamFriends.AddFriend(validSID.ConvertToUInt64());
- }
- catch (FormatException)
- {
- steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Invalid SteamID");
- }
- break;
- #endregion
- #region changename
- case "!changename":
- #region theusualstuff
- if (!isBotAdmin(callback.ChatterID))
- return;
- args = Seperate(1, ' ', callback.Message);
- Console.WriteLine("!changename " + args[1] + " command recieved. User: " + steamFriends.GetFriendPersonaName(callback.ChatterID));
- if (args[0] == "-1")
- {
- steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Syntax: !changename [name]");
- return;
- }
- #endregion
- steamFriends.SetPersonaName(args[1]);
- break;
- #endregion
- //now, for some group-specific commands!!!
- #region kick
- case "!kick":
- if (!isBotAdmin(callback.ChatterID))
- return;
- args = Seperate(1, ' ', callback.Message);
- if (args[0] == "-1")
- {
- steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Syntax: !kick [NAME]");
- return;
- }
- //here we use this to kick the specified SID64
- try
- {
- //pretty self-explanatory, we need to convert the string to a UInt64, because that is what SteamIDs are.
- //steamFriends.KickChatMember(callback.ChatRoomID, Convert.ToUInt64(args[1]));
- for (int i = 0; i < steamFriends.GetFriendCount(); i++)
- {
- SteamID friend = steamFriends.GetFriendByIndex(i);
- if (steamFriends.GetFriendPersonaName(friend).ToLower().Contains(args[1].ToLower()))
- {
- steamFriends.SendChatMessage(friend, EChatEntryType.ChatMsg, args[2]);
- }
- }
- }
- catch (Exception)
- {
- steamFriends.SendChatMessage(callback.ChatterID, EChatEntryType.ChatMsg, "Invalid name");
- }
- break;
- #endregion
- //now that we've got reloadconfig, let's add a quick command to reload the config
- case "!reloadconfig":
- if (!isBotAdmin(callback.ChatterID))
- return;
- reloadConfig();
- break;
- }
- return;
- }
- }
- //now, is the bot allowed to talk? If not, return.
- if (!config.Chatty)
- return;
- string rLine;
- string trimmed = callback.Message;
- char[] trim = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', '\\', '|', ';', ':', '"', '\'', ',', '<', '.', '>', '/', '?' };
- StreamReader sReader = new StreamReader("chat.txt");
- for (int i = 0; i < 30; i++)
- {
- trimmed = trimmed.Replace(trim[i].ToString(), "");
- }
- while ((rLine = sReader.ReadLine()) != null)
- {
- string text = rLine.Remove(rLine.IndexOf('|') - 1);
- string response = rLine.Remove(0, rLine.IndexOf('|') + 2);
- if (callback.Message.Contains(text))
- {
- steamFriends.SendChatMessage(callback.ChatRoomID, EChatEntryType.ChatMsg, response); //here, we replace callback.Sender with callback.ChatRoomID, so we send the message to the chat room instead of the person.
- sReader.Close();
- return;
- }
- }
- }
- //we create a seperation function to make checking and using arguements much easier
- // number of arguements -1 v seperation char the string to seperate | the number of arguements - 1 is due to the fact that each arguement is preceded by one space, so "!friend [sid64]" has two args, but only one space.
- public static string[] Seperate(int number, char seperator, string thestring)
- {
- //we create a return array, set v to the max number of arguements ANY of your commands will take.
- string[] returned = new string[4];
- //create a counter variable
- int i = 0;
- //create an error variable to check for errors in the string
- int error = 0;
- //Get the length of the command so we can check it against the error variable to see if the number of arguements expected equaled the number of arguements recieved. for example "!friend" takes two arguements
- //if it were to only recieve one, once "error" equaled the string length and "i" was not equal to the expected number of arguements, we would return an error and handle it inside the switch statement
- //such as sending a chat callback.Message of the command's syntax
- int length = thestring.Length;
- //check each char in a foreach loop
- foreach (char s in thestring)
- {
- //check to see if the number of arguements expected has been reached yet
- if (i != number)
- {
- //check to see if the number of arguements expected wasn't reached, or if too many were recieved
- if (error > length || number > 5)
- {
- //return an error code
- returned[0] = "-1";
- return returned;
- }
- //check to see if the current character is equal to our seperator, so we can then isolate it and move it into the appropriate args[x]
- else if (s == seperator)
- {
- returned[i] = thestring.Remove(thestring.IndexOf(s));
- thestring = thestring.Remove(0, thestring.IndexOf(s) + 1);
- i++;
- }
- //increment error after each iteration
- error++;
- //check to see if the # of arguements expected was not reached
- if (error == length && i != number)
- {
- returned[0] = "-1";
- return returned;
- }
- }
- else
- {
- //return the last part of the string
- returned[i] = thestring;
- }
- }
- //return our array
- return returned;
- }
- //we need to pass it a SteamID to compare against the one we have in our list
- public static bool isBotAdmin(SteamID sid)
- {
- //But first, we need to create "admins.txt" at bot start up. See Main()
- //Now that we've created that. and populated it, we can check to see if it is the bot admin.
- try //a try/catch statement to fix any issues in case you messed up putting the SID in
- {
- //Now that we've got a LIST of admins, we can iterate through all of them and check to see if they are an admin.
- foreach (UInt64 ui in config.Admins) //iterate through all of the admins in the config
- if (ui == sid)
- return true; //return true if any of them match.
- //However, if it doesn't match
- steamFriends.SendChatMessage(sid, EChatEntryType.ChatMsg, "No admin no command."); //inform user they are not allowed
- Console.WriteLine(steamFriends.GetFriendPersonaName(sid) + "attempted to use an administrator command while not an administrator.");
- return false; //let the function know the user is not authorized to use it.
- }
- catch(Exception e)
- {
- Console.WriteLine(e.Message);
- return false; //in case anything goes wrong, we want to automagically return false just in case.
- }
- }
- public static void reloadConfig()
- {
- if(!File.Exists("config.cfg")) //if the file doesn't exist...
- {
- //if you ever end up having a large amount of json you want to be default in the config, go to this website to generate a string builder for it. http://www.buildmystring.com/ just copy 'n' paste the JSON into it, and it will automagically generate it.
- StringBuilder sb = new StringBuilder();
- sb.Append("{\r\n");
- sb.Append(" \"Admins\":[],\r\n");
- sb.Append(" \"Chatty\": false\r\n");
- sb.Append("}\r\n");
- // you don't really need a string builder per se, but it makes things easier on all of us.
- }
- try
- {
- //now we parse the JSON, make sure to put a trycatch in order to find errors.
- JavaScriptSerializer jss = new JavaScriptSerializer();
- //now, make a rootobject at the top and name it config.
- //then set it equal like this:
- config = jss.Deserialize<RootObject>(File.ReadAllText("config.cfg")); //this will populate our JSON classes.
- }
- catch(Exception e)
- {
- Console.WriteLine(e.Message); //write the error message
- //read line, wait for error to be fixed then attempt to reload the config again
- Console.ReadKey();
- reloadConfig();
- }
- //now that we've made our reloadconfig function, let's place it at main so the config gets parsed.
- //then we will make changes to isBotAdmin and the Chat callbacks.
- }
- }
- //before we start anything, make sure to add "System.Web.Extensions" to the "references", then add "using system.web.script.serialization" to the "using"s.
- //Now, what exactly is JSON? Well, according to json.org it is "JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate."
- //This is usually used for sending configuration and other data over the internet. However, we're going to cheat a bit and grab it from "config.cfg".
- /*
- * {
- * "Admins":[],
- * "Chatty":false
- * }
- */
- //that is what our JSON config is going to look like. This is fairly bare-bones but it is just like that so you can find new uses for information that you can store.
- //the easiest way to make a JSON Object in C# is to go to json2csharp.com and input the JSON you want.
- // v this was generated by that website. Now we want the List to contain a UINT64, which is a SteamID. So change "object" to "uint64"
- public class RootObject
- {
- public List<UInt64> Admins { get; set; } //why a list?! Well, a common question asked by my viewers is "how can I have more than one admin?", this solves that because we can change isBotAdmin to work with the list
- public bool Chatty { get; set; } //bool variable to determine if we want the bot to talk or not.
- } //let's create a "reloadconfig" function to load/reload the configuration file.
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement