Advertisement
Guest User

Untitled

a guest
Feb 11th, 2016
862
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 18.13 KB | None | 0 0
  1. using SteamKit2;
  2. using SteamKit2.Internal;
  3. using System.Linq;
  4. using System;
  5. using System.Collections.Concurrent;
  6. using System.Collections.Generic;
  7. using System.IO;
  8. using System.Security.Cryptography;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using System.Xml;
  12. using System.Text;
  13.  
  14. //FIRST thing to do - Add Steamkit2 to project
  15.  
  16. //Now that our account is logged in, we need to make it show as online in our friends list
  17. //We need to create a handler for SteamFriends (SteamLogIn()) *Create static SteamFriends steamFriends first
  18. namespace InstructionsForTut
  19. {
  20.     class Bot
  21.     {
  22.  
  23.         static SteamClient steamClient;
  24.         static CallbackManager manager;
  25.         static SteamUser steamUser;
  26.         static SteamFriends steamFriends;
  27.         static string user, pass;
  28.         static string authCode;
  29.         static bool isRunning = false;
  30.         SteamKit2.SteamID steamId = 76561197992656741;
  31.  
  32.         static void Main(string[] args)
  33.         {
  34.             if (!File.Exists("chat.txt"))
  35.             {
  36.                 //Create the file, then close the object.
  37.                 File.Create("chat.txt").Close();
  38.                 File.WriteAllText("chat.txt", "abc | 123"); //write this to the file so it isn't empty and providse a template.
  39.             }
  40.  
  41.             //Then create the console, add a title and some text if you want. Include instructions.
  42.             //Set the title
  43.             Console.Title = "A Bot";
  44.             Console.WriteLine("CTRL+C quits the program.");
  45.             //Our first order of buisness is to retrieve a username and password from the bot user so they can log in.
  46.             //Don't forget to add some string variables for user/pass
  47.             Console.Write("Username: ");
  48.             //Console.Readline() reads the input from the user.
  49.             user = Console.ReadLine();
  50.  
  51.             Console.Write("Password: ");
  52.             pass = Console.ReadLine();
  53.             //We can create a function to make Logging in a bit cleaner, so let's do that.
  54.             SteamLogIn();
  55.         }
  56.         static void SteamLogIn()
  57.         {
  58.             //Need to add static SteamClient() steamClient. We add this to the top of the project to make it available to entire project.
  59.             //We need to create an instance of the SteamClient() class.
  60.             steamClient = new SteamClient();
  61.  
  62.             //We need to add static CallbackManager manager for the same reason.
  63.             //And then create an instance of the CallBackManager class. We put steamClient inside the CallbackManager so we can handle the callbacks.
  64.             manager = new CallbackManager(steamClient);
  65.  
  66.             //Then, we need to create static SteamUser steamUser;, again, for the same reason.
  67.             //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.
  68.             steamUser = steamClient.GetHandler<SteamUser>();
  69.  
  70.  
  71.             //We need to create the handler for steamfriends, in order to perform
  72.             //Friends related tasks, such as messages and setting our persona state
  73.             steamFriends = steamClient.GetHandler<SteamFriends>();
  74.  
  75.  
  76.             //Now, we can't handle any callbacks without registering the Callbacks with the manager, and the fucntion that we use to handle what happens.
  77.             //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
  78.             new Callback<SteamClient.ConnectedCallback>(OnConnected, manager);
  79.  
  80.             //We need to create an ondisconnected callback to reconnect when the bot is disconnected
  81.             new Callback<SteamClient.DisconnectedCallback>(OnDisconnected, manager); //See OnDisconnected function
  82.  
  83.             //We register a JOB callback, a JobCallback is a callback that performs a specific purpose
  84.             new JobCallback<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth, manager);
  85.  
  86.             //Now we register the Log On callback, and create the OnLoggedOn function
  87.             new Callback<SteamUser.LoggedOnCallback>(OnLoggedOn, manager);
  88.  
  89.             //Now we register the OnAccountInfo callback, and create its corresponding function
  90.             new Callback<SteamUser.AccountInfoCallback>(OnAccountInfo, manager);
  91.  
  92.             //Now we register the OnSteamMessage callback, and create its corresponding function
  93.             new Callback<SteamFriends.FriendMsgCallback>(OnChatMessage, manager);
  94.  
  95.             //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.
  96.             isRunning = true;
  97.             Console.WriteLine("\nConnecting to Steam...\n");
  98.             steamClient.Connect();
  99.             isRunning = true;
  100.             while (isRunning)
  101.             {
  102.                 manager.RunWaitCallbacks(TimeSpan.FromSeconds(1));
  103.             }
  104.             Console.ReadKey();
  105.         }
  106.  
  107.         static void OnConnected(SteamClient.ConnectedCallback callback)
  108.         {
  109.             if (callback.Result != EResult.OK)
  110.             {
  111.                 Console.WriteLine("Unable to connect to steam: {0}\n", callback.Result);
  112.                 isRunning = false;
  113.                 return;
  114.             }
  115.            
  116.             Console.WriteLine("Connected to Steam. \nLogging in '{0}'...\n", user);
  117.             byte[] sentryHash = null;
  118.             if (File.Exists("sentry.bin"))
  119.             {
  120.                 byte[] sentryFile = File.ReadAllBytes("sentry.bin");
  121.                 sentryHash = CryptoHelper.SHAHash(sentryFile);
  122.             }
  123.             steamUser.LogOn(new SteamUser.LogOnDetails
  124.             {
  125.                 Username = user,
  126.                 Password = pass,
  127.                 AuthCode = authCode,
  128.  
  129.                 SentryFileHash = sentryHash,
  130.             });
  131.  
  132.  
  133.         }
  134.  
  135.         static void OnLoggedOn(SteamUser.LoggedOnCallback callback)
  136.         {
  137.             if (callback.Result == EResult.AccountLogonDenied)
  138.             {
  139.                 Console.WriteLine("This account is SteamGuard protected.");
  140.                 Console.Write("Please enter the auth code sent to the email at {0}: ", callback.EmailDomain);
  141.                 authCode = Console.ReadLine();
  142.                 return;
  143.             }
  144.             if (callback.Result != EResult.OK)
  145.             {
  146.                 Console.WriteLine("Unable to log in to Steam: {0}\n", callback.Result);
  147.                 isRunning = false;
  148.                 return;
  149.             }            
  150.             Console.WriteLine("Successfully logged in!", user);
  151.             steamFriends.JoinChat(new SteamID(103582791439031144ul));
  152.         }
  153.  
  154.         static void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback, JobID jobID)
  155.         {
  156.             Console.WriteLine("Updating sentry file...");
  157.             byte[] sentryHash = CryptoHelper.SHAHash(callback.Data);
  158.             File.WriteAllBytes("sentry.bin", callback.Data);
  159.             steamUser.SendMachineAuthResponse(new SteamUser.MachineAuthDetails
  160.             {
  161.                 JobID = jobID,
  162.                 FileName = callback.FileName,
  163.                 BytesWritten = callback.BytesToWrite,
  164.                 FileSize = callback.Data.Length,
  165.                 Offset = callback.Offset,
  166.                 Result = EResult.OK,
  167.                 LastError = 0,
  168.                 OneTimePassword = callback.OneTimePassword,
  169.                 SentryFileHash = sentryHash,
  170.             });
  171.             //Inform the user the process is complete
  172.             Console.WriteLine("Done.");
  173.             //Refer to OnConnected steamUser.Logon, adding authcode and sentry hash
  174.         }
  175.  
  176.         //Now we create an OnDisconnected function to have the bot attempt to reconnect
  177.         static void OnDisconnected(SteamClient.DisconnectedCallback callback)
  178.         {
  179.             //Inform the user that the bot was disconnected and is now attempting to reconnect
  180.             Console.WriteLine("\n{0} disconnected from Steam, reconnecting in 5...\n", user);
  181.             //Sleep the program for 5 seconds
  182.             Thread.Sleep(TimeSpan.FromSeconds(5));
  183.             //attempt to reconnect
  184.             steamClient.Connect();
  185.         }
  186.  
  187.  
  188.         //Now we create our OnAccountInfo function to have the bot perform a specific
  189.         //Action when steam sends it the info of the account it is logged in as
  190.         //What we're going to do is set our "Persona State" to online, this makes the bot
  191.         //Show up as online in people's friends lists
  192.         static void OnAccountInfo(SteamUser.AccountInfoCallback callback)
  193.         {
  194.             //Set our persona state to online
  195.             steamFriends.SetPersonaState(EPersonaState.Online);
  196.             //Now our bot will show up in our friends list
  197.             //Now, let's create a callback for steam messages so that
  198.             //we can respond to them!
  199.         }
  200.  
  201.         //Creating this callback handler allows us to respond to a message
  202.         //We can perform specific actions based on this message
  203.         //but for now we will just stick with responding to every message
  204.         //with "hello"
  205.         static void OnChatMessage(SteamFriends.FriendMsgCallback callback)
  206.         {
  207.             //This allows us to send a message, callback.sender is the steam ID
  208.             //of the friend who sent the message, therefore we can use it
  209.             //for the SendChatMessage function which requires a steam ID
  210.             //Then, chat entry type is set to chat message in order to
  211.             //inform steam we are sending a text based message
  212.             //and not a "x user is typing..." or something like that
  213.  
  214.             //this if statement prevents the bot from saqying something every while you're typing
  215.             //because the "x user is typing..." is interperated as a steam message, so
  216.             //we need to check if it's an actual chat message
  217.  
  218.             //we're going to create a switch statement to mass-check the arguements.
  219.  
  220.             //but first we need to check if the chat message has a valid length to keep the .Remove() from crashing
  221.             if (callback.Message.Length > 1)
  222.             {
  223.                 //we check the first character of the message for the valid command prefix
  224.                 if (callback.Message.Remove(1) == "!")
  225.                 {
  226.                     //we set a string equal to the message so we can manipulate it without screwing up the original message
  227.                     string command = callback.Message;
  228.                     //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.
  229.                     if (callback.Message.Contains(' '))
  230.                     {
  231.                         //set the string command equal to its stripped counterpart. !friend [sid64] becomes !friend for the switch statement later on
  232.                         command = callback.Message.Remove(callback.Message.IndexOf(' '));
  233.                     }
  234.  
  235.                     /*now we use a switch statement, which is basically like a cascaded if statement. Instead of writing
  236.                      if(command == "!send") {
  237.                            
  238.                      }
  239.  
  240.                      * { stuff; }
  241.                      *
  242.                      * else if (command == "!friend")
  243.                      * { stuff; }
  244.                      *
  245.                      * we write
  246.                      *
  247.                      * switch(command)
  248.                      * {
  249.                      * case "!send":
  250.                      * stuff;
  251.                      * break;
  252.                      *
  253.                      * case "!friend":
  254.                      * stuff;
  255.                      * break;
  256.                      * }
  257.                      *
  258.                      * Which is much clearer and easier to write
  259.                      */
  260.  
  261.                     if (command == "!gay") {
  262.                         steamFriends.SendChatRoomMessage(ChatId, EChatEntryType.ChatMsg, "Gaygaygaygaygaygaygaygaygay");
  263.                     }
  264.  
  265.                     string[] args; //set up an array string for our future args
  266.                     switch (command)
  267.                     {
  268.                         //check the command to see if it is "!send"
  269.                         case "!send":
  270.                         //first we need to create a seperation function to seperate the args. so !friend [sid64] becomes args[0] = "!friend", args[1] = "sid64"
  271.                         break;
  272.                     }
  273.                     return;
  274.                 }
  275.             }
  276.             //before we start off, go to main() and work with the chat.txt
  277.             //we'll need two string variables, one to hold the trimed version of the message, and another to hold the read line.
  278.             string rLine;
  279.             string trimmed = callback.Message; //we can just set it here for now
  280.             //we also need an array of the characters we need to trim from the message
  281.             char[] trim = { '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', ']', '{', '}', '\\', '|', ';', ':', '"', '\'', ',', '<', '.', '>', '/', '?' };
  282.  
  283.             //now we need to create a stream reader to read the file that contains all of our chat lines
  284.             StreamReader sReader = new StreamReader("chat.txt");
  285.             //now we need to trim all weird characters from a persons response (this helps with the matching)
  286.             for (int i = 0; i < 30; i++)
  287.             {
  288.                 trimmed = trimmed.Replace(trim[i].ToString(), "");
  289.             }
  290.             //now we need to use that streamreader to read the file of our responses
  291.             while ((rLine = sReader.ReadLine()) != null)
  292.             {
  293.                 //we need to create two local variables, to hold either side of the message | response
  294.                 string text = rLine.Remove(rLine.IndexOf('|') - 1); //this will give us just 'message', the -1 removes the trailing space
  295.                 string response = rLine.Remove(0, rLine.IndexOf('|') + 2); //this will give us just 'response', the +2 is to delete the '|' and the space.
  296.                 if (callback.Message.Contains(text)) //does the message contain the appropriate text?
  297.                 {
  298.                     steamFriends.SendChatRoomMessage( ChatId, EChatEntryType.ChatMsg, response); //if so, respond with the response listed in chat.txt
  299.                     sReader.Close(); //cleaning up
  300.                     return; //exit method
  301.                 }
  302.                 if (callback.Message == "hi")
  303.                 {
  304.                     steamFriends.SendChatRoomMessage( ChatId, EChatEntryType.ChatMsg, "Hey");
  305.                     sReader.Close();
  306.                     return;
  307.                 }
  308.             }
  309.         }
  310.  
  311.         //we create a seperation function to make checking and using arguements much easier
  312.         //           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.
  313.         public static string[] Seperate(int number, char seperator, string thestring)
  314.         {
  315.             //we create a return array, set v to the max number of arguements ANY of your commands will take.
  316.             string[] returned = new string[4];
  317.             //create a counter variable
  318.             int i = 0;
  319.             //create an error variable to check for errors in the string
  320.             int error = 0;
  321.             //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
  322.             //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
  323.             //such as sending a chat message of the command's syntax
  324.             int length = thestring.Length;
  325.             //check each char in a foreach loop
  326.             foreach (char s in thestring)
  327.             {
  328.                 //check to see if the number of arguements expected has been reached yet
  329.                 if (i != number)
  330.                 {
  331.                     //check to see if the number of arguements expected wasn't reached, or if too many were recieved
  332.                     if (error > length || number > 5)
  333.                     {
  334.                         //return an error code
  335.                         returned[0] = "-1";
  336.                         return returned;
  337.                     }
  338.                     //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]
  339.                     else if (s == seperator)
  340.                     {
  341.                         returned[i] = thestring.Remove(thestring.IndexOf(s));
  342.                         thestring = thestring.Remove(0, thestring.IndexOf(s) + 1);
  343.                         i++;
  344.                     }
  345.                     //increment error after each iteration
  346.                     error++;
  347.                     //check to see if the # of arguements expected was not reached
  348.                     if (error == length && i != number)
  349.                     {
  350.                         returned[0] = "-1";
  351.                         return returned;
  352.                     }
  353.                 }
  354.  
  355.                 else
  356.                 {
  357.                     //return the last part of the string
  358.                     returned[i] = thestring;
  359.                 }
  360.             }
  361.             //return our array
  362.             return returned;
  363.         }
  364.     }
  365.  
  366.     internal class JobCallback<T>
  367.     {
  368.         private CallbackManager manager;
  369.         private Action<SteamUser.UpdateMachineAuthCallback, JobID> onMachineAuth;
  370.  
  371.         public JobCallback(Action<SteamUser.UpdateMachineAuthCallback, JobID> onMachineAuth, CallbackManager manager)
  372.         {
  373.             this.onMachineAuth = onMachineAuth;
  374.             this.manager = manager;
  375.         }
  376.     }
  377. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement