static void Main(string[] args) { var client = new DiscordClient(); //Display all log messages in the console client.LogMessage += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); //Echo back any message received, provided it didn't come from the bot itself client.MessageReceived += async (s, e) => { if (!e.Message.IsAuthor) await client.SendMessage(e.Channel, e.Message.Text); }; //Convert our sync method to an async one and block the Main function until the bot disconnects client.Run(async () => { while (true) { try { await client.Connect(EMAIL, PASSWORD); await client.SetGame(1); break; } catch (Exception ex) { client.LogMessage += (s, e) => Console.WriteLine(String.Concat("Login Failed", ex)); await Task.Delay(client.Config.FailedReconnectDelay); } } }); }
static void Main(string[] args) { var client = new DiscordClient(); //Display all log messages in the console client.LogMessage += (s, e) => Console.WriteLine("[{e.Severity}] {e.Source}: {e.Message}"); //Echo back any message received, provided it didn't come from the bot itself client.MessageReceived += async (s, e) => { if (!e.Message.IsAuthor) await client.SendMessage(e.Channel, e.Message.Text); }; //Convert our sync method to an async one and block the Main function until the bot disconnects client.Run(async () => { //Connect to the Discord server using our email and password await client.Connect(EMAIL, PASSWORD); client.SetGame(1); //If we are not a member of any server, use our invite code (made beforehand in the official Discord Client) /* if (!client.AllServers.Any()) await client.AcceptInvite(client.GetInvite(TL_SOKU_INVITE_CODE)); */ }); }
private async void Connect(DiscordClient inoriClient) { inoriClient.Run(async () => { while (true) { try { await inoriClient.Connect(EMAIL, PASSWORD); await inoriClient.SetGame(1); break; } catch (Exception ex) { inoriClient.LogMessage += (s, e) => Console.WriteLine(String.Concat("Login Failed", ex)); await Task.Delay(inoriClient.Config.FailedReconnectDelay); } } }); }
static void Main() { //load credentials from credentials.json Credentials c; try { c = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); botMention = c.BotMention; if (c.GoogleAPIKey == null || c.GoogleAPIKey == "") { Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened."); } else { GoogleAPIKey = c.GoogleAPIKey; } OwnerID = c.OwnerID; password = c.Password; } catch (Exception) { Console.WriteLine("Failed to load stuff from credentials.json, RTFM"); Console.ReadKey(); return; } //create new discord client client = new DiscordClient(); //create a command service var commandService = new CommandService(new CommandServiceConfig { CommandChar = null, HelpMode = HelpMode.Disable }); //init parse if (c.ParseKey != null && c.ParseID != null && c.ParseID != "" && c.ParseKey != "") { ParseClient.Initialize(c.ParseID, c.ParseKey); //monitor commands for logging stats_collector = new StatsCollector(commandService); } else { Console.WriteLine("Parse key and/or ID not found. Bot will not log."); } //add command service var commands = client.Services.Add<CommandService>(commandService); //create module service var modules = client.Services.Add<ModuleService>(new ModuleService()); //add audio service var audio = client.Services.Add<AudioService>(new AudioService(new AudioServiceConfig() { Channels = 2, EnableEncryption = false })); //install modules modules.Install(new Administration(), "Administration", FilterType.Unrestricted); modules.Install(new Conversations(), "Conversations", FilterType.Unrestricted); modules.Install(new Gambling(), "Gambling", FilterType.Unrestricted); modules.Install(new Games(), "Games", FilterType.Unrestricted); modules.Install(new Music(), "Music", FilterType.Unrestricted); modules.Install(new Searches(), "Searches", FilterType.Unrestricted); //run the bot client.Run(async () => { await client.Connect(c.Username, c.Password); Console.WriteLine("Connected!"); }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
static void Main(string[] args) { if (!restart) { rpg = new KokoroBotRPG(); loadFiles(); } else { restart = false; } { DiscordClientConfig config = new DiscordClientConfig(); config.VoiceMode = DiscordVoiceMode.Outgoing; config.VoiceBufferLength = 40; var client = new DiscordClient(config); //Display all log messages in the console client.LogMessage += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); client.MessageReceived += async (s, e) => { Console.WriteLine(e.Message.User.Name + ": " + e.Message.Text); if (!e.Message.IsAuthor) { var currentChannel = e.Channel; if (e.User.Id == 95543627391959040) { if (e.Message.Text == "-mute") { mute = !mute; await client.SendMessage(currentChannel, "KokoroBot is now mute: " + mute.ToString()); } else if (e.Message.Text == "-clear") { if (voiceclient != null) voiceclient.ClearVoicePCM(); } else if (e.Message.Text == "-save") { saveFiles(); await client.SendMessage(currentChannel, "I have saved everything :3"); } else if (e.Message.Text == "-dc") { quit = true; running = false; } else if (e.Message.Text == "-restart") { await client.SendMessage(currentChannel, "Cya on the other side :3"); restart = true; running = false; await client.Disconnect(); } else if (e.Message.Text.StartsWith("-join")) { var channels = e.Server.Channels.Where((Channel chan) => { return e.Message.Text.Substring(5).TrimStart(' ') == chan.Name && chan.Type == ChannelType.Voice; }); if (channels.Any()) { var channel = channels.First(); Console.WriteLine("KokoroBot tries to join Channel: " + channel.Name); voiceclient = await client.JoinVoiceServer(channel); voiceserver = e.Message.Server; } } else if (e.Message.Text == "-leave") { if (voiceclient != null) { voiceclient.ClearVoicePCM(); await client.LeaveVoiceServer(voiceserver); voiceclient = null; voiceserver = null; } } } else if (e.User.Name == "part") { await client.SendMessage(currentChannel, "I don't like you. B-b-baka. >.<"); return; } if (!mute) { if (e.Message.Text.Length > 0) { string[] splitmessage = e.Message.Text.Split(' '); if (splitmessage[0] == "-kardfacts") { if (splitmessage.Length > 2) { if (splitmessage[1] == "add") { try { string finalstr = ""; for (int i = 2; i < splitmessage.Length; i++) { if (i != 2) finalstr += ' ' + splitmessage[i]; else finalstr = splitmessage[i]; } if (finalstr.Length > 5) { kardFactsStrings.Add(finalstr); await client.SendMessage(currentChannel, "A new fact about Kard has been added. (Yay ^-^):"); currentChannel = e.Channel; await client.SendMessage(currentChannel, finalstr); } else { throw new IOException("Hue."); } } catch (Exception) { await client.SendMessage(currentChannel, "That hurt <.< Don't do this again, ok? :3"); } } } else { await client.SendMessage(currentChannel, kardFacts()); } } else if (e.Message.Text.StartsWith("-play")) { Task.Run(() => { PlaySoundWav(e); }); } else if(e.Message.Text.StartsWith("-getclientid")) { if (e.Message.Text.Length > "-getclientid ".Length) { try { await client.SendMessage(currentChannel, e.Server.Members.Where((User u) => { return u.Name.StartsWith(e.Message.Text.Substring("-getclientid ".Length)); }).First().Id.ToString()); } catch(Exception) { await client.SendMessage(currentChannel, "User does not exist. B-baka."); } } else { await client.SendMessage(currentChannel, e.Message.User.Id.ToString()); } } else if(e.Message.Text.StartsWith(":")) { await rpg.HandleCommands(e, client, currentChannel); } else if (await handleSimpleCommands(e, client, currentChannel) == false) { await handleTiroCommands(e, client, currentChannel); } } } } }; //Convert our sync method to an async one and block the Main function until the bot disconnects client.Run(async () => { //Connect to the Discord server using our email and password await client.Connect(Sensitive.email, Sensitive.passwd); while (running) { var inputTask = Task.Run<string>((Func<string>)Console.ReadLine); await inputTask; string dbgCommand = inputTask.Result; if( dbgCommand == "exit" || restart || quit) { running = false; await client.Disconnect(); } else if ( dbgCommand == "listservers") { foreach(Server s in client.AllServers) { Console.WriteLine("#######################################"); Console.WriteLine("Servername: " + s.Name); Console.WriteLine("Voicechannels: "); foreach(Channel c in s.VoiceChannels) { Console.WriteLine(" "+c.Name); } Console.WriteLine("Channels: "); foreach (Channel c in s.Channels) { Console.WriteLine(" "+c.Name); } } } } //If we are not a member of any server, use our invite code (made beforehand in the official Discord Client) }); } if (!restart) { saveFiles(); } else { Main(new string[] { }); } }
private void Start(string[] args) { GlobalSettings.Load(); //Set up the base client itself with no voice and small message queues _client = new DiscordClient(new DiscordConfig { AppName = "VoltBot", AppUrl = "https://github.com/RogueException/DiscordBot", AppVersion = DiscordConfig.LibVersion, LogLevel = LogSeverity.Info, MessageCacheSize = 0, UsePermissionsCache = false }) //** Core Services **// //These are services adding functionality from other Discord.Net.XXX packages //Enable commands on this bot and activate the built-in help command .UsingCommands(new CommandServiceConfig { CommandChar = '~', HelpMode = HelpMode.Public }) //Enable command modules .UsingModules() //Enable audio support .UsingAudio(new AudioServiceConfig { Mode = AudioMode.Outgoing, EnableMultiserver = false, EnableEncryption = true, Bitrate = 512, BufferLength = 10000 }) //** Command Permission Services **// // These allow you to use permission checks on commands or command groups, or apply a permission globally (such as a blacklist) //Add a blacklist service so we can add people that can't run any commands. We have used a whitelist instead to restrict it to just us. .UsingGlobalBlacklist() //.EnableGlobalWhitelist(GlobalSettings.Users.DevId)) //Assign users to our own role system based on their permissions in the server/channel a command is run in. .UsingPermissionLevels((u, c) => { if (u.Id == GlobalSettings.Users.DevId) return (int)PermissionLevel.BotOwner; if (u.Server != null) { if (u == c.Server.Owner) return (int)PermissionLevel.ServerOwner; var serverPerms = u.ServerPermissions; if (serverPerms.ManageRoles) return (int)PermissionLevel.ServerAdmin; if (serverPerms.ManageMessages && serverPerms.KickMembers && serverPerms.BanMembers) return (int)PermissionLevel.ServerModerator; var channelPerms = u.GetPermissions(c); if (channelPerms.ManagePermissions) return (int)PermissionLevel.ChannelAdmin; if (channelPerms.ManageMessages) return (int)PermissionLevel.ChannelModerator; } return (int)PermissionLevel.User; }) //** Helper Services**// //These are used by the modules below, and will likely be removed in the future .AddService<SettingsService>() .AddService<HttpService>() //** Command Modules **// //Modules allow for events such as commands run or user joins to be filtered to certain servers/channels, as well as provide a grouping mechanism for commands .AddModule<AdminModule>("Admin", ModuleFilter.ServerWhitelist) .AddModule<ColorsModule>("Colors", ModuleFilter.ServerWhitelist) .AddModule<FeedModule>("Feeds", ModuleFilter.ServerWhitelist) .AddModule<GithubModule>("Repos", ModuleFilter.ServerWhitelist) .AddModule<ModulesModule>("Modules", ModuleFilter.None) .AddModule<PublicModule>("Public", ModuleFilter.None) .AddModule<TwitchModule>("Twitch", ModuleFilter.ServerWhitelist); //.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist); //** Events **// _client.Log.Message += (s, e) => WriteLog(e); //Display errors that occur when a user tries to run a command //(In this case, we hide argcount, parsing and unknown command errors to reduce spam in servers with multiple bots) _client.Commands().CommandErrored += (s, e) => { string msg = e.Exception?.GetBaseException().Message; if (msg == null) //No exception - show a generic message { switch (e.ErrorType) { case CommandErrorType.Exception: //msg = "Unknown error."; break; case CommandErrorType.BadPermissions: msg = "You do not have permission to run this command."; break; case CommandErrorType.BadArgCount: //msg = "You provided the incorrect number of arguments for this command."; break; case CommandErrorType.InvalidInput: //msg = "Unable to parse your command, please check your input."; break; case CommandErrorType.UnknownCommand: //msg = "Unknown command."; break; } } if (msg != null) { _client.ReplyError(e, msg); _client.Log.Error("Command", msg); } }; //Log to the console whenever someone uses a command _client.Commands().CommandExecuted += (s, e) => _client.Log.Info("Command", $"{e.Command.Text} ({e.User.Name})"); //Used to load private modules outside of this repo #if PRIVATE PrivateModules.Install(_client); #endif //** Run **// #if !DNXCORE50 Console.Title = $"{_client.Config.AppName} v{_client.Config.AppVersion} (Discord.Net v{DiscordConfig.LibVersion})"; #endif //Convert this method to an async function and connect to the server //DiscordClient will automatically reconnect once we've established a connection, until then we loop on our end //Note: Run is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function. _client.Run(async () => { while (true) { try { await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password); _client.SetGame("Discord.Net"); break; } catch (Exception ex) { _client.Log.Error($"Login Failed", ex); await Task.Delay(_client.Config.FailedReconnectDelay); } } }); }
private static void Start() { SettingsManager.Load(); _client = new DiscordClient(); _client.LogMessage += (s, e) => { Console.WriteLine($"[{e.Severity}] {e.Source} => {e.Message}"); }; //Set up permissions _client.AddService(new BlacklistService()); _client.AddService(new WhitelistService()); _client.AddService(new PermissionLevelService((u, c) => { if (u.Id == long.Parse(SettingsManager.OwnerID)) return (int)PermissionLevel.BotOwner; if (!u.IsPrivate) { if (u == c.Server.Owner) return (int)PermissionLevel.ServerOwner; var serverPerms = u.GetServerPermissions(); if (serverPerms.ManageRoles) return (int)PermissionLevel.ServerAdmin; if (serverPerms.ManageMessages && serverPerms.KickMembers && serverPerms.BanMembers) return (int)PermissionLevel.ServerMod; var channelPerms = u.GetPermissions(c); if (channelPerms.ManagePermissions) return (int)PermissionLevel.ChannelAdmin; if (channelPerms.ManageMessages) return (int)PermissionLevel.ChannelMod; } return (int)PermissionLevel.User; })); //Set up commands var commands = _client.AddService(new CommandService(new CommandServiceConfig { CommandChar = '!', HelpMode = HelpMode.Private })); commands.RanCommand += (s, e) => Console.WriteLine($"[Command] {(e.Server == null ? "[Private]" : e.Server.ToString()) + "/" + e.Channel} => {e.Message}"); commands.CommandError += (s, e) => { string msg = e.Exception?.GetBaseException().Message; if (msg == null) { { switch (e.ErrorType) { case CommandErrorType.Exception: msg = "Unknown error."; break; case CommandErrorType.BadPermissions: msg = "You do not have permission to run this command."; break; case CommandErrorType.BadArgCount: msg = "You provided the incorrect number of arguments for this command."; break; case CommandErrorType.InvalidInput: msg = "Unable to parse your command, please check your input."; break; case CommandErrorType.UnknownCommand: msg = "Unknown command."; break; } } } if (msg != null) { _client.SendMessage(e.Channel, $"Failed to complete command: {msg}"); Console.WriteLine($"[Error] Failed to complete command: {e.Command?.Text} for {e.User?.Name}"); Console.WriteLine($"Command failure: {msg}"); } }; //Set up modules var modules = _client.AddService(new ModuleService()); //Boot up _client.Run(async () => { while (true) { try { await _client.Connect(SettingsManager.Email, SettingsManager.Password); if (!_client.AllServers.Any()) await _client.AcceptInvite(_client.GetInvite("0nwaapOqh2LPqDL9").Result); modules.Install(new Modules.SimpleCommands(), "Simple Commands", FilterType.Unrestricted); modules.Install(new Modules.Chance(), "Dice Rolling", FilterType.Unrestricted); break; } catch (Exception ex) { Console.WriteLine("Login failed" + ex.ToString()); } } }); }
public void Run() { ReadConfig(); VerifyReady(); Thread t = new Thread(() => { f = new EasyMusicBot.Form1(this); Application.EnableVisualStyles(); Application.Run(f); }); t.SetApartmentState(ApartmentState.STA); t.Start(); Client = new DiscordClient(new DiscordConfig { AppName = "Easy Music Bot", AppUrl = "Put url here", //AppVersion = DiscordConfig.LibVersion, LogLevel = LogSeverity.Info, MessageCacheSize = 0, UsePermissionsCache = false }); VidLoopAsync(); Client.Connected += (s, e) => { Console.WriteLine("Connected to Discord with email " + email); //Client.SetGame(null); foreach (Discord.Channel c in Client.GetServer(104979971667197952).TextChannels) { if (c.Name.Equals(Channel)) { //MessageBox.Show("che set to " + c.Name); DChannel = c; } } }; Client.MessageReceived += (s, e) => { LRC = e.Message.Channel; Console.WriteLine("Message recieved!"); InterpretCommand(e.Message); }; try { Client.Run(async () => { await Client.Connect(email, password); }); } catch (Exception e) { Console.WriteLine("Oh noes! There seems to be a problem with conencting to Discord!"); Console.WriteLine("Make sure you typed the email and password fields correctly in the config.txt"); Console.WriteLine("If you happen across the developer, make sure to tell him this: " + e.Message); } MessageBox.Show("t"); }
static void Main(string[] args) { // Load up the DB, or create it if it doesn't exist SQL.LoadDB(); // Load up the config file LoadConfig(); Console.Title = $"Nekobot v{version}"; // Load the stream channels Music.LoadStreams(); // Initialize rest client RCInit(); client = new DiscordClient(new DiscordClientConfig { AckMessages = true, LogLevel = LogMessageSeverity.Verbose, TrackActivity = true, UseMessageQueue = false, UseLargeThreshold = true, EnableVoiceMultiserver = true, VoiceMode = DiscordVoiceMode.Outgoing, }); // Set up the events and enforce use of the command prefix commands.CommandError += CommandError; client.Connected += Connected; client.Disconnected += Disconnected; client.UserJoined += UserJoined; client.LogMessage += LogMessage; client.AddService(commands); client.AddService(new PermissionLevelService(GetPermissions)); commands.CreateGroup("", group => GenerateCommands(group)); commands.NonCommands += Chatbot.Do; // Load the chatbots Chatbot.Load(); // Keep the window open in case of crashes elsewhere... (hopefully) Thread input = new Thread(InputThread); input.Start(); // Connection, join server if there is one in config, and start music streams try { client.Run(async() => { await client.Connect(config["email"].ToString(), config["password"].ToString()); if (config["server"].ToString() != "") { await client.AcceptInvite(client.GetInvite(config["server"].ToString()).Result); } await Music.StartStreams(); }); } catch (Exception e) { Console.WriteLine($"Error: {e.GetBaseException().Message}"); } }