private static void InputCheck() { string input; do { input = Console.ReadLine(); if (input.Contains("?changepass")) { Console.Write("Please enter the new password (will be visible): "); string newPass = Console.ReadLine(); DiscordUserInformation i = client.ClientPrivateInformation.Copy(); i.password = newPass; client.ChangeBotInformation(i); Console.WriteLine("Password changed!"); } else if (input.Contains("?logout")) { client.Logout(); } } while (!String.IsNullOrWhiteSpace(input)); }
public static void Main(string[] args) { Console.WriteLine("DiscordSharp Tester"); client.ClientPrivateInformation = new DiscordUserInformation(); Console.Write("Please enter your email: "); string email = Console.ReadLine(); client.ClientPrivateInformation.email = email; Console.Write("Now, your password (visible): "); string pass = Console.ReadLine(); client.ClientPrivateInformation.password = pass; Console.WriteLine("Attempting login.."); var worker = new Thread(() => { client.DebugMessageReceived += (sender, e) => { client.SendMessageToUser("[DEBUG MESSAGE]: " + e.message, client.GetServersList().Find(x => x.members.Find(y => y.user.username == "Axiom") != null).members.Find(x => x.user.username == "Axiom")); }; client.UnknownMessageTypeReceived += (sender, e) => { using (var sw = new StreamWriter(e.RawJson["t"].ToString() + ".txt")) { sw.WriteLine(e.RawJson); } client.SendMessageToUser("Heya, a new message type, '" + e.RawJson["t"].ToString() + "', has popped up!", client.GetServersList().Find(x => x.members.Find(y => y.user.username == "Axiom") != null).members.Find(x => x.user.username == "Axiom")); }; client.VoiceStateUpdate += (sender, e) => { Console.WriteLine("***Voice State Update*** User: "******"Server Created: " + e.server.name); }; client.MessageEdited += (sender, e) => { if (e.author.user.username == "Axiom") { client.SendMessageToChannel("What the f**k, <@" + e.author.user.id + "> you can't event type your message right. (\"" + e.MessageEdited.content + "\")", e.Channel); } }; client.ChannelCreated += (sender, e) => { var parentServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.ChannelCreated.id) != null); if (parentServer != null) { Console.WriteLine("Channel {0} created in {1}!", e.ChannelCreated.name, parentServer.name); } }; client.PrivateChannelCreated += (sender, e) => { Console.WriteLine("Private channel started with {0}", e.ChannelCreated.recipient.username); }; client.PrivateMessageReceived += (sender, e) => { client.SendMessageToUser("Pong!", e.author); }; client.MentionReceived += (sender, e) => { if (e.author.user.id != client.Me.user.id) { client.SendMessageToChannel("Heya, @" + e.author.user.username, e.Channel); } }; client.MessageReceived += (sender, e) => { DiscordServer fromServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null); Console.WriteLine("[- Message from {0} in {1} on {2}: {3}", e.author.user.username, e.Channel.name, fromServer.name, e.message.content); if (e.message.content.StartsWith("?status")) { client.SendMessageToChannel("I work ;)", e.Channel); } else if (e.message.content.StartsWith("?notify")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); } else if (e.message.content.StartsWith("?whereami")) { DiscordServer server = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null); string owner = ""; foreach (var member in server.members) { if (member.user.id == server.owner_id) { owner = member.user.username; } } string whereami = String.Format("I am currently in *#{0}* ({1}) on server *{2}* ({3}) owned by {4}. The channel's topic is: {5}", e.Channel.name, e.Channel.id, server.name, server.id, owner, e.Channel.topic); client.SendMessageToChannel(whereami, e.Channel); } else if (e.message.content.StartsWith("?test_game")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (split.Length > 0) { client.UpdateCurrentGame(int.Parse(split[1])); } } else if (e.message.content.StartsWith("?gtfo")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (split.Length > 1) { DiscordServer curServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == split[1]) != null); if (curServer != null) { client.SendMessageToChannel("Leaving server " + curServer.name, e.Channel); client.LeaveServer(curServer.id); } } else { DiscordServer curServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null); client.SendMessageToChannel("Bye!", e.Channel); client.LeaveServer(curServer.id); } } else if (e.message.content.StartsWith("?everyone")) { DiscordServer server = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null); string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (split.Length > 1) { string message = ""; foreach (var user in server.members) { if (user.user.id == client.Me.user.id) { continue; } if (user.user.username == "Blank") { continue; } message += "@" + user.user.username + " "; } message += ": " + split[1]; client.SendMessageToChannel(message, e.Channel); } } else if (e.message.content.StartsWith("?lastfm")) { #if __MONOCS__ client.SendMessageToChannel("Sorry, not on Mono :(", e.Channel); #else string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (split.Length > 1) { using (var lllfclient = new LastfmClient("4de0532fe30150ee7a553e160fbbe0e0", "0686c5e41f20d2dc80b64958f2df0f0c", null, null)) { try { var recentScrobbles = lllfclient.User.GetRecentScrobbles(split[1], null, 1, 1); LastTrack lastTrack = recentScrobbles.Result.Content[0]; client.SendMessageToChannel(string.Format("*{0}* last listened to _{1}_ by _{2}_", split[1], lastTrack.Name, lastTrack.ArtistName), e.Channel); } catch { client.SendMessageToChannel(string.Format("User _*{0}*_ not found!", split[1]), e.Channel); } } } else { client.SendMessageToChannel("Who??", e.Channel); } #endif } else if (e.message.content.StartsWith("?rename")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (split.Length > 0) { //client.ChangeBotUsername(split[1]); DiscordUserInformation newUserInfo = client.ClientPrivateInformation; newUserInfo.username = split[1].ToString(); client.ChangeBotInformation(newUserInfo); } } else if (e.message.content.StartsWith("?changepic")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (split.Length > 0) { Regex linkParser = new Regex(@"\b(?:https?://|www\.)\S+\b", RegexOptions.Compiled | RegexOptions.IgnoreCase); string rawString = $"{split[1]}"; if (linkParser.Matches(rawString).Count > 0) { string url = linkParser.Matches(rawString)[0].ToString(); using (WebClient wc = new WebClient()) { byte[] data = wc.DownloadData(url); using (MemoryStream mem = new MemoryStream(data)) { using (var image = System.Drawing.Image.FromStream(mem)) { client.ChangeBotPicture(new Bitmap(image)); } } } } } } else if (e.message.content.StartsWith("?whois")) { //?whois <@01393408> Regex r = new Regex("\\d+"); Match m = r.Match(e.message.content); Console.WriteLine("WHOIS INVOKED ON: " + m.Value); var foundServer = client.GetServersList().Find(x => x.channels.Find(y => y.id == e.Channel.id) != null); if (foundServer != null) { var foundMember = foundServer.members.Find(x => x.user.id == m.Value); client.SendMessageToChannel(string.Format("<@{0}>: {1}, {2}", foundMember.user.id, foundMember.user.id, foundMember.user.username), e.Channel); } } else if (e.message.content.StartsWith("?prune")) { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (split.Length > 0) { if (split[1].Trim() == "all") { int messagesDeleted = client.DeleteAllMessages(); if (split.Length > 1 && split[2] != "nonotice") { client.SendMessageToChannel(messagesDeleted + " messages deleted across all channels.", e.Channel); } } else if (split[1].Trim() == "here") { int messagesDeleted = client.DeleteAllMessagesInChannel(e.Channel); if (split.Length > 1 && split[2] != "nonotice") { client.SendMessageToChannel(messagesDeleted + " messages deleted in channel '" + e.Channel.name + "'.", e.Channel); } } else { DiscordChannel channelToPrune = client.GetChannelByName(split[1].Trim()); if (channelToPrune != null) { int messagesDeleted = client.DeleteAllMessagesInChannel(channelToPrune); if (split.Length > 1 && split[2] != "nonotice") { client.SendMessageToChannel(messagesDeleted + " messages deleted in channel '" + channelToPrune.name + "'.", e.Channel); } } } } else { client.SendMessageToChannel("Prune what?", e.Channel); } } else if (e.message.content.StartsWith("?quoththeraven")) { client.SendMessageToChannel("nevermore", e.Channel); } else if (e.message.content.StartsWith("?quote")) { client.SendMessageToChannel("Luigibot does what Reta don't.", e.Channel); } else if (e.message.content.StartsWith("?selfdestruct")) { if (e.author.user.username == "Axiom") { client.SendMessageToChannel("restaroni in pepparoni", e.Channel); } Environment.Exit(0); } else if (e.message.content.StartsWith("?changetopic")) { if (e.author.user.username == "Axiom") { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (split.Length > 0) { client.ChangeChannelTopic(split[1], e.Channel); } } } else if (e.message.content.StartsWith("?join")) { if (e.author.user.username == "Axiom") { string[] split = e.message.content.Split(new char[] { ' ' }, 2); if (split.Length > 0) { string substring = split[1].Substring(split[1].LastIndexOf('/') + 1); //client.SendMessageToChannel(substring, e.Channel); client.AcceptInvite(substring); } } } }; client.Connected += (sender, e) => { Console.WriteLine("Connected! User: "******"Closed ({0}): {1}", e.Code, e.Reason); }; //ConnectStuff(); //while (true) ; if (client.SendLoginRequest() != null) { Console.WriteLine("Logged in!"); client.ConnectAndReadMessages(); Console.WriteLine($"Connected to {client.CurrentGatewayURL}"); client.UpdateCurrentGame(256); } }); worker.Start(); InputCheck(); //System.Windows.Forms.Application.Run(); /** * Since this is a test app and people actually do read my code... * I'd like to say one thing: * If you're not going to be doing any input accepting **INSIDE OF THE CONSOLE** you don't have to setup * a seperate thread for the client and accept input on main. This is why I've only commented out * the System.Windows.Forms.Application.Run(); part instead of removing it. * * If you're not accepting input, you can just run client on the main thread and run that * System.Windows.Forms.Application.Run(); snippet and this will keep the app alive, with no CPU * hit! */ client.Dispose(); Console.ReadLine(); }
static void Main(string[] args) { //Checks to see if Bot_Settings.ini exists and if it doesnt it writes to console and ends the program. MakeIni.Create(); // First of all, a DiscordClient will be created, and the email and password will be defined. Console.WriteLine("Defining variables"); // Fill in token and change isbot to true if you use the API // Else, leave token alone and change isbot to false // But believe me, the API bots are nicer because of a sexy bot tag! //BotSettings.botToken gets the token from Bot_Settings.ini DiscordClient client = new DiscordClient(BotSettings.botToken, isbot); client.ClientPrivateInformation.Email = "email"; client.ClientPrivateInformation.Password = "******"; // Then, we are going to set up our events before connecting to discord, to make sure nothing goes wrong. Console.WriteLine("Defining Events"); // find that one you interested in client.Connected += (sender, e) => // Client is connected to Discord { Console.WriteLine("Connected! User: "******"https://github.com/NaamloosDT/DiscordSharp_Starter"); // This will display at "Playing: " //Whoops! i messed up here. (original: Bot online!\nPress any key to close this window.) //if the bots username is not the same as the name set in the Bot_Settings.ini // this sets the bot name to be the updated name in the Bot_Settings.ini if (client.Me.Username != BotSettings.botName) { DiscordUserInformation info = new DiscordUserInformation(); info.Username = BotSettings.botName; client.ChangeClientInformation(info); } //checks to see if a avatar image exists and updates it. if (File.Exists("avatar.jpg")) { client.ChangeClientAvatarFromFile("avatar.jpg"); } }; client.PrivateMessageReceived += (sender, e) => // Private message has been received { if (e.Message == pf + "help") { e.Author.SendMessage("This is a private message!"); // Because this is a private message, the bot should send a private message back // A private message does NOT have a channel } if (e.Message == pf + "update avatar") { // Because this is a private message, the bot should send a private message back // A private message does NOT have a channel } if (e.Message.StartsWith(pf + "join")) { if (!isbot) { string inviteID = e.Message.Substring(e.Message.LastIndexOf('/') + 1); // Thanks to LuigiFan (Developer of DiscordSharp) for this line of code! client.AcceptInvite(inviteID); e.Author.SendMessage("Joined your discord server!"); Console.WriteLine("Got join request from " + inviteID); } else { e.Author.SendMessage("Please use this url instead!" + "https://discordapp.com/oauth2/authorize?client_id=[CLIENT_ID]&scope=bot&permissions=0"); } } }; client.MessageReceived += (sender, e) => // Channel message has been received { if (e.MessageText == pf + "admin") { bool isadmin = false; List <DiscordRole> roles = e.Author.Roles; foreach (DiscordRole role in roles) { if (role.Name.Contains("Administrator") || e.Author.HasPermission(DiscordSpecialPermissions.Administrator)) { isadmin = true; break; } } if (isadmin) { e.Channel.SendMessage("Yes, you are! :D"); } else { e.Channel.SendMessage("No, you aren't :c"); } } if (e.MessageText == pf + "help") { e.Channel.SendMessage("This is a public message!"); // Because this is a public message, // the bot should send a message to the channel the message was received. } if (e.MessageText == pf + "cat") { e.Channel.SendMessage("Meow :cat: " + randomcat()); } }; // Below: some things that might be nice? // This sends a message to every new channel on the server client.ChannelCreated += (sender, e) => { if (e.ChannelCreated.Type == ChannelType.Text) { e.ChannelCreated.SendMessage("Nice! a new channel has been created!"); } }; // When a user joins the server, send a message to them. client.UserAddedToServer += (sender, e) => { e.AddedMember.SendMessage("Welcome " + e.Guild.Name + ", please read the rules.\nEnjoy you're time here!"); }; // Don't want messages to be removed? this piece of code will // Keep messages for you. Remove if unused :) /*client.MessageDeleted += (sender, e) => * { * e.Channel.SendMessage("Removing messages has been disabled on this server!"); * e.Channel.SendMessage("<@" + e.DeletedMessage.Author.ID + "> sent: " +e.DeletedMessage.Content.ToString()); * };*/ // Now, try to connect to Discord. try{ // Make sure that IF something goes wrong, the user will be notified. // The SendLoginRequest should be called after the events are defined, to prevent issues. Console.WriteLine("Sending login request"); client.SendLoginRequest(); Console.WriteLine("Connecting client in separate thread"); // Cannot convert from 'method group' to 'ThreadStart', so i removed threading // Pass argument 'true' to use .Net sockets. client.Connect(); // Login request, and then connect using the discordclient i just made. Console.WriteLine("Client connected!"); }catch (Exception e) { Console.WriteLine("Something went wrong!\n" + e.Message + "\nPress any key to close this window."); } // Done! your very own Discord bot is online! // Now to make sure the console doesnt close: Console.ReadKey(); // If the user presses a key, the bot will shut down. Environment.Exit(0); // Make sure all threads are closed. }
/* public List<DiscordRole> GetRoles(DiscordServer server) { return null; } */ /// <summary> /// Used for changing the client's email, password, username, etc. /// </summary> /// <param name="info"></param> public void ChangeClientInformation(DiscordUserInformation info) { string usernameRequestJson; if (info.Password != ClientPrivateInformation.Password) { usernameRequestJson = JsonConvert.SerializeObject(new { email = info.Email, new_password = info.Password, password = ClientPrivateInformation.Password, username = info.Username, avatar = info.Avatar }); ClientPrivateInformation.Password = info.Password; try { File.Delete("token_cache"); DebugLogger.Log("Deleted token_cache due to change of password."); } catch (Exception) { /*ignore*/ } } else { usernameRequestJson = JsonConvert.SerializeObject(new { email = info.Email, password = info.Password, username = info.Username, avatar = info.Avatar }); } string url = Endpoints.BaseAPI + Endpoints.Users + "/@me"; try { var result = JObject.Parse(WebWrapper.Patch(url, token, usernameRequestJson)); foreach (var server in ServersList) { if (server.Members[Me.ID] != null) server.Members[Me.ID].Username = info.Username; } Me.Username = info.Username; Me.Email = info.Email; Me.Avatar = info.Avatar; } catch (Exception ex) { DebugLogger.Log($"Error ocurred while changing client's information: {ex.Message}", MessageLevel.Error); } }
/// <summary> /// /// </summary> /// <param name="tokenOverride">If you have a token you wish to use, provide it here. Else, a login attempt will be made.</param> /// <param name="isBotAccount">Set this to true if your bot is going to be a bot account</param> public DiscordClient(string tokenOverride = null, bool isBotAccount = false, bool enableLogging = true) { if (isBotAccount && tokenOverride == null) throw new Exception("Token override cannot be null if using a bot account!"); DebugLogger.EnableLogging = enableLogging; token = tokenOverride; IsBotAccount = isBotAccount; if (IsBotAccount) UserAgentString = "DiscordBot " + UserAgentString; else UserAgentString = "Custom Discord Client " + UserAgentString; if (ClientPrivateInformation == null) ClientPrivateInformation = new DiscordUserInformation(); DebugLogger.LogMessageReceived += (sender, e) => { if (e.message.Level == MessageLevel.Error) DisconnectFromVoice(); if (TextClientDebugMessageReceived != null) TextClientDebugMessageReceived(this, e); }; }
static void Main(string[] args) { MakeIni.Create(); Console.WriteLine("Defining variables"); DiscordClient client = new DiscordClient(BotSettings.botToken, isbot); client.ClientPrivateInformation.Email = "email"; client.ClientPrivateInformation.Password = "******"; Console.WriteLine("Defining Events"); client.Connected += (sender, e) => { Console.WriteLine("Connected! User: "******"https://github.com/Follew/Oscuro-Bot/"); if (client.Me.Username != BotSettings.botName) { DiscordUserInformation info = new DiscordUserInformation(); info.Username = BotSettings.botName; client.ChangeClientInformation(info); } if (File.Exists("avatar.jpg")) { client.ChangeClientAvatarFromFile("avatar.jpg"); } }; client.PrivateMessageReceived += (sender, e) => { if (e.Message == pf + "help") { e.Author.SendMessage("This is a private message!"); } if (e.Message == pf + "update avatar") { } if (e.Message.StartsWith(pf + "join")) { if (!isbot) { string inviteID = e.Message.Substring(e.Message.LastIndexOf('/') + 1); client.AcceptInvite(inviteID); e.Author.SendMessage("Joined your discord server!"); Console.WriteLine("Got join request from " + inviteID); } else { e.Author.SendMessage("Please use this url instead!" + "https://discordapp.com/oauth2/authorize?client_id=[CLIENT_ID]&scope=bot&permissions=0"); } } }; client.MessageReceived += (sender, e) => { if (e.MessageText == pf + "admin") { bool isadmin = false; List <DiscordRole> roles = e.Author.Roles; foreach (DiscordRole role in roles) { if (role.Name.Contains("Administrator") || e.Author.HasPermission(DiscordSpecialPermissions.Administrator)) { isadmin = true; break; } } if (isadmin) { e.Channel.SendMessage("Yes, you are! :D"); } else { e.Channel.SendMessage("No, you aren't :c"); } } if (e.MessageText == pf + "help") { e.Channel.SendMessage("This is a public message!"); } if (e.MessageText == pf + "cat") { //e.Channel.SendMessage("Meow :cat: " + randomcat()); } }; client.ChannelCreated += (sender, e) => { if (e.ChannelCreated.Type == ChannelType.Text) { e.ChannelCreated.SendMessage("Nice! a new channel has been created!"); } }; client.UserAddedToServer += (sender, e) => { e.AddedMember.SendMessage("Welcome " + e.Guild.Name + ", please read the rules.\nEnjoy you're time here!"); }; /*client.MessageDeleted += (sender, e) => * { * e.Channel.SendMessage("Removing messages has been disabled on this server!"); * e.Channel.SendMessage("<@" + e.DeletedMessage.Author.ID + "> sent: " +e.DeletedMessage.Content.ToString()); * };*/ try { Console.WriteLine("Sending login request"); client.SendLoginRequest(); Console.WriteLine("Connecting client in separate thread"); client.Connect(); Console.WriteLine("Client connected!"); } catch (Exception e) { Console.WriteLine("Something went wrong!\n" + e.Message + "\nPress any key to close this window."); } Console.ReadKey(); // If the user presses a key, the bot will shut down. Environment.Exit(0); // Make sure all threads are closed. }
public DiscordClient() { if (ClientPrivateInformation == null) ClientPrivateInformation = new DiscordUserInformation(); DebugLogger.LogMessageReceived += (sender, e) => { if (e.message.Level == MessageLevel.Error) DisconnectFromVoice(); if (TextClientDebugMessageReceived != null) TextClientDebugMessageReceived(this, e); }; }