private async Task <ulong> LodgeTransactionTask(DataBaseHandlingService db, CommandHandlingService CommandService, StockMarketService marketService, int hours, int mins)
        {
            EmbedFieldBuilder typeField    = new EmbedFieldBuilder().WithIsInline(true).WithName("Type:").WithValue($"Industry Auction");
            EmbedFieldBuilder companyField = new EmbedFieldBuilder().WithIsInline(true).WithName("ID:").WithValue(industryID);
            EmbedFieldBuilder amountField  = new EmbedFieldBuilder().WithIsInline(true).WithName("Type:").WithValue((string)await db.GetFieldAsync(industryID, "Type", "industries"));
            EmbedFieldBuilder priceField   = new EmbedFieldBuilder().WithIsInline(true).WithName("Price:").WithValue("$" + price);

            EmbedBuilder emb = new EmbedBuilder().WithTitle("Stock Market Offer").WithDescription($"Use the command `&bid [ticker] {id.ToString()} [price]` to accept this offer.").WithFooter($"Transaction ID: {id.ToString()}").AddField(typeField).AddField(companyField).AddField(amountField).AddField(priceField).WithColor(Color.Green);

            Discord.Rest.RestUserMessage message = await CommandService.PostEmbedTask((string)await db.GetFieldAsync("MarketChannel", "channel", "system"), emb.Build());

            DateTime now       = DateTime.UtcNow;
            DateTime scheduled = now.AddHours(hours).AddMinutes(mins);

            plannedEnd = scheduled;
            JobDataMap map = new JobDataMap();

            map.Add("market", marketService);
            map.Add("auction", this);
            map.Add("command", CommandService);
            map.Add("db", db);
            IJobDetail job     = JobBuilder.Create <Job>().SetJobData(map).Build();
            ITrigger   trigger = TriggerBuilder.Create().WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromMilliseconds(1)).WithRepeatCount(1)).StartAt(plannedEnd).Build();
            await CommandService.scheduler.ScheduleJob(job, trigger);

            return(message.Id);
        }
예제 #2
0
        public TipBot(
            IOptionsMonitor <TipBotSettings> options,
            IServiceProvider services,
            DiscordSocketClient client,
            INodeIntegration nodeIntegration,
            QuizExpiryChecker quizExpiryChecker,
            CommandService commandService,
            DiscordConnectionKeepAlive discordConnectionKeepAlive,
            CommandHandlingService commandHandlingService,
            FatalErrorNotifier fatalErrorNotifier
            )
        {
            this.settings                   = options.CurrentValue;
            this.services                   = services;
            this.client                     = client;
            this.nodeIntegration            = nodeIntegration;
            this.quizExpiryChecker          = quizExpiryChecker;
            this.commandService             = commandService;
            this.discordConnectionKeepAlive = discordConnectionKeepAlive;
            this.commandHandlingService     = commandHandlingService;
            this.fatalErrorNotifier         = fatalErrorNotifier;

            options.OnChange(config =>
            {
                this.settings = config;
            });
        }
        public async Task schedule(DataBaseHandlingService db, CommandHandlingService CommandService, StockMarketService marketService)
        {
            if (plannedEnd.Ticks <= DateTime.Now.Ticks)
            {
                Industry ind = new Industry(await db.getJObjectAsync(this.industryID, "industries"));
                ind.CompanyId = this.currentWinner;
                await db.SetJObjectAsync(ind.SerializeIntoJObject(), "industries");

                await db.RemoveObjectAsync(this.id, "transactions");

                string markchan = (string)await db.GetFieldAsync("MarketChannel", "channel", "system");

                await CommandService.deleteMessageTask(markchan, this.messageID);

                await CommandService.PostMessageTask(markchan, $"Auction with ID {this.id} has been won by <@{(string)await db.GetFieldAsync(this.currentWinner, "name", "companies")}>!");

                return;
            }
            JobDataMap map = new JobDataMap();

            map.Add("market", marketService);
            map.Add("auction", this);
            map.Add("command", CommandService);
            map.Add("db", db);
            IJobDetail job     = JobBuilder.Create <Job>().SetJobData(map).Build();
            ITrigger   trigger = TriggerBuilder.Create().WithSimpleSchedule(x => x.WithInterval(TimeSpan.FromMilliseconds(1)).WithRepeatCount(1)).StartAt(plannedEnd).Build();
            await CommandService.scheduler.ScheduleJob(job, trigger);
        }
예제 #4
0
        private async Task <bool> isWin(long game, Summoner tocheck)
        {
            await CommandHandlingService.Logger(new LogMessage(LogSeverity.Debug, "isWin Check", $"GameID:{game}, PlayerACC:{tocheck.AccountId}, Name:{tocheck.Name}"));

            Match match = await _rapi.RAPI.MatchV4.GetMatchAsync(Region.NA, game);

            int playerId     = -1;
            int playerTeam   = -1;
            int playerTeamId = -1;

            foreach (var part in match.ParticipantIdentities)
            {
                if (part.Player.CurrentAccountId == tocheck.AccountId)
                {
                    playerId     = part.ParticipantId - 1;
                    playerTeamId = match.Participants[playerId].TeamId;
                    playerTeam   = (playerTeamId == 100) ? 0 : 1;
                    break;
                }
            }
            if (match.Teams[playerTeam].TeamId != playerTeamId)
            {
                throw new IndexOutOfRangeException($"TeamId found:{playerTeamId}, Team index made:{playerTeam}, TeamId in index reached:{match.Teams[playerTeam].TeamId}");
            }
            //await CommandHandlingService.Logger(new LogMessage(LogSeverity.Debug, "isWinCheck", $"{match.Teams[playerTeam].Win == "Win"}"));
            return(match.Teams[playerTeam].Win == "Win");
        }
            public async Task Execute(IJobExecutionContext context)
            {
                /*Industry ind = new Industry(await db.getJObjectAsync(auction.industryID, "industries"));
                 * ind.CompanyId = auction.currentWinner;
                 * await db.SetJObjectAsync(ind.SerializeIntoJObject(), "industries");
                 * string markchan = (string)await db.GetFieldAsync("MarketChannel", "channel", "system");
                 *
                 * await comm.deleteMessageTask(markchan, auction.messageID);
                 *
                 * await comm.PostMessageTask(markchan, $"Auction with ID {auction.id} has been accepted by <@{(string)await db.GetFieldAsync(auction.currentWinner, "name", "companies")}>!");
                 * await db.RemoveObjectAsync(auction.id, "transactions");*/
                IndustryAuction         auction = (IndustryAuction)context.JobDetail.JobDataMap.Get("auction");
                StockMarketService      market  = (StockMarketService)context.JobDetail.JobDataMap.Get("market");
                CommandHandlingService  comm    = (CommandHandlingService)context.JobDetail.JobDataMap.Get("command");
                DataBaseHandlingService db      = (DataBaseHandlingService)context.JobDetail.JobDataMap.Get("db");

                auction = new IndustryAuction(await db.getJObjectAsync(auction.id, "transactions"));
                Industry ind = new Industry(await db.getJObjectAsync(auction.industryID, "industries"));

                ind.CompanyId = auction.currentWinner;
                await db.SetJObjectAsync(ind.SerializeIntoJObject(), "industries");

                await db.RemoveObjectAsync(auction.id, "transactions");

                string markchan = (string)await db.GetFieldAsync("MarketChannel", "channel", "system");

                await comm.deleteMessageTask(markchan, auction.messageID);

                await comm.PostMessageTask(markchan, $"Auction with ID {auction.id} has been accepted by {(string)await db.GetFieldAsync(auction.currentWinner, "name", "companies")}!");
            }
예제 #6
0
        public OwnerModule(CommandHandlingService _handler, UserGuildUpdateService service, StarBoardService starboards,
                           EPService _epService, AnimeService aniSer)
        {
            handler          = _handler;
            updateService    = service;
            starBoardService = starboards;
            epService        = _epService;
            _aniServ         = aniSer;

            /* //TODO FIX THIS SHIT UP
             * configDict = ConfigService.getConfig();
             *
             #if DEBUG
             * if (!configDict.TryGetValue("token2", out _token))
             * {
             *  throw new Exception("FAILED TO GET TOKEN2");
             * }
             * else
             * {
             *  Console.WriteLine("GOT DEBUG TOKEN");
             * }
             #else
             * if (!configDict.TryGetValue("token1", out _token))
             * {
             *  throw new Exception("FAILED TO GET TOKEN1");
             * }
             #endif
             */
        }
예제 #7
0
        public RingFitModule(DatabaseService dbService, IConfiguration config, CommandHandlingService chService, DiscordSocketClient dsc, IScheduler scheduler)
        {
            _dbService = dbService;
            _config    = config;
            _scheduler = scheduler;

            _linkPepeHypeCode = _config["Emotes:LinkPepeHype"];
            _marioYayCode     = _config["Emotes:MarioYay"];
            _sonicDabCode     = _config["Emotes:SonicDab"];
            _samusCode        = _config["Emotes:Samus"];
            _linkRageCode     = _config["Emotes:LinkRage"];

            _allowedAuthorIds = _config.GetSection("RingFit:ApprovedAuthorIds").Get <ulong[]>();
            _ringFitChannelId = Convert.ToUInt64(_config["RingFit:ChannelId"]);
            _ringFitChannel   = dsc.GetGuild(Convert.ToUInt64(_config["RingFit:GuildId"]))
                                .GetTextChannel(_ringFitChannelId);

            _minuteScoresMap = MapMinuteScores();
            _trackedReacts   = _minuteScoresMap.Keys.ToList();

            chService.ReactAdded      += OnReactAdded;
            chService.ReactRemoved    += OnReactRemoved;
            chService.MessageRemoved  += OnMessageRemoved;
            chService.MessageReceived += OnMessageReceived;

            ScheduleJobs();
        }
예제 #8
0
        public async Task MainAsync()
        {
            using (StreamReader tfile = File.OpenText("config.json")){
                dynamic config     = JsonConvert.DeserializeObject(tfile.ReadToEnd());
                char    tempPrefix = config.prefix ?? '`';
                int     tempLevel  = config.logLevel ?? 3;

                CLIENT_ID     = config.clientId ?? "NONE";
                CLIENT_SECRET = config.clientSecret ?? "NONE";
                RKEY          = config.riotKey ?? throw (new ArgumentNullException("No Riot API Key (riotKey in config file) given!"));
                BOT_TOKEN     = config.botToken ?? throw (new ArgumentNullException("No Discord Bot token (botKey in config file) given!"));
                CommandHandlingService.setLog(tempLevel);
                CommandHandlingService.setPrefix(tempPrefix);
            }
            await CommandHandlingService.Logger(new LogMessage(LogSeverity.Info, "Config", $"Prefix set to:'{CommandHandlingService.Prefix}'"));

            using (var services = ConfigServices()){
                main_client = services.GetRequiredService <DiscordSocketClient>();
                services.GetRequiredService <CommandService>().Log += Logger;
                rapi = services.GetRequiredService <RapiInfo>();

                main_client.Log += Logger;
                await main_client.LoginAsync(TokenType.Bot, BOT_TOKEN);

                await main_client.StartAsync();

                await services.GetRequiredService <Services.CommandHandlingService>().InitializeAsync();

                await Task.Delay(-1);
            }
        }
예제 #9
0
        private bool IsValidMessage(IMessage m, bool checkReactions = true)
        {
            if (!(m is IUserMessage msg))
            {
                return(false);
            }
            if (msg.Author.IsBot || msg.Author.IsWebhook)
            {
                return(false);
            }
            if (msg.Embeds.Count < 1 && msg.Attachments.Count < 1)
            {
                return(false);
            }
            CommandHandlingService commands = this.ServiceManager.GetService <CommandHandlingService>("Commands");

            if (commands.IsCommandMessage(msg))
            {
                return(false);
            }
            if (checkReactions && ((msg.Reactions.TryGetValue(Emote, out ReactionMetadata data) && !data.IsMe) || !msg.Reactions.ContainsKey(Emote)))
            {
                return(false);
            }

            return(true);
        }
예제 #10
0
 public ResourceCommands(CompanyService com, DataBaseHandlingService db, CommandHandlingService comm, StockMarketService markserv, ResourceHandlingService res)
 {
     _companyService          = com;
     _dataBaseService         = db;
     _commandService          = comm;
     _marketService           = markserv;
     _resourceHandlingService = res;
 }
예제 #11
0
 public IndustryCommands(IndustryService ind, CompanyService com, DataBaseHandlingService db, CommandHandlingService comm, StockMarketService markserv)
 {
     _companyService  = com;
     _dataBaseService = db;
     _commandService  = comm;
     _marketService   = markserv;
     _industryService = ind;
 }
        public async Task StartInventoryStateMachine()
        {
            await Context.Channel.TriggerTypingAsync();

            InventoryAccessStateMachine state = new InventoryAccessStateMachine(Context.User.Id);

            CommandHandlingService.AddToStateMachines(state, Context);
        }
예제 #13
0
 public CommandRefreshWorker(ILogger <CommandRefreshWorker> logger,
                             DiscordSocketClient client,
                             CommandHandlingService commandHandlingService,
                             IOptions <CommandsSettings> commandsSettings)
 {
     _logger = logger;
     _client = client;
     _commandHandlingService = commandHandlingService;
     _commandsSettings       = commandsSettings.Value;
 }
예제 #14
0
        public async Task HideAsync([Remainder] string command)
        {
            var context = new ShadeContext(Context.Me, Context.Message, Context.Client, Context.Services);

            context.SetAnswerType(AnswerType.None);

            var result = await CommandService.ExecuteAsync(context, command, Context.Services);

            _ = CommandHandlingService.HandleCommandResult(context, result);
        }
예제 #15
0
        public TicketModule(Settings.Deserialized.Settings settings, CommandHandlingService commandHandlingService)
        {
            _settings = settings;

            Task.Run(async() =>
            {
                var commands = await commandHandlingService.GetCommandList("TicketModule", true, true, false);
                _commandList = commands.MessageSplitToSize();
            });
        }
예제 #16
0
        public PaprikaFilterModule(IConfigurationService configService, CommandHandlingService chService, IDiscordClient discordClient)
        {
            _discordClient = discordClient;
            _config        = configService.Configuration;

            chService.MessageReceived += MessageReceivedAsync;
            chService.MessageUpdated  += MessageUpdatedAsync;

            LinkRageEmote = Emote.Parse(_config["Emotes:GooseHonkKnife"]);
        }
예제 #17
0
        public HamagenModule(IConfigurationService configService, CommandHandlingService chService)
        {
            _config        = configService.Configuration;
            _hamagenUserId = _config["UserIds:Hamagen"];
            _hamagenEmote  = Emote.Parse(_config["Emotes:CallHamagen"]);
            var whiteCheckmark = new Emoji(_config["Emojis:WhiteCheckmark"]);

            _baseWarnMessageModule = new BaseWarnMessageModule(configService, whiteCheckmark);

            chService.ReactAdded += ReactionAddedAsync;
        }
예제 #18
0
        public async Task <string> DeleteTaskAsync(CommandHandlingService commandService, ulong id, int count)
        {
            string reply = "";
            await Task.Run(async() =>
            {
                int deleteCounter     = 0;
                ulong latestMessageId = 0;
                IMessage msgId        = await commandService.Message.Channel.GetMessageAsync(id);
                IReadOnlyCollection <IMessage> getLast100Messages = await commandService.Message.Channel.GetMessagesAsync().LastAsync();

                // Ensures that message length of numMsg is greater than 0, therefore ensures that the message exists
                if (msgId?.Content.Length > 0)
                {
                    do
                    {
                        // Automagically gets the latest message from the channel and deletes it
                        latestMessageId = getLast100Messages.ElementAt(deleteCounter).Id;
                        await getLast100Messages.ElementAt(deleteCounter).DeleteAsync();
                        Thread.Sleep(500);
                        deleteCounter++;
                    } while (latestMessageId != id);

                    reply = $"Successfully deleted {deleteCounter} messages.";
                }
                else
                {
                    foreach (IMessage msg in getLast100Messages)
                    {
                        ulong authorId  = msg.Author.Id;
                        ulong resultMsg = msg.Id;

                        if (authorId.Equals(id))
                        {
                            await commandService.Message.Channel.DeleteMessageAsync(resultMsg);
                            Thread.Sleep(500);
                            deleteCounter++;
                        }
                        if (count.Equals(deleteCounter))
                        {
                            // Counter is still by 1 short because it iterates from 0
                            deleteCounter++;
                            break;
                        }
                    }
                    reply = $"Successfully deleted {deleteCounter + 1} messages.";
                }
                if (deleteCounter == 0)
                {
                    reply = "0 messages deleted. Have you entered a valid message/user ID?";
                }
            });

            return(reply);
        }
예제 #19
0
        public CompanyCommands(CompanyService com, DataBaseHandlingService db, CommandHandlingService comm, StockMarketService markserv)
        {
            CompanyService  = com;
            dataBaseService = db;
            CommandService  = comm;
            MarketService   = markserv;
            guild           = ulong.Parse(Resources.guild);
#if DEBUG
            guild = ulong.Parse(Resources.devguild);
#endif
        }
예제 #20
0
        public JaraSoukupModule(IConfigurationService configService, CommandHandlingService chService)
        {
            _config           = configService.Configuration;
            _jaraSoukupUserId = _config["UserIds:JaraSoukup"];
            _rabbit2Emoji     = new Emoji(_config["Emojis:Rabbit2"]);
            var blueCheckmark = new Emoji(_config["Emojis:BlueCheckmark"]);

            _baseWarnMessageModule = new BaseWarnMessageModule(configService, blueCheckmark);

            chService.ReactAdded += ReactionAddedAsync;
        }
예제 #21
0
 public BotStartup(IServiceProvider serviceProvider,
                   DiscordSocketClient discordSocketClient,
                   CommandService commandService,
                   LoggingService loggingService,
                   CommandHandlingService commandHandlingService)
 {
     _serviceProvider        = serviceProvider;
     _discordSocketClient    = discordSocketClient;
     _commandService         = commandService;
     _loggingService         = loggingService;
     _commandHandlingService = commandHandlingService;
 }
예제 #22
0
        public async Task Prefix([Remainder] string Prefix)
        {
            var guild = CommandHandlingService.GetOrCreateServer(Context.Guild.Id);

            guild.Prefix = Prefix[0].ToString();

            var col = Database.GetCollection <Server>("Servers");

            col.Update(guild);

            await ReplyAsync(Context.User.Mention + ", Changed prefix for this server to `" + guild.Prefix + "`.");
        }
예제 #23
0
 public async Task TestCombatStarterCommand()
 {
     try
     {
         TestCombatLevel level = new TestCombatLevel(Context, Context.User.Id);
         CommandHandlingService.AddToStateMachines(level, Context);
     }
     catch (Exception ex)
     {
         await ReplyAsync(ex.Message + " " + ex.StackTrace);
     }
 }
        public async Task PressPlusToStart()
        {
            if (Program.game.PlayerDict.ContainsKey(Context.User.Id))
            {
                await Context.Channel.SendMessageAsync($"A Player Account has already created. If you would like to start over please use {CommandHandlingService.GetGuildPrefix(Context)}resetaccount");

                return;
            }
            PlayerCreationStateMachine state = new PlayerCreationStateMachine(Context.User.Id);

            CommandHandlingService.AddToStateMachines(state, Context);
        }
예제 #25
0
 public BotService(
     DiscordSocketClient discorClient,
     CommandHandlingService commandHandlingService,
     CommandService commandService,
     IOptions <BotOptions> botOptions,
     ILogger <BotService> logger)
 {
     _commandHandlingService = commandHandlingService;
     _commandService         = commandService;
     _discordClient          = discorClient;
     _botOptions             = botOptions;
     _logger = logger;
 }
예제 #26
0
        public async Task ExecuteAsync(IUser user, [Remainder] string command)
        {
            var fakeContext = new ShadeContext(Context.Me, Context.Message, Context.Client, Context.Services);

            fakeContext.OverrideUser(user);
            fakeContext.OverridePermissionsUser(Context.User as IGuildUser);

            var result = await CommandHandlingService.CommandService.ExecuteAsync(fakeContext, command, Services);

            await Context.Message.AddReactionAsync(new Emoji("\u2705"));

            _ = CommandHandlingService.HandleCommandResult(fakeContext, result);
        }
        private async Task <ulong> LodgeTransactionTask(DataBaseHandlingService db, CommandHandlingService CommandService)
        {
            EmbedFieldBuilder typeField    = new EmbedFieldBuilder().WithIsInline(true).WithName("Type:").WithValue($"Looking to {type} industry");
            EmbedFieldBuilder companyField = new EmbedFieldBuilder().WithIsInline(true).WithName("ID:").WithValue(industryID);
            EmbedFieldBuilder amountField  = new EmbedFieldBuilder().WithIsInline(true).WithName("Type:").WithValue(db.GetFieldAsync(industryID, "type", "industry").ToString());
            EmbedFieldBuilder priceField   = new EmbedFieldBuilder().WithIsInline(true).WithName("Price:").WithValue("$" + price);

            EmbedBuilder emb = new EmbedBuilder().WithTitle("Stock Market Offer").WithDescription($"Use the command `&accept {id.ToString()}` to accept this offer.").WithFooter($"Transaction ID: {id.ToString()}").AddField(typeField).AddField(companyField).AddField(amountField).AddField(priceField).WithColor(Color.Green);

            Discord.Rest.RestUserMessage message = await CommandService.PostEmbedTask((string)await db.GetFieldAsync("MarketChannel", "channel", "system"), emb.Build());

            return(message.Id);
        }
 public DiscordServerHostedService(IApplicationEnder applicationEnder,
                                   ILogger <DiscordServerHostedService> logger,
                                   AppOptions options,
                                   DiscordSocketClient discordClient,
                                   CommandService commandService,
                                   CommandHandlingService commandHandlingService) : base(applicationEnder)
 {
     _logger                 = logger;
     _options                = options;
     _discordClient          = discordClient;
     _commandService         = commandService;
     _commandHandlingService = commandHandlingService;
 }
예제 #29
0
        private CommandInformation OnCommandsRequested(RemoteProcess proc, object _)
        {
            this.Log($"Sent command information to process \'{proc}\'");

            CommandHandlingService commandService = this.ServiceManager.GetService <CommandHandlingService>("Commands");

            return(new CommandInformation
            {
                BotMention = this.DiscordClient.CurrentUser.ToString(),
                Prefix = this.Prefix,
                Commands = commandService.RegisteredCommands.ToList().Select(kv => Command.ToModel(kv.Value)).ToList()
            });
        }
예제 #30
0
        //private static string formatFullDate = "dd.MM.yyyy HH:mm:ss";

        public ListenFor1337(DiscordSocketClient client, CommandHandlingService command, bool devMode)
        {
            this._devMode = devMode;
            this._client  = client;
            this._command = command;
            this._command.AddAbonents(Message1337);

            if (!initPostDaylieStatsOnes)
            {
                this._client.GuildAvailable += PostDaylieStats;
                CopyTableEveryDay();
                LogMain("PostDaylieStats Inizialisiert", LogLevel.Debug);
            }
        }