public static async Task Main() { try { BotHandler handler = new BotHandler(); DiscordBot client = new DiscordBot(".config"); await client.configManger.LoadData(client.cacheManger); await client.Setup(await client.cacheManger.GetAsync("Token")); await client.cacheManger.AddAsync("CommandCall", "0"); await client.cacheManger.AddAsync("MessageCall", "0"); await handler.StartHandler(); await client.StartAsync(); await Task.Delay(-1); } catch (Exception ex) { Console.WriteLine(ex); Environment.Exit(1); } }
public DiscordPaginatedMessageContext(IEmote emote, IUserMessage message, DiscordBot bot) : base(message, bot) { switch (emote.Name) { case "⏮": Direction = ScrollDirection.SkipToBeginning; break; case "⬅": Direction = ScrollDirection.Backwards; break; case "➡": Direction = ScrollDirection.Forwards; break; case "⏭": Direction = ScrollDirection.SkipToEnd; break; } Match match = PaginatedCommand.FooterRegex.Match(message.Embeds.FirstOrDefault()?.Footer?.Text ?? ""); Command = match.Groups["command"].Value; CurrentPageNumber = int.Parse(match.Groups["pageNumber"].Value); LastPage = int.Parse(match.Groups["lastPage"].Value); }
private static void isPlayerTeleportHacking(AnticheatInfo player) { // Has the player left a car recently. if (player.LeftCarRecently) { player.LeftCarRecently = false; player.LastPosition = player.PlayerClient.position; return; } // Player on foot can cover about 21 feet per 3 seconds. if (!player.PlayerClient.isInVehicle) { if (player.PlayerClient.position.DistanceTo2D(player.LastPosition) > 28) { player.CurrentStrikes += 1; DiscordBot.sendMessageToServer(string.Format("[Anticheat] {0}, strike added for Teleporting.", player.PlayerClient.name)); } } else { if (player.PlayerClient.position.DistanceTo2D(player.LastPosition) > 180) { player.CurrentStrikes += 1; DiscordBot.sendMessageToServer(string.Format("[Anticheat] {0}, strike added for Teleporting.", player.PlayerClient.name)); } } player.LastPosition = player.PlayerClient.position; }
public ReactionControlCommands(MessageConfiguration msgCfg, DiscordBot bot, DbRepository repo, [Named("plugin")] Logger log) { this.msgCfg = msgCfg; this.bot = bot; this.repo = repo; this.log = log; }
public static void Main(string[] args) { Native.SetThreadExecutionState(EXECUTION_STATE.ES_DISPLAY_REQUIRED); // prevent server from sleeping var bot = new DiscordBot(); bot.Start(); }
public async Task GeneralStats() { // Get the guilds IReadOnlyCollection <IGuild> guilds = DiscordBot.GetGuilds(); // Count the total number of users int users = 0; foreach (SocketGuild guild in guilds) { users += guild.MemberCount; } // Calculate the number of registered servers int registeredServers = Configuration.LoadedConfiguration.DiscordConfig.GuildSettings.Count; int percent = (int)Math.Round((double)(100 * registeredServers) / guilds.Count); // Create an embed Embed embed = new EmbedBuilder() .WithTitle("General Statistics") .AddField("Servers", $"{guilds.Count}") .AddField("Registered Servers", $"{registeredServers} (approx. {percent}%)") .AddField("Total Users", users) .WithTimestamp(DateTimeOffset.UtcNow) .WithColor(Color.Blue) .Build(); // Send the embed await Context.Channel.SendMessageAsync(embed : embed); }
public async Task ServerLookup(ulong id) { // Get the GuildSettings GuildSettings guildSettings = Configuration.LoadedConfiguration.DiscordConfig.GuildSettings.Where(settings => settings.GuildId == id).FirstOrDefault(); // Get the SocketGuild and SocketGuildChannel SocketGuild guild = DiscordBot.GetGuild(id); // Build an embed EmbedBuilder embedBuilder = new EmbedBuilder() .WithTitle("Lookup") .AddField("Guild", $"{guild.Name} ({guild.Id}, {(guildSettings != null ? "registered" : "unregistered")})"); // Check if this guild is registered if (guildSettings != null) { // Get the registered channel SocketGuildChannel channel = guild.GetChannel(guildSettings.TargetChannelId); // Add additional lookup details embedBuilder .AddField("Channel", $"#{channel.Name} ({channel.Id})") .AddField("Language", guildSettings.DefaultLanguage.ToString()); } // Complete the embed embedBuilder .AddField("Owner", $"{guild.Owner.Username}#{guild.Owner.Discriminator} ({guild.Owner.Id})") .AddField("User Count", guild.MemberCount) .WithColor(Color.Blue); await Context.Channel.SendMessageAsync(embed : embedBuilder.Build()); }
/// <summary> /// Generates default command name->method pairs. /// </summary> void DefaultCommands(DiscordBot bot) { AdminCommands adminCmds = new AdminCommands(); MetaCommands metaCmds = new MetaCommands(); UtilityCommands utilCmds = new UtilityCommands(); CoreCommands coreCmds = new CoreCommands(IsBotCommander); // Informational bot.RegisterCommand(InfoCmds.CMD_Help, "help", "halp", "helps", "halps", "hel", "hal", "h"); bot.RegisterCommand(InfoCmds.CMD_Hello, "hello", "hi", "hey", "source", "src"); bot.RegisterCommand(InfoCmds.CMD_Info, "info", "notice", "alert"); bot.RegisterCommand(InfoCmds.CMD_Update, "update", "latest", "current", "build", "builds", "download", "version"); bot.RegisterCommand(InfoCmds.CMD_GitHub, "github", "git", "gh", "readme", "read", "link"); bot.RegisterCommand(InfoCmds.CMD_Issues, "issues", "issue", "error", "ghissues", "githubissues"); bot.RegisterCommand(InfoCmds.CMD_Rule, "rule", "rules"); bot.RegisterCommand(InfoCmds.CMD_Quote, "quote", "quotes", "q"); // Meta Docs bot.RegisterCommand(metaCmds.CMD_Command, "command", "commands", "cmd", "cmds", "c"); bot.RegisterCommand(metaCmds.CMD_Mechanism, "mechanism", "mechanisms", "mech", "mechs", "mec", "mecs", "m"); bot.RegisterCommand(metaCmds.CMD_Tag, "tag", "tags", "t"); bot.RegisterCommand(metaCmds.CMD_Event, "event", "events", "evt", "evts", "e"); bot.RegisterCommand(metaCmds.CMD_Action, "action", "actions", "act", "acts", "a"); bot.RegisterCommand(metaCmds.CMD_Language, "language", "languages", "lang", "langs", "l"); bot.RegisterCommand(metaCmds.CMD_Guide, "guide", "guides", "g", "beginner", "beginners", "beginnersguide", "guidepage", "guidespage"); bot.RegisterCommand(metaCmds.CMD_Search, "search", "s", "find", "f", "get", "locate", "what", "where", "how", "w", "meta", "metainfo", "docs", "doc", "documentation", "documentations", "document", "documents"); // Utility bot.RegisterCommand(utilCmds.CMD_LogCheck, "logcheck", "checklog", "logscheck", "checklogs"); bot.RegisterCommand(utilCmds.CMD_VersionCheck, "versioncheck", "checkversion", "iscurrent", "isuptodate", "isupdated", "checkcurrent", "currentcheck"); bot.RegisterCommand(utilCmds.CMD_ScriptCheck, "script", "scriptcheck", "dscript", "ds", "checkscript", "dscriptcheck", "checkdscript"); // Admin bot.RegisterCommand(coreCmds.CMD_Restart, "restart"); bot.RegisterCommand(adminCmds.CMD_Reload, "reload"); }
public static async Task <int> Main(string[] args) { Console.OutputEncoding = Encoding.UTF8; if (args.Any()) { var mode = args[0]; switch (mode) { case "interactive": case "script": { var game = FindLostyGame.Terminal(args.FirstOrDefault(), args.ElementAtOrDefault(1)); await game.StartAsync(); } break; case "web": { var game = FindLostyGame.Webserver(args.ElementAtOrDefault(1)); await game.StartAsync(); } break; } } else { var bot = new DiscordBot(); bot.RegisterGame("FindLosty", FindLostyGame.Discord); await bot.Start("FindLosty"); await Task.Delay(-1); } return(0); }
public async Task AddRole(CommandContext ctx, string role, params string[] commands) { if (Permissions.CheckPrivate(ctx)) { return; } if (commands.Length == 0) { commands = new string[] { "*" }; } var mention = ctx.Member.Mention; if (Permissions.CheckCommandPermission(ctx)) { if (DiscordBot.AddRole(role, commands, ctx.Guild)) { await DiscordBot.RespondAsync(ctx, mention + ", role **" + role + "** added for * " + string.Join(", ", commands) + " *"); } else { await DiscordBot.RespondAsync(ctx, mention + ", that didn't work."); } } else { await DiscordBot.RespondAsync(ctx, mention + ", you do not have permission to do that."); } }
public static async Task HandleAdded(LineNews lineNews) { // Localize the embed title Dictionary <Language, string> localizedTitles = Localizer.LocalizeToAllLanguagesWithFormat("line_news.title", Nintendo.SmashUltimate.Bcat.Container.LanguageOrder, lineNews.Id); // Localize the embed description // Dictionary<Language, string> localizedDescriptions = Localizer.LocalizeToAllLanguages("line_news.more_info", $"https://smash.oatmealdome.me/line_news/{lineNews.Id}/{pair.Key.GetCode()}/"); // Create localized Embeds LocalizedEmbedBuilder localizedEmbedBuilder = new LocalizedEmbedBuilder(Nintendo.SmashUltimate.Bcat.Container.LanguageOrder) .WithTitle(localizedTitles) //.WithDescription(localizedDescriptions) .AddField("line_news.start_time", Localizer.LocalizeDateTimeToAllLanguages(lineNews.StartDateTime)) .AddField("line_news.end_time", Localizer.LocalizeDateTimeToAllLanguages(lineNews.EndDateTime)); // Add every OneLine foreach (OneLine oneLine in lineNews.OneLines) { localizedEmbedBuilder.AddField(Localizer.LocalizeToAllLanguagesWithFormat("line_news.line_title", oneLine.Id), oneLine.Text); } // Create localized Embeds Dictionary <Language, Embed> localizedEmbeds = localizedEmbedBuilder.Build(); // Send the notifications await DiscordBot.SendNotificationAsync("**[Line News]**", localizedEmbeds); }
public TwitchController(TwitchService service, DiscordBot discord, DiscordContext ctx, ILogger <TwitchController> logger) { _service = service; _discord = discord; _db = ctx; _logger = logger; }
public async Task RemoveChannel(CommandContext ctx, string channelIDorName) { if (Permissions.CheckPrivate(ctx)) { return; } var mention = ctx.Member.Mention; var channel = ctx.Guild.Channels.Values.FirstOrDefault(x => x.Name.Equals(channelIDorName) || x.Id.ToString().Equals(channelIDorName)); if (Permissions.CheckCommandPermission(ctx)) { if (DiscordBot.RemoveChannel(channel)) { await DiscordBot.RespondAsync(ctx, mention + ", channel **" + channelIDorName + "** removed from valid response channels"); } else { await DiscordBot.RespondAsync(ctx, mention + ", that didn't work."); } } else { await DiscordBot.RespondAsync(ctx, mention + ", you do not have permission to do that."); } }
public async Task CreateNote(CommandContext ctx, string idOrName, params string[] noteContentList) { if (Permissions.CheckPrivate(ctx)) { return; } var mention = ctx.Member.Mention; var noteContent = string.Join(" ", noteContentList); if (Permissions.CheckCommandPermission(ctx)) { if (noteContent.Length > 1500) { await DiscordBot.RespondAsync(ctx, mention + ", maximum note length is 1500 characters"); } else if (DiscordBot.AddNote(idOrName, noteContent, ctx)) { await DiscordBot.RespondAsync(ctx, mention + ", note for **" + idOrName + "** added."); } else { await DiscordBot.RespondAsync(ctx, mention + ", that didn't work."); } } else { await DiscordBot.RespondAsync(ctx, mention + ", you do not have permission to do that."); } }
public async Task GetAllNotes(CommandContext ctx) { if (Permissions.CheckPrivate(ctx)) { return; } var mention = ctx.Member.Mention; if (Permissions.CheckCommandPermission(ctx)) { if (!DiscordBot.GetAllNotes(ctx, 1, 25)) { await DiscordBot.RespondAsync(ctx, mention + ", that didn't work."); } else { if (!_pagingCache.ContainsKey(ctx.Guild.ToString())) { _pagingCache.Add(ctx.Guild.ToString(), new Dictionary <ulong, int>()); } var guildPagingCache = _pagingCache[ctx.Guild.ToString()]; if (!guildPagingCache.ContainsKey(ctx.Member.Id)) { guildPagingCache.Add(ctx.Member.Id, 25); } } } else { await DiscordBot.RespondAsync(ctx, mention + ", you do not have permission to do that."); } }
public CommandHandler(DiscordSocketClient client, DiscordBot bot) { this.client = client; this.bot = bot; this.mainServiceProvider = bot.MainProvider; this.commands = this.mainServiceProvider.GetRequiredService <CommandService>(); }
public async Task MainAsync() { var bot = new DiscordBot("settings.json"); await bot.Start(); await Task.Delay(-1); }
public async Task <IActionResult> Edit(int id, [Bind("Id,BotToken,Name")] DiscordBot discordBot) { if (id != discordBot.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(discordBot); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DiscordBotsExists(discordBot.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(discordBot)); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); services.AddDbContext <ApplicationDbContext>( options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); services.AddScoped <Proj2Aalst_G3DataInitializer>(); services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; }).AddCookie(options => { options.LoginPath = "/signin"; options.LogoutPath = "/signout"; }).AddDiscord(options => { options.ClientId = Configuration["Discord:ClientId"]; options.ClientSecret = Configuration["Discord:ClientSecret"]; options.Scope.Add("email"); options.Scope.Add("guilds.join"); }); //TODO Clean this mess up DiscordBot bot = new DiscordBot(Configuration["Discord:BotToken"], Configuration["Discord:Prefix"], Configuration["Discord:LfgChannelName"]); bot.Start(); }
private void API_onPlayerDisconnected(Client player, string reason) { // Add our player to our connection cooldown. ConnectionManager.AddClient(player.address); if (!API.hasEntityData(player, "Instance")) { return; } Player instance = (Player)API.getEntityData(player, "Instance"); // Used for players in interiors. Logs them out outside the interior. if (player.hasData("LastPosition")) { player.position = player.getData("LastPosition"); } if (player.hasData("Anticheat")) { AnticheatInfo info = player.getData("Anticheat"); info.isOnline = false; info.LastPosition = player.position; } // Update player data just as they disconnect. instance.updatePlayerPosition(); instance.PlayerClothing.savePlayerClothes(); instance.PlayerInventory.saveInventory(); instance.removePlayerVehicles(); DiscordBot.sendMessageToServer(string.Format("{0} has logged out from the server.", player.name)); }
static void Main(string[] args) { //TODO check for duplicates /*DraftPick draft = new DraftPick(); * draft.Bans.Add(Civilization.Venice); * draft.NumCivsPerPerson = 5; * draft.Players.Add(00); * draft.Players.Add(01); * draft.Players.Add(02); * draft.Players.Add(03); * draft.Players.Add(04); * draft.Players.Add(05); * draft.Players.Add(06); * draft.Players.Add(07); * * draft.GeneratePicks(); * * int a = 0; * foreach(var x in draft.PlayerOptions) * { * string s = ""; * foreach(var y in x.picks) * { * s += y.ToString() + " / "; * } * Console.WriteLine("Player {0}: {1}", a, s); * a++; * }*/ DiscordBot bot = new DiscordBot(); }
public static string ParseSpecialStrings(string localizedValue, Language language) { // Match every special string foreach (Match match in Regex.Matches(localizedValue, @"{\$.*?}")) { // Remove the brackets and dollar sign string specialStr = match.Value.Substring(2, match.Value.Length - 3); // Get the appropriate replacement string replacement; switch (specialStr) { case "BOT_NAME": replacement = DiscordBot.GetName(); break; case "BOT_COMMAND_PREFIX": replacement = Configuration.LoadedConfiguration.DiscordConfig.CommandPrefix; break; default: replacement = Localizer.Localize("localizer.bad_special_string", language); break; } // Replace the special string localizedValue = localizedValue.Replace(match.Value, replacement); } return(localizedValue); }
public async Task SetDeletionDelay(CommandContext ctx, int delay) { if (Permissions.CheckPrivate(ctx)) { return; } var mention = ctx.Member.Mention; if (Permissions.CheckCommandPermission(ctx)) { if (!DiscordBot.SetDeletionDelay(ctx, delay)) { await DiscordBot.RespondAsync(ctx, mention + ", that didn't work."); } else { var newDelay = DiscordBot.GetOptions().DeletionDelayInSeconds; await DiscordBot.RespondAsync(ctx, mention + ", deletion delay set to " + newDelay); } } else { await DiscordBot.RespondAsync(ctx, mention + ", you do not have permission to do that."); } }
public static void checkHealth(Client player, int oldValue) { if (!player.hasData("Anticheat")) { return; } // Get Anticheat Info AnticheatInfo info = player.getData("Anticheat"); // If their health is only going down, don't worry about it. if (player.health < oldValue) { return; } // If their health is going up, we're checking it. if (info.HealthChangedRecently) { info.HealthChangedRecently = false; return; } else { info.CurrentStrikes += 1; DiscordBot.sendMessageToServer(string.Format("[Anticheat] {0}, possible health hacking.", player.name)); } }
public async Task StartAsync(CancellationToken cancellationToken) { _logger.LogInformation("Initializing"); var bots = new List <IBot>(); if (cancellationToken.CanBeCanceled) { cancellationToken.Register(() => _cancellationTokenSource.Cancel()); } if (!_configuration.GetSection("Discord").Exists()) { _logger.LogCritical("Missing configuration for Discord features"); } _logger.LogDebug("Initializing bot logic for Discord"); var discordConfig = new DiscordBotConfig(); _configuration.GetSection("Discord").Bind(discordConfig); var discordBot = new DiscordBot(_loggerFactory, new DiscordSocketClient(), discordConfig); bots.Add(discordBot); _logger.LogInformation("Starting {0} bots", bots.Count); bots.ForEach(t => t.RunAsync(_cancellationTokenSource.Token)); await Task.Delay(-1, _cancellationTokenSource.Token); }
public static async Task HandleAdded(PopUpNews popUpNews) { // Localize the embed description Dictionary <Language, string> localizedDescriptions = Localizer.LocalizeToAllLanguages("popup_news.description", Nintendo.SmashUltimate.Bcat.Container.LanguageOrder); // Create a new Dictionary for localized descriptions with the URL Dictionary <Language, string> localizedDescriptionsWithUrl = new Dictionary <Language, string>(); // Loop over every localized description foreach (KeyValuePair <Language, string> pair in localizedDescriptions) { // Format the URL in the description localizedDescriptionsWithUrl.Add(pair.Key, string.Format(pair.Value, popUpNews.ContentText[pair.Key], $"https://smash.oatmealdome.me/popup_news/{popUpNews.Id}/{pair.Key.GetCode()}/")); } // Create localized Embeds Dictionary <Language, Embed> localizedEmbeds = new LocalizedEmbedBuilder(Nintendo.SmashUltimate.Bcat.Container.LanguageOrder) .WithTitle(popUpNews.TitleText) .WithDescription(localizedDescriptionsWithUrl) .AddField("popup_news.start_time", Localizer.LocalizeDateTimeToAllLanguages(popUpNews.StartDateTime)) .AddField("popup_news.end_time", Localizer.LocalizeDateTimeToAllLanguages(popUpNews.EndDateTime)) .WithImageUrl($"https://cdn.oatmealdome.me/smash/popup_news/{popUpNews.Id}/image.jpg") .Build(); // Send the notifications await DiscordBot.SendNotificationAsync("**[News]**", localizedEmbeds); }
private void LoadDiscordBot() { if (discordBot is object) { discordBot.Stop(); } discordBot = new DiscordBot(General.CurProject.DiscordBotConfig); bool hasLoaded = false; bool hasError = false; discordBot.GotReady += (sender, e) => hasLoaded = true; discordBot.LoggedMsg += (sender, msg, isError) => { if (isError) { hasError = true; } }; discordBot.Start(); ProgressControls(true); while (!hasLoaded && !hasError) { Application.DoEvents(); } ProgressControls(false); if (hasError) { discordBot = null; } }
/// <summary> /// Starts the <see cref="CoinBot"/>. /// </summary> /// <param name="provider">The <see cref="IServiceProvider"/>.</param> /// <returns></returns> private static async Task Run(IServiceProvider provider) { //set up a task completion source so we can quit on CTRL+C TaskCompletionSource <bool> exitSource = new TaskCompletionSource <bool>(); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; exitSource.SetResult(true); }; CurrencyManager coinManager = provider.GetRequiredService <CurrencyManager>(); MarketManager marketManager = provider.GetRequiredService <MarketManager>(); DiscordBot bot = provider.GetRequiredService <DiscordBot>(); // Initialize the bot DiscordBotSettings botConfig = provider.GetRequiredService <IOptions <DiscordBotSettings> >().Value; await bot.LoginAsync(TokenType.Bot, botConfig.Token); // Start the bot & coinSource await bot.StartAsync(); coinManager.Start(); marketManager.Start(); // Keep the application alive until the exitSource task is completed. await exitSource.Task; // Stop the bot & coinSource await bot.LogoutAsync(); coinManager.Stop(); marketManager.Stop(); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env, DiscordBot bot, DiscordContext ctx) { ctx.Database.EnsureCreated(); var queries = new string[] { "ALTER TABLE Guild ADD COLUMN AnnounceRoleId INTEGER DEFAULT 0 NOT NULL", "ALTER TABLE Guild ADD COLUMN EnableVods INTEGER DEFAULT 0 NOT NULL", "ALTER TABLE Guild ADD COLUMN VodChannelId INTEGER DEFAULT 0 NOT NULL", }; foreach (var query in queries) { try { ctx.Database.ExecuteSqlRaw(query); } catch {} } bot.Start(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); }
private static async Task Main(string[] args) { await ConfigureServices(); var logger = _serviceProvider.GetRequiredService <ILogger <Program> >(); if (!_serviceProvider.GetRequiredService <Config>().IsValid()) { await Exit(ExitCodes.CONFIGURATION_IS_INVALID, "Configuration is not valid!"); } var cancellationToken = new CancellationTokenSource(); Console.CancelKeyPress += (sender, eventArgs) => { eventArgs.Cancel = true; cancellationToken.Cancel(); }; logger.LogInformation($"Setting up the DB..."); if (_serviceProvider.GetRequiredService <Config>().IsContainerized) { logger.LogInformation("App is containerized. - Giving some ahead time for DB to kick in..."); await Task.Delay(10_000); } var connectionString = _serviceProvider.GetRequiredService <ConnectionString>(); try { await DatabaseHelpers.SetupTables(connectionString); await DatabaseHelpers.SetupProcedures(connectionString); logger.LogInformation("DB is set up."); } catch (Exception) { await Exit(ExitCodes.COULD_NOT_CONNECT_TO_DB, "Couldn't connect to DB! Check your connection.."); } try { await Task.WhenAll(new Task[] { Task.Run(() => DiscordBot.DiscordMainAsync(_serviceProvider, cancellationToken), cancellationToken.Token), Task.Run(() => DatabaseConnectionController.ControlDatabaseConnection(_serviceProvider, cancellationToken), cancellationToken.Token) }); } catch (Exception ex) { cancellationToken.Cancel(); logger.LogCritical(ex, "Exception occured in one of the clients!"); } }