Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using SteamKit2;
- using SteamKit2.Internal;
- using System.Linq;
- using System;
- using System.Collections.Concurrent;
- using System.Collections.Generic;
- using System.IO;
- using System.Security.Cryptography;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Xml;
- using System.Text;
- //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 InstructionsForTut
- {
- class Bot
- {
- static SteamClient steamClient;
- static CallbackManager manager;
- static SteamUser steamUser;
- static SteamFriends steamFriends;
- static string user, pass;
- static string authCode;
- static bool isRunning = false;
- SteamKit2.SteamID steamId = 76561197992656741;
- 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.
- }
- //Then create the console, add a title and some text if you want. Include instructions.
- //Set the title
- Console.Title = "A Bot";
- Console.WriteLine("CTRL+C quits the program.");
- //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("Username: ");
- //Console.Readline() reads the input from the user.
- user = Console.ReadLine();
- Console.Write("Password: ");
- pass = Console.ReadLine();
- //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 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 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;
- Console.WriteLine("\nConnecting to Steam...\n");
- steamClient.Connect();
- isRunning = true;
- while (isRunning)
- {
- manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
- }
- Console.ReadKey();
- }
- static void OnConnected(SteamClient.ConnectedCallback callback)
- {
- if (callback.Result != EResult.OK)
- {
- Console.WriteLine("Unable to connect to steam: {0}\n", callback.Result);
- isRunning = false;
- return;
- }
- Console.WriteLine("Connected to Steam. \nLogging in '{0}'...\n", user);
- byte[] sentryHash = null;
- if (File.Exists("sentry.bin"))
- {
- byte[] sentryFile = File.ReadAllBytes("sentry.bin");
- sentryHash = CryptoHelper.SHAHash(sentryFile);
- }
- steamUser.LogOn(new SteamUser.LogOnDetails
- {
- Username = user,
- Password = pass,
- AuthCode = authCode,
- SentryFileHash = sentryHash,
- });
- }
- static void OnLoggedOn(SteamUser.LoggedOnCallback callback)
- {
- if (callback.Result == EResult.AccountLogonDenied)
- {
- Console.WriteLine("This account is SteamGuard protected.");
- Console.Write("Please enter the auth code sent to the email at {0}: ", callback.EmailDomain);
- authCode = Console.ReadLine();
- return;
- }
- if (callback.Result != EResult.OK)
- {
- Console.WriteLine("Unable to log in to Steam: {0}\n", callback.Result);
- isRunning = false;
- return;
- }
- Console.WriteLine("Successfully logged in!", user);
- steamFriends.JoinChat(new SteamID(103582791439031144ul));
- }
- static void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback, JobID jobID)
- {
- Console.WriteLine("Updating sentry file...");
- byte[] sentryHash = CryptoHelper.SHAHash(callback.Data);
- File.WriteAllBytes("sentry.bin", callback.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 in 5...\n", user);
- //Sleep the program for 5 seconds
- Thread.Sleep(TimeSpan.FromSeconds(5));
- //attempt to reconnect
- steamClient.Connect();
- }
- //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);
- //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 message
- //We can perform specific actions based on this message
- //but for now we will just stick with responding to every message
- //with "hello"
- static void OnChatMessage(SteamFriends.FriendMsgCallback callback)
- {
- //This allows us to send a message, callback.sender is the steam ID
- //of the friend who sent the message, therefore we can use it
- //for the SendChatMessage function which requires a steam ID
- //Then, chat entry type is set to chat message in order to
- //inform steam we are sending a text based message
- //and not a "x user is typing..." or something like that
- //this if statement prevents the bot from saqying something every while you're typing
- //because the "x user is typing..." is interperated as a steam message, so
- //we need to check if it's an actual chat message
- //we're going to create a switch statement to mass-check the arguements.
- //but first we need to check if the chat message has a valid length to keep the .Remove() from crashing
- if (callback.Message.Length > 1)
- {
- //we check the first character of the message for the valid command prefix
- if (callback.Message.Remove(1) == "!")
- {
- //we set a string equal to the message so we can manipulate it without screwing up the original message
- string command = callback.Message;
- //check to see if the 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
- */
- if (command == "!gay") {
- steamFriends.SendChatRoomMessage(ChatId, EChatEntryType.ChatMsg, "Gaygaygaygaygaygaygaygaygay");
- }
- string[] args; //set up an array string for our future args
- switch (command)
- {
- //check the command to see if it is "!send"
- case "!send":
- //first we need to create a seperation function to seperate the args. so !friend [sid64] becomes args[0] = "!friend", args[1] = "sid64"
- break;
- }
- return;
- }
- }
- //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 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 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 message | response
- string text = rLine.Remove(rLine.IndexOf('|') - 1); //this will give us just '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 message contain the appropriate text?
- {
- steamFriends.SendChatRoomMessage( ChatId, EChatEntryType.ChatMsg, response); //if so, respond with the response listed in chat.txt
- sReader.Close(); //cleaning up
- return; //exit method
- }
- if (callback.Message == "hi")
- {
- steamFriends.SendChatRoomMessage( ChatId, EChatEntryType.ChatMsg, "Hey");
- 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 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;
- }
- }
- internal class JobCallback<T>
- {
- private CallbackManager manager;
- private Action<SteamUser.UpdateMachineAuthCallback, JobID> onMachineAuth;
- public JobCallback(Action<SteamUser.UpdateMachineAuthCallback, JobID> onMachineAuth, CallbackManager manager)
- {
- this.onMachineAuth = onMachineAuth;
- this.manager = manager;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement