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)); */ }); }
static void Main(string[] args) { var inoriBot = new DiscordClient(); //Display all log messages in the console inoriBot.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 //Convert our sync method to an async one and block the Main function until the bot disconnects inoriBot.Run(async () => { while (true) { try { await inoriBot.Connect(EMAIL, PASSWORD); await inoriBot.SetGame(1); break; } catch (Exception ex) { inoriBot.LogMessage += (s, e) => Console.WriteLine(String.Concat("Login Failed", ex)); await Task.Delay(inoriBot.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 () => { while (true) { try { await client.Connect(EMAIL, PASSWORD); client.SetGame("Discord.Net); break; } catch (Exception ex) { client.LogMessage += (s, e) => Console.WriteLine(String.Concat("Login Failed", ex.Message)); await Task.Delay(client.Config.FailedReconnectDelay); } } }); }
//connects the bot and then logs the chat public BauwsBot() { bot = new DiscordClient(); bot.MessageReceived += Bot_MessageReceived; bot.Connect("*****@*****.**", "loveall4god123"); bot.Wait(); }
public static void InitBot() { bot = new DiscordClient(); bot.MessageReceived += Bot_MessagedReceived; bot.ExecuteAndWait(async () => { await bot.Connect(discordBotToken); }); }
// This code is executed when the bot is created. public DiscoBot() { // Bot connects using Bot Token. bot = new DiscordClient(); // In place of the ("") put your Bot Token. bot.Connect(""); bot.MessageReceived += bot_MessageReceived; bot.Wait(); }
public override bool onLoggedOn() { client = new DiscordClient(); client.Connect(Options.DiscordOptions.Token); client.Ready += Client_Ready; client.MessageReceived += Client_MessageReceived; client.UserJoined += Client_UserJoined; client.UserLeft += Client_UserLeft; client.ChannelUpdated += Client_ChannelUpdated; client.UserUpdated += Client_UserUpdated; client.UserBanned += Client_UserBanned; return true; }
public BotConnect() { _config = new Settings(); _client = new DiscordClient(x => { x.AppName = "Ethereal"; x.LogLevel = LogSeverity.Info; }) .UsingCommands(x => { x.PrefixChar = _config.Prefix; x.HelpMode = HelpMode.Public; }) .UsingPermissionLevels((u, c) => (int)GetPermission(u, c)) .UsingModules(); _client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] [{e.Source}] [Bot] {e.Message}"); _client.AddModule <Modules.Commands>("Commands", ModuleFilter.None); _client.UserJoined += _client_UserJoined; _client.UserUpdated += _client_UserUpdated; _client.RoleUpdated += _client_RoleUpdated; //_client.MessageReceived += _client_MsgReceived; _client.ExecuteAndWait(async() => { while (true) { try { await _client.Connect(_config.BotToken, TokenType.Bot); _client.SetGame(_config.CurrentGame, GameType.Twitch, _config.DiscordUrl); UserConnect userConnect = new UserConnect(); return; } catch (Exception ex) { _client.Log.Error("Failed to log in", ex); await Task.Delay(_client.Config.FailedReconnectDelay); } } }); }
public void Init(YAMLConfiguration conf) { try { Config = conf; string token = Config.ReadString("discord.token", null); if (token == null) { Logger.Output(LogType.INFO, "Discord bot not configured!"); return; } Client = new DiscordClient(); Client.MessageReceived += messageReceived; Client.ExecuteAndWait(async () => await Client.Connect(token, TokenType.Bot)); } catch (Exception ex) { Logger.Output(LogType.ERROR, ex.ToString()); } }
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); } } }); }
public override async void ShowDialog() { LoginDialog dialog = new LoginDialog(); if (dialog.ShowDialog() == true) { _client = new DiscordClient(); _client.UsingAudio(x => { x.Mode = AudioMode.Outgoing; x.Bitrate = null; x.Channels = 2; }); await _client.Connect(dialog.Username, dialog.Password); var voiceChannel = CurrentServer.VoiceChannels.FirstOrDefault(d => d.Name == "Bot Test"); _voiceClient = await _client.GetService<AudioService>() .Join(voiceChannel); } }
static void Main(string[] args) { LoadData(); _bot = new DiscordClient(); Console.Write("Email: "); email = Console.ReadLine(); Console.Write("Password: "******"\nConnecting to Discord..."); try { _bot.Connect(email, ConvertToUnsecureString(password)); Console.WriteLine("Connected!"); } catch { Console.WriteLine("Connection failed, please try again."); System.Environment.Exit(-1); } Running(); }
public void Connect() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; CommandListInit(); try { if (!Properties.Settings.Default.DateTimeFormatCorrected) { //xmlprovider.DateTimeCorrection(); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); } _streamProviderManager = new StreamProviderManager(); _streamProviderManager.StreamStarted += OnStreamStarted; _streamProviderManager.StreamStopped += OnStreamStopped; _streamProviderManager.StreamGlobalNotification += OnStreamGlobalNotification; _streamProviderManager.AddStreamProvider(new TwitchProvider()); _streamProviderManager.AddStreamProvider(new HitboxProvider()); bot = new DiscordClient(); bot.MessageReceived += Message_Received; bot.UserJoined += User_Joined; deathmicirc = new RelayBot(bot,false); Thread RelayThread = new Thread(deathmicirc.runBot); RelayThread.Start(); while (!RelayThread.IsAlive) ; Thread.Sleep(1); readUsers(); bot.ExecuteAndWait(async () => { await bot.Connect("MjYwMTE2OTExOTczNDY2MTEy.CzhvyA.kpEIti2hVnjNIUccob0ERB4QFTw", TokenType.Bot); }); }
private void Connect() { _client = new DiscordClient(); //Convert our sync method to an async one and block the Main function until the bot disconnects _client.Ready += _client_Ready; try { _client.Connect(BasicTeraData.Instance.WindowData.DiscordLogin, BasicTeraData.Instance.WindowData.DiscordPassword); } catch (Exception e) { //Failing here is not a reason to make the meter crash BasicTeraData.LogError(e.Message + "\n" + e.StackTrace + "\n" + e.InnerException + "\n" + e, false, false); return; } while (!_ready) { Thread.Sleep(1000); } }
public Bot() { try { r = new Random(); discordBot = new DiscordClient(x => { x.AppName = "IluvatarSuperBot"; x.LogLevel = LogSeverity.Info; x.LogHandler = Log; }); discordBot.UsingCommands(x => { x.PrefixChar = '~'; x.AllowMentionPrefix = true; x.HelpMode = HelpMode.Public; }); discordBot.UsingPermissionLevels((u, c) => (int)GetPermissions(u, c)); discordBot.UsingAudio(x => { x.Mode = AudioMode.Outgoing; }); CreateCommand(); discordBot.ExecuteAndWait(async() => { await discordBot.Connect(token); }); } catch (Exception ex) { Console.WriteLine(ex); } }
public void Start() { Console.WriteLine("Initializing..."); _client = new DiscordClient(); _client.UsingAudio(x => // Opens an AudioConfigBuilder so we can configure our AudioService { x.Mode = AudioMode.Outgoing; // Tells the AudioService that we will only be sending audio }); // _vClient = _client.GetService<AudioService>(); _client.MessageReceived += async (s, e) => { if (!e.Message.IsAuthor) { Console.WriteLine(e.Message.User.Name + "> " + e.Message.Text); if (e.Message.Text.StartsWith("!!")) { string command = e.Message.Text.Replace("!!", ""); // if (command.Equals("")) // { // await e.Channel.SendMessage("I am Jukebot. Do !!info for more details."); // // } string[] words = command.Split(' '); switch (words[0]) { case "info": await e.Channel.SendMessage( "```diff\n!====== [Jukebot] ======!" + "\nA shitty ass music bot made by Ratismal (stupid cat)" + "\nIt plays music. lol what did u expect" + "\n!== [Features] ==!" + "\n+ a shitty looking unintuitive piece of shit GUI that only the host can see (lol)" + "\n+ plays music" + "\n!== [Commands] ==!" + "\n+ !!info - shows this" + "\n+ !!summon - summons bot to current voice channel" + "\n+ !!banish - tells the bot to piss off" + "\n+ !!volume - shows the current volume" + "\n+ !!volume <amount> - set the volume" + "\n+ !!volume +-<amount> - add/subtract the volume" + "\n!== [Conclusi] ==!" + "\n+ '-on' cut off from title for consistancy spacing sake" + "\n+ f**k my life" + "\n+ you want to play something? GOOD LUCK WITH THAT LOL ONLY I CAN" + "\n- This is red text!" + "\n- its really late i should go to bed lol fml smfh lmao kms" + "\n```"); break; case "summon": Console.WriteLine("Joining a voice channel"); await e.Channel.SendMessage("Joining channel"); var voiceChannel = e.User.VoiceChannel; _vClient = await _client.GetService<AudioService>().Join(voiceChannel); //await _vClient.Join(voiceChannel); break; case "banish": Console.WriteLine("Leaving a voice channel"); await e.Channel.SendMessage("Leaving channel"); await _client.GetService<AudioService>().Leave(e.Server); break; case "volume": if (words.Length == 1) { e.Channel.SendMessage("Current volume: " + MainWindow.volume); } else { // string goodstuff; if (words[1].StartsWith("+") || words[1].StartsWith("-")) { int addVolume = Int32.Parse(words[1]); MainWindow.volume += addVolume; e.Channel.SendMessage("New volume: " + MainWindow.volume); } else { MainWindow.volume = Int32.Parse(words[1]); e.Channel.SendMessage("New volume: " + MainWindow.volume); } } break; default: await e.Channel.SendMessage("I am Jukebot. Do !!info for more details."); break; } } } }; _client.ExecuteAndWait(async () => { await _client.Connect(token ); }); Console.WriteLine("Cool story bro (finished)"); }
public async void Start() { var settings = GlobalSettings.Load(); if (settings == null) return; _client = new DiscordClient(); StartNet(settings.Port); if (settings.usePokeSnipers) { pollPokesniperFeed(); } _client.MessageReceived += async (s, e) => { if (settings.ServerChannels.Any(x => x.Equals(e.Channel.Name.ToString(), StringComparison.OrdinalIgnoreCase))) { await relayMessageToClients(e.Message.Text, e.Channel.Name.ToString()); } }; _client.ExecuteAndWait(async () => { if (settings.useToken && settings.DiscordToken != null) await _client.Connect(settings.DiscordToken); else if (settings.DiscordUser != null && settings.DiscordPassword != null) { try { await _client.Connect(settings.DiscordUser, settings.DiscordPassword); } catch { Console.WriteLine("Failed to authroize Discord user! Check your config.json and try again."); Console.ReadKey(); return; } } else { Console.WriteLine("Please set your logins in the config.json first"); } }); }
async void Init() { Karuta.logger.Log("Starting Discord Bot..", _appName); try { ImgurSetup(); } catch (Exception e) { Karuta.logger.LogError($"Unable to initiate Imgur Connection: {e.Message}", _appName); } client = new DiscordClient(); if(string.IsNullOrWhiteSpace(_token)) { _token = Karuta.GetInput("Enter discord token"); Karuta.registry.SetValue("discordToken", _token); } client.MessageReceived += MessageRecieved; client.UserJoined += UserJoined; try { await client.Connect(_token, TokenType.Bot); client.SetGame("World Domination"); //SendToAllConsoles("Bot Online"); }catch(Exception e) { Karuta.logger.LogWarning($"Unable to initiate connection to discord: {e.Message}", _appName); Karuta.logger.LogError(e.StackTrace, _appName, true); Karuta.Write("Unable to connect to discord..."); } }
private static void Main() { Console.OutputEncoding = Encoding.Unicode; //var lines = File.ReadAllLines("data/input.txt"); //HashSet<dynamic> list = new HashSet<dynamic>(); //for (int i = 0; i < lines.Length; i += 3) { // dynamic obj = new JArray(); // obj.Text = lines[i]; // obj.Author = lines[i + 1]; // if (obj.Author.StartsWith("-")) // obj.Author = obj.Author.Substring(1, obj.Author.Length - 1).Trim(); // list.Add(obj); //} //File.WriteAllText("data/quotes.json", Newtonsoft.Json.JsonConvert.SerializeObject(list, Formatting.Indented)); //Console.ReadKey(); // generate credentials example so people can know about the changes i make try { File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented)); if (!File.Exists("data/config.json")) File.Copy("data/config_example.json", "data/config.json"); File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented)); } catch { Console.WriteLine("Failed writing credentials_example.json or data/config_example.json"); } try { Config = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText("data/config.json")); Config.Quotes = JsonConvert.DeserializeObject<List<Quote>>(File.ReadAllText("data/quotes.json")); Config.PokemonTypes = JsonConvert.DeserializeObject<List<PokemonType>>(File.ReadAllText("data/PokemonTypes.json")); } catch (Exception ex) { Console.WriteLine("Failed loading configuration."); Console.WriteLine(ex); Console.ReadKey(); return; } try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //if password is not entered, prompt for password if (string.IsNullOrWhiteSpace(Creds.Password) && string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine("Password blank. Please enter your password:\n"); Creds.Password = Console.ReadLine(); } Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey) ? "No google api key found. You will not be able to use music and links won't be shortened." : "Google API key provided."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey) ? "No trello appkey found. You will not be able to use trello commands." : "Trello app key provided."); Console.WriteLine(Config.ForwardMessages != true ? "Not forwarding messages." : "Forwarding private messages to owner."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID) ? "No soundcloud Client ID found. Soundcloud streaming is disabled." : "SoundCloud streaming enabled."); BotMention = $"<@{Creds.BotId}>"; //create new discord client and log Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 10, ConnectionTimeout = 120000, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => Console.WriteLine($"Severity: {e.Severity}" + $"Message: {e.Message}" + $"ExceptionMessage: {e.Exception?.Message ?? "-"}"), }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled, ErrorHandler = async (s, e) => { if (e.ErrorType != CommandErrorType.BadPermissions) return; if (string.IsNullOrWhiteSpace(e.Exception?.Message)) return; try { await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false); } catch { } } }); //reply to personal messages and forward if enabled. Client.MessageReceived += Client_MessageReceived; //add command service Client.AddService<CommandService>(commandService); //create module service var modules = Client.AddService<ModuleService>(new ModuleService()); //add audio service Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, Bitrate = 128, })); //install modules modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None); modules.Add(new HelpModule(), "Help", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None); modules.Add(new MusicModule(), "Music", ModuleFilter.None); modules.Add(new SearchesModule(), "Searches", ModuleFilter.None); modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None); modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None); modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None); modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None); if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) modules.Add(new TrelloModule(), "Trello", ModuleFilter.None); //run the bot Client.ExecuteAndWait(async () => { try { if (string.IsNullOrWhiteSpace(Creds.Token)) await Client.Connect(Creds.Username, Creds.Password).ConfigureAwait(false); else { await Client.Connect(Creds.Token).ConfigureAwait(false); IsBot = true; } Console.WriteLine(NadekoBot.Client.CurrentUser.Id); } catch (Exception ex) { if (string.IsNullOrWhiteSpace(Creds.Token)) Console.WriteLine($"Probably wrong EMAIL or PASSWORD."); else Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account."); Console.WriteLine(ex); Console.ReadKey(); return; } //await Task.Delay(90000).ConfigureAwait(false); Console.WriteLine("-----------------"); Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false)); Console.WriteLine("-----------------"); try { OwnerPrivateChannel = await Client.CreatePrivateChannel(Creds.OwnerIds[0]).ConfigureAwait(false); } catch { Console.WriteLine("Failed creating private channel with the first owner listed in credentials.json"); } Client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) return; // meew0 is magic request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_"; if (string.IsNullOrWhiteSpace(request.Content)) e.Cancel = true; }; PermissionsHandler.Initialize(); NadekoBot.Ready = true; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
private async void button1_Click(object sender, EventArgs e) { lock (o) { if (button1Clicked) return; else button1Clicked = true; } DiscordClient client = new DiscordClient(); try { textBox1.Enabled = false; textBox2.Enabled = false; this.Text = "Logging in..."; await client.Connect(textBox1.Text, textBox2.Text); if (client.State == ConnectionState.Connected || client.State == ConnectionState.Connecting) { if (!checkBox1.Checked) { textBox1.Text = ""; textBox2.Text = ""; } Properties.Settings.Default.Email = textBox1.Text; Properties.Settings.Default.Password = textBox2.Text; Properties.Settings.Default.Remember = checkBox1.Checked; Properties.Settings.Default.Save(); // The best way to wait of course DateTime start = DateTime.Now; while (client.State != ConnectionState.Connected) { System.Threading.Thread.Sleep(10); var delta = DateTime.Now - start; if (delta >= TimeSpan.FromSeconds(TIMEOUT)) throw new TimeoutException("Login timed out. Either the email/password provided is incorrect or the program can not connect to Discord."); else if (delta < TimeSpan.Zero) throw new Exception("The time on this computer was changed."); } MainForm main = new MainForm(client); main.Owner = this; main.Show(); this.Hide(); } else { throw new Exception("Login failed."); } } catch (Exception ex) { textBox1.Enabled = true; textBox2.Enabled = true; this.Text = "DiscordStatusUpdater"; MessageBox.Show(ex.Message + Environment.NewLine + Environment.NewLine + ex.StackTrace, "Failed to login", MessageBoxButtons.OK, MessageBoxIcon.Error, MessageBoxDefaultButton.Button1); Console.WriteLine(ex.ToString() + Environment.NewLine + ex.StackTrace); client.Dispose(); } lock (o) { button1Clicked = false; } }
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()); } } }); }
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() { //load credentials from credentials.json bool loadTrello = false; try { creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); botMention = creds.BotMention; if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) { Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened."); } else { Console.WriteLine("Google API key provided."); GoogleAPIKey = creds.GoogleAPIKey; } if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) { Console.WriteLine("No trello appkey found. You will not be able to use trello commands."); } else { Console.WriteLine("Trello app key provided."); TrelloAppKey = creds.TrelloAppKey; loadTrello = true; } if (creds.ForwardMessages != true) Console.WriteLine("Not forwarding messages."); else { ForwardMessages = true; Console.WriteLine("Forwarding messages."); } if(string.IsNullOrWhiteSpace(creds.SoundCloudClientID)) Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled."); else Console.WriteLine("SoundCloud streaming enabled."); OwnerID = creds.OwnerID; password = creds.Password; } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //create new discord client client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 0, ConnectionTimeout = 60000, }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled }); //reply to personal messages and forward if enabled. client.MessageReceived += Client_MessageReceived; //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 AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, EnableMultiserver = true, Bitrate = 128, })); //install modules modules.Add(new Administration(), "Administration", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new Gambling(), "Gambling", ModuleFilter.None); modules.Add(new Games(), "Games", ModuleFilter.None); modules.Add(new Music(), "Music", ModuleFilter.None); modules.Add(new Searches(), "Searches", ModuleFilter.None); if (loadTrello) modules.Add(new Trello(), "Trello", ModuleFilter.None); modules.Add(new NSFW(), "NSFW", ModuleFilter.None); //run the bot client.ExecuteAndWait(async () => { await client.Connect(creds.Username, creds.Password); Console.WriteLine("-----------------"); Console.WriteLine(NadekoStats.Instance.GetStats()); Console.WriteLine("-----------------"); try { OwnerPrivateChannel = await client.CreatePrivateChannel(OwnerID); } catch { Console.WriteLine("Failed creating private channel with the owner"); } Classes.Permissions.PermissionsHandler.Initialize(); client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request != null) { if (string.IsNullOrWhiteSpace(request.Content)) e.Cancel = true; request.Content = request.Content.Replace("@everyone", "@everyοne"); } }; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }
public void Start() { const string configFile = "configuration.json"; try { _config = Configuration.LoadFile(configFile); // Load the configuration from a saved file. } catch { _config = new Configuration(); // Create a new configuration file if it doesn't exist. Console.WriteLine("Config file created. Enter a token."); Console.Write("Token: "); _config.Token = Console.ReadLine(); // Read the user's token from the console. _config.SaveFile(configFile); } _client = new DiscordClient(x => // Create a new instance of DiscordClient { x.AppName = "Moetron"; x.AppUrl = "https://github.com/Cappucirno/moetron"; x.AppVersion = "1.0"; x.LogLevel = LogSeverity.Info; // Mirror relevant information to the console. }) .UsingCommands(x => // Configure the Commands extension { x.PrefixChar = _config.Prefix; // Set the prefix from the configuration file x.HelpMode = HelpMode.Private; // Enable the automatic `!help` command. }) .UsingPermissionLevels((u, c) => (int)GetPermission(u, c)) // Permission levels are used to check basic or custom permissions .UsingModules(); // Configure the Modules extension // With LogLevel enabled, mirror info to the console in this format. _client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); // Load modules into the Modules extension. _client.AddModule<AdminModule>("Admin", ModuleFilter.None); _client.AddModule<EventModule>("Events", ModuleFilter.None); _client.AddModule<PointModule>("Points", ModuleFilter.None); _client.AddModule<ImageModule>("Images", ModuleFilter.None); _client.AddModule<UtilModule>("Utility", ModuleFilter.None); // Proper Login.md _client.ExecuteAndWait(async () => { while (true) { try { await _client.Connect(_config.Token, TokenType.Bot); break; } catch (Exception ex) { _client.Log.Error("Login Failed", ex); await Task.Delay(_client.Config.FailedReconnectDelay); } } }); //_client.SetGame("with your :heart:"); }
public Tars() { client = new DiscordClient(); timer = new Timer(UpdateGameTimer, client, 3000, 14400000); commands = new Dictionary<string, Func<CommandArgs, Task>>(); Commands.Init(commands); client.Log.Message += (s, e) => Console.WriteLine($"[{e.Severity}] {e.Source}: {e.Message}"); client.MessageReceived += async (s, e) => { if (e.Channel.IsPrivate) { CommandArgs dm = new CommandArgs(e); if (dm.Message.RawText.ToLower() == "tars help") await e.Channel.SendMessage(Util.GetInfo()); else { ulong id = 0; if (dm.Args.Count() >= 2 && dm.Message.RawText.ToLower().StartsWith("tars getprefix") && ulong.TryParse(dm.Args.ElementAt(1), out id)) await e.Channel.SendMessage("That server's prefix is: `" + DataBase.GetServerPrefix(id) + "`"); } return; } Console.WriteLine("[{0}] [{1}] [{2}]: {3}", e.Server.Name, e.Channel.Name, e.User.Name, e.Message.Text); if (e.Message.IsAuthor) return; if (e.Message.IsMentioningMe() && DataBase.IsUniqueUser(e.User.Id)) { await e.Channel.SendMessage(e.User.Mention + " " + Util.GetRandomHump()); return; } if (e.Message.RawText.ToLower().Contains("so i guess it's a") || e.Message.RawText.ToLower().Contains("so i suppose it's a")) { await e.Channel.SendFile("images/ADate.jpg"); return; } if (e.Message.RawText.ToLower().Equals("ayy")) { await e.Channel.SendMessage("lmao"); return; } if (e.Message.RawText.ToLower().StartsWith("present new changes")) { await e.Channel.SendMessage("In your lame life nothing has changed.\nAnd it's even sadder when you realize " + e.User.Mention + " made me say it."); return; } if (e.Message.RawText.ToLower().Equals("tars help")) { string currentPrefix = DataBase.GetServerPrefix(e.Server.Id); if (currentPrefix.ToLower() != "tars") { await e.Channel.SendMessage("TARS' prefix for this server is: `" + currentPrefix + "`\nUse `" + currentPrefix + " info`"); return; } } prefix = DataBase.GetServerPrefix(e.Server.Id).Trim().ToLower(); if (!e.Message.RawText.ToLower().StartsWith(prefix)) return; var trigger = string.Join("", e.Message.RawText.Substring(prefix.Length + 1).TakeWhile(c => c != ' ')); if (!commands.ContainsKey(trigger.ToLower())) { await e.Channel.SendMessage(Util.GetRandomGrump()); return; } await commands[trigger.ToLower()](new CommandArgs(e)); }; client.JoinedServer += async (s, e) => { await e.Server.DefaultChannel.SendMessage("Hello, I'm TARS, made by <@96550262403010560>, and I'm ready to rule the universe. ∞"); }; client.ExecuteAndWait(async () => { await client.Connect(ConstData.loginToken, TokenType.Bot); }); }
private static void Main() { Console.OutputEncoding = Encoding.Unicode; try { File.WriteAllText("data/config_example.json", JsonConvert.SerializeObject(new Configuration(), Formatting.Indented)); if (!File.Exists("data/config.json")) File.Copy("data/config_example.json", "data/config.json"); File.WriteAllText("credentials_example.json", JsonConvert.SerializeObject(new Credentials(), Formatting.Indented)); } catch { Console.WriteLine("Failed writing credentials_example.json or data/config_example.json"); } try { Config = JsonConvert.DeserializeObject<Configuration>(File.ReadAllText("data/config.json")); Config.Quotes = JsonConvert.DeserializeObject<List<Quote>>(File.ReadAllText("data/quotes.json")); Config.PokemonTypes = JsonConvert.DeserializeObject<List<PokemonType>>(File.ReadAllText("data/PokemonTypes.json")); } catch (Exception ex) { Console.WriteLine("Failed loading configuration."); Console.WriteLine(ex); Console.ReadKey(); return; } try { //load credentials from credentials.json Creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); Console.ReadKey(); return; } //if password is not entered, prompt for password if (string.IsNullOrWhiteSpace(Creds.Token)) { Console.WriteLine("Token blank. Please enter your bot's token:\n"); Creds.Token = Console.ReadLine(); } Console.WriteLine(string.IsNullOrWhiteSpace(Creds.GoogleAPIKey) ? "No google api key found. You will not be able to use music and links won't be shortened." : "Google API key provided."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.TrelloAppKey) ? "No trello appkey found. You will not be able to use trello commands." : "Trello app key provided."); Console.WriteLine(Config.ForwardMessages != true ? "Not forwarding messages." : "Forwarding private messages to owner."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.SoundCloudClientID) ? "No soundcloud Client ID found. Soundcloud streaming is disabled." : "SoundCloud streaming enabled."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.OsuAPIKey) ? "No osu! api key found. Song & top score lookups will not work. User lookups still available." : "osu! API key provided."); Console.WriteLine(string.IsNullOrWhiteSpace(Creds.DerpiAPIKey) ? "No Derpiboori api key found. Only searches useing the Default filter will work." : "Derpiboori API key provided."); BotMention = $"<@{Creds.BotId}>"; //create new discord client and log Client = new DiscordClient(new DiscordConfigBuilder() { MessageCacheSize = 10, ConnectionTimeout = int.MaxValue, LogLevel = LogSeverity.Warning, LogHandler = (s, e) => Console.WriteLine($"Severity: {e.Severity}" + $"ExceptionMessage: {e.Exception?.Message ?? "-"}" + $"Message: {e.Message}"), }); //create a command service var commandService = new CommandService(new CommandServiceConfigBuilder { AllowMentionPrefix = false, CustomPrefixHandler = m => 0, HelpMode = HelpMode.Disabled, ErrorHandler = async (s, e) => { if (e.ErrorType != CommandErrorType.BadPermissions) return; if (string.IsNullOrWhiteSpace(e.Exception?.Message)) return; try { await e.Channel.SendMessage(e.Exception.Message).ConfigureAwait(false); } catch { } } }); //add command service Client.AddService<CommandService>(commandService); //create module service var modules = Client.AddService<ModuleService>(new ModuleService()); //add audio service Client.AddService<AudioService>(new AudioService(new AudioServiceConfigBuilder() { Channels = 2, EnableEncryption = false, Bitrate = 128, })); //install modules modules.Add(new HelpModule(), "Help", ModuleFilter.None); modules.Add(new AdministrationModule(), "Administration", ModuleFilter.None); modules.Add(new UtilityModule(), "Utility", ModuleFilter.None); modules.Add(new PermissionModule(), "Permissions", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new GamblingModule(), "Gambling", ModuleFilter.None); modules.Add(new GamesModule(), "Games", ModuleFilter.None); #if !NADEKO_RELEASE modules.Add(new MusicModule(), "Music", ModuleFilter.None); #endif modules.Add(new SearchesModule(), "Searches", ModuleFilter.None); modules.Add(new NSFWModule(), "NSFW", ModuleFilter.None); modules.Add(new ClashOfClansModule(), "ClashOfClans", ModuleFilter.None); modules.Add(new PokemonModule(), "Pokegame", ModuleFilter.None); modules.Add(new TranslatorModule(), "Translator", ModuleFilter.None); modules.Add(new CustomReactionsModule(), "Customreactions", ModuleFilter.None); if (!string.IsNullOrWhiteSpace(Creds.TrelloAppKey)) modules.Add(new TrelloModule(), "Trello", ModuleFilter.None); //run the bot Client.ExecuteAndWait(async () => { await Task.Run(() => { Console.WriteLine("Specific config started initializing."); var x = SpecificConfigurations.Default; Console.WriteLine("Specific config done initializing."); }); await PermissionsHandler.Initialize(); try { await Client.Connect(Creds.Token, TokenType.Bot).ConfigureAwait(false); } catch (Exception ex) { Console.WriteLine($"Token is wrong. Don't set a token if you don't have an official BOT account."); Console.WriteLine(ex); Console.ReadKey(); return; } #if NADEKO_RELEASE await Task.Delay(300000).ConfigureAwait(false); #else await Task.Delay(1000).ConfigureAwait(false); #endif Console.WriteLine("-----------------"); Console.WriteLine(await NadekoStats.Instance.GetStats().ConfigureAwait(false)); Console.WriteLine("-----------------"); OwnerPrivateChannels = new List<Channel>(Creds.OwnerIds.Length); foreach (var id in Creds.OwnerIds) { try { OwnerPrivateChannels.Add(await Client.CreatePrivateChannel(id).ConfigureAwait(false)); } catch { Console.WriteLine($"Failed creating private channel with the owner {id} listed in credentials.json"); } } Client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) return; // meew0 is magic request.Content = request.Content?.Replace("@everyone", "@everyοne").Replace("@here", "@һere") ?? "_error_"; if (string.IsNullOrWhiteSpace(request.Content)) e.Cancel = true; }; #if NADEKO_RELEASE Client.ClientAPI.SentRequest += (s, e) => { Console.WriteLine($"[Request of type {e.Request.GetType()} sent in {e.Milliseconds}]"); var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request == null) return; Console.WriteLine($"[Content: { request.Content }"); }; #endif NadekoBot.Ready = true; NadekoBot.OnReady(); Console.WriteLine("Ready!"); //reply to personal messages and forward if enabled. Client.MessageReceived += Client_MessageReceived; }); 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 static async void ConnectAsync() { State = ConnectionState.Connecting; Client = new DiscordClient(); Client.MessageReceived += MessageHandler.HandleIncomingMessage; Client.MessageUpdated += MessageHandler.HandleEdit; Console.WriteLine("Connecting..."); try { await Client.Connect(Config.Token, TokenType.Bot); Client.SetGame("3v.fi/l/BotVentic"); State = ConnectionState.Connected; Console.WriteLine("Connected!"); } catch (Exception ex) { Console.WriteLine(ex.ToString()); Console.WriteLine("Reconnecting..."); State = ConnectionState.Disconnected; Client.Dispose(); } }
private void Start(string[] args) { #if !DNXCORE50 Console.Title = $"{AppName} (Discord.Net v{DiscordConfig.LibVersion})"; #endif GlobalSettings.Load(); _client = new DiscordClient(x => { x.AppName = AppName; x.AppUrl = AppUrl; x.MessageCacheSize = 0; x.UsePermissionsCache = true; x.EnablePreUpdateEvents = true; x.LogLevel = LogSeverity.Debug; x.LogHandler = OnLogMessage; }) .UsingCommands(x => { x.AllowMentionPrefix = true; x.HelpMode = HelpMode.Public; x.ExecuteHandler = OnCommandExecuted; x.ErrorHandler = OnCommandError; }) .UsingModules() .UsingAudio(x => { x.Mode = AudioMode.Outgoing; x.EnableMultiserver = true; x.EnableEncryption = true; x.Bitrate = AudioServiceConfig.MaxBitrate; x.BufferLength = 10000; }) .UsingPermissionLevels(PermissionResolver); _client.AddService<SettingsService>(); _client.AddService<HttpService>(); _client.AddModule<AdminModule>("Admin", ModuleFilter.ServerWhitelist); _client.AddModule<ColorsModule>("Colors", ModuleFilter.ServerWhitelist); _client.AddModule<FeedModule>("Feeds", ModuleFilter.ServerWhitelist); _client.AddModule<GithubModule>("Repos", ModuleFilter.ServerWhitelist); _client.AddModule<ModulesModule>("Modules", ModuleFilter.None); _client.AddModule<PublicModule>("Public", ModuleFilter.None); _client.AddModule<TwitchModule>("Twitch", ModuleFilter.ServerWhitelist); _client.AddModule<StatusModule>("Status", ModuleFilter.ServerWhitelist); //_client.AddModule(new ExecuteModule(env, exporter), "Execute", ModuleFilter.ServerWhitelist); #if PRIVATE PrivateModules.Install(_client); #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: ExecuteAndWait is only needed for Console projects as Main can't be declared as async. UI/Web applications should *not* use this function. _client.ExecuteAndWait(async () => { while (true) { try { await _client.Connect(GlobalSettings.Discord.Email, GlobalSettings.Discord.Password); _client.SetGame("Discord.Net"); //await _client.ClientAPI.Send(new Discord.API.Client.Rest.HealthRequest()); break; } catch (Exception ex) { _client.Log.Error($"Login Failed", ex); await Task.Delay(_client.Config.FailedReconnectDelay); } } }); }
public override void Start() { Running = true; client.Connect(token, Discord.TokenType.Bot); }
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"); }
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); } } }); }
static void Main() { //load credentials from credentials.json bool loadTrello = false; try { creds = JsonConvert.DeserializeObject<Credentials>(File.ReadAllText("credentials.json")); botMention = creds.BotMention; if (string.IsNullOrWhiteSpace(creds.GoogleAPIKey)) { Console.WriteLine("No google api key found. You will not be able to use music and links won't be shortened."); } else { Console.WriteLine("Google API key provided."); GoogleAPIKey = creds.GoogleAPIKey; } if (string.IsNullOrWhiteSpace(creds.TrelloAppKey)) { Console.WriteLine("No trello appkey found. You will not be able to use trello commands."); } else { Console.WriteLine("Trello app key provided."); TrelloAppKey = creds.TrelloAppKey; loadTrello = true; } if (creds.ForwardMessages != true) Console.WriteLine("Not forwarding messages."); else { ForwardMessages = true; Console.WriteLine("Forwarding messages."); } if (string.IsNullOrWhiteSpace(creds.ParseID) || string.IsNullOrWhiteSpace(creds.ParseKey)) { Console.WriteLine("Parse key and/or ID not found. Those are mandatory."); ParseActive = false; } else ParseActive = true; if(string.IsNullOrWhiteSpace(creds.OsuApiKey)) Console.WriteLine("No osu API key found. Osu functionality is disabled."); else Console.WriteLine("Osu enabled."); if(string.IsNullOrWhiteSpace(creds.SoundCloudClientID)) Console.WriteLine("No soundcloud Client ID found. Soundcloud streaming is disabled."); else Console.WriteLine("SoundCloud streaming enabled."); //init parse if (ParseActive) try { ParseClient.Initialize(creds.ParseID, creds.ParseKey); } catch (Exception) { Console.WriteLine("Parse exception. Probably wrong parse credentials."); } OwnerID = creds.OwnerID; password = creds.Password; } catch (Exception ex) { Console.WriteLine($"Failed to load stuff from credentials.json, RTFM\n{ex.Message}"); 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 }); //reply to personal messages and forward if enabled. client.MessageReceived += Client_MessageReceived; //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, EnableMultiserver = true, Bitrate = 128, })); //install modules modules.Add(new Administration(), "Administration", ModuleFilter.None); modules.Add(new Conversations(), "Conversations", ModuleFilter.None); modules.Add(new Gambling(), "Gambling", ModuleFilter.None); modules.Add(new Games(), "Games", ModuleFilter.None); modules.Add(new Music(), "Music", ModuleFilter.None); modules.Add(new Searches(), "Searches", ModuleFilter.None); if (loadTrello) modules.Add(new Trello(), "Trello", ModuleFilter.None); //run the bot client.ExecuteAndWait(async () => { await client.Connect(creds.Username, creds.Password); Console.WriteLine("-----------------"); Console.WriteLine(NadekoStats.Instance.GetStats()); Console.WriteLine("-----------------"); foreach (var serv in client.Servers) { if ((OwnerUser = serv.GetUser(OwnerID)) != null) return; } client.ClientAPI.SendingRequest += (s, e) => { var request = e.Request as Discord.API.Client.Rest.SendMessageRequest; if (request != null) { if (string.IsNullOrWhiteSpace(request.Content)) e.Cancel = true; } }; }); Console.WriteLine("Exiting..."); Console.ReadKey(); }