コード例 #1
0
        public async Task StartAsync()
        {
            config = new DiscordSocketConfig()
            {
                MessageCacheSize = 1000000
            };                                        // initialize the config for the client, and set the message cache size
            Client = new DiscordSocketClient(config); // get the client with the configurations we want

            // Managers
            userDataManager = new UserDataManager(); // This sets up the user data files and loads them into memory
            fileManager     = new FileManager();     // initialize the file manager

            // Initialize Handlers
            _commands = new CommandHandler(Client);
            _logs     = new LogHandler();
            _reaction = new ReactionHandler(Client);
            _general  = new GeneralHandler(Client);

            Client.Ready += OnReady;   // Add the OnReady event

            BotUtils.SaveReady = true; // Tell the class that the autosave loop should start
            BotUtils.GCReady   = true;

            StartThreads();

            await Client.LoginAsync(TokenType.Bot, GetToken());

            await Client.StartAsync();

            KLog.Important("Logged in!");

            await Task.Delay(-1);  // Stop this method from exiting.
        }
コード例 #2
0
        public void updateTiers(List <string> IDS)
        {
            List <string> updates = new List <string>();

            foreach (string triumID in IDS)
            {
                string triumName = "";
                int    atomID    = 1;
                int    tID       = ReactionHandler.getInfo(triumID, out triumName, out atomID);
                Trium  t         = (Trium)bp[tID];
                bool   inc       = t.increaseTier();
                if (inc)
                {
                    updates.Add(t.getName());
                }
            }

            if (updates.Count == 1)
            {
                Notification.notify("You unlocked a new fact for " + updates[0] + ".", 4);
            }
            else if (updates.Count == 2)
            {
                Notification.notify("You unlocked new facts for " + updates[0] + " and " + updates[1] + ".", 5);
            }
        }
コード例 #3
0
ファイル: UI.cs プロジェクト: Eivlisskiv/Discord_Zihativa
        public async Task Click2(SocketReaction reaction, IUserMessage msg)
        {
            string emote = reaction.Emote.ToString();

            if (emote == help)
            {
                await AllHelp(reaction, msg);
            }
            else if (type != MsgType.SpecSelection && ArrayM.IsInArray(emote, specs))
            {
                await player.Specialization.MainMenu(player, reaction.Channel);
            }
            else if (options.Contains(emote))
            {
                string function = type.ToString();
                try
                {
                    await reflectionCache.Run <Task>(function, this, reaction, msg);
                }
                catch (Exception e)
                {
                    if (!await NeitsilliaError.SpecialExceptions(e, reaction.Channel, player))
                    {
                        ReactionHandler.LogReactionError(this, e, reaction.Emote, msg.Channel);
                    }
                }
            }
        }
コード例 #4
0
        private async Task RemRoleEmote(SocketRole role)
        {
            List <string> roleKeys = new List <string>();

            foreach (KeyValuePair <string, ulong> kvp in ReactionHandler.RoleMap)
            {
                if (kvp.Value == role.Id)
                {
                    // Add the role for removal with each reaction attached to it
                    roleKeys.Add(kvp.Key);
                }
            }

            // Remove the role
            for (int i = 0; i < roleKeys.Count; i++)
            {
                ReactionHandler.RoleMap.Remove(roleKeys[i]);
            }
            ReactionHandler.SaveRoleMap();

            if (roleKeys.Count == 0)
            {
                await ReplyAsync(BotUtils.KamtroText("That role has no emote attached to it!"));
            }
            else
            {
                await UpdateRoleMessage();
                await ReplyAsync(BotUtils.KamtroText("Role emote association removed."));
            }
        }
コード例 #5
0
        public async Task ReloadConfigAsync()
        {
            if (!ServerData.HasPermissionLevel(BotUtils.GetGUser(Context), ServerData.PermissionLevel.ADMIN))
            {
                return;                                                                                                // This is an admin only command
            }
            Program.ReloadConfig();
            ReactionHandler.SetupRoleMap();

            await ReplyAsync(BotUtils.KamtroText("Settings Reloaded."));
        }
コード例 #6
0
 internal static void OpportunityAttack(this Charakter charakter, Charakter target)
 {
     if (ReactionHandler.CheckForOpportunityAttack(charakter))
     {
         if (checkForHit(charakter, target.ArmourClass))
         {
             Actions.DealDamage(charakter, target, charakter.Damage);
         }
         else
         {
             Console.WriteLine(String.Format("{0} missed with his attack.", charakter.Name));
         }
     }
 }
コード例 #7
0
        public async Task PrepareAsync()
        {
            _serviceControlManager = new ServiceControlManager(_type);
            _reactionHandler       = new ReactionHandler();
            _antiMessageSpam       = new AntiSpam(SpamType.Message);
            _antiReactionSpam      = new AntiSpam(SpamType.Reaction);

            _client.ReactionAdded   += OnReactionAdditionAsync;
            _client.ReactionRemoved += OnReactionRemoving;
            _client.Connected       += OnConnection;
            _client.Disconnected    += OnDisconnection;
            _client.UserJoined      += OnUserJoining;
            _client.MessageReceived += OnMessageReceivingAsync;

            await _client.SetGameAsync("ANBOTIP Group");
        }
コード例 #8
0
        // Update is called once per frame
        void Update()
        {
            buddies.Clear();
            buddies    = new List <GameObject>(GameObject.FindGameObjectsWithTag("Buddy"));
            numBuddies = buddies.Count;
            if (inFusion)
            {
                FusionHandler f = new FusionHandler();
                //Debug.Log(getSelected().Count);
                bool done = f.fuse(getSelected());
                inFusion = false;
                deselectAll();
                makeBuddiesSelectable(false);
            }
            if (inGrouping)
            {
                // Grouping will just use the ReactionHandler method reactCurrent since it takes the same parameters
                ReactionHandler.reactCurrent(getSelected(), reactants, reactantCount, products, productCount);
                inGrouping = false;
                deselectAll();
                makeBuddiesSelectable(false);
            }
            if (inReaction)
            {
                //List<string> reactants = new List<string> { "H2", "O" };
                //List<string>
                ReactionHandler.reactCurrent(getSelected(), reactants, reactantCount, products, productCount);
                inReaction = false;
                deselectAll();
                makeBuddiesSelectable(false);

                /*
                 * bool done = ReactionHandler.reactCurrent(getSelected(), new List<string>() { "H2", "O" }, new List<int>() { 1, 1 }, new List<string>() { "H2O" }, new List<int>() { 1 });
                 * if (done)
                 * {
                 *  deselectAll();
                 *  makeBuddiesSelectable(false);
                 *  inReaction = false;
                 * }
                 */

                //Debug.Log("DONE : "+done);
            }
            //space.color = color;
            //rim.color = rimColor;
        }
コード例 #9
0
ファイル: Program.cs プロジェクト: Not-Solid/VJEmmy_v2
        private async Task MainAsync()
        {
            BotRegistry.FillRegistry();
            GuildRegistry.FillRegistry();

            _client = new DiscordSocketClient();

            await InitHandler.HandleInit(_client);

            var commandConfig = new CommandServiceConfig {
                DefaultRunMode = RunMode.Async
            };
            var commandHandler = new CommandHandler(_client, new CommandService(commandConfig));
            await commandHandler.InstallCommandsAsync();

            var reactionHandler = new ReactionHandler();

            reactionHandler.HandleReactions(_client);

            await Task.Delay(-1);
        }
コード例 #10
0
ファイル: Bullet.cs プロジェクト: Sychqh/ChemicalDungeon
    void Start()
    {
        Physics2D.IgnoreCollision(GameObject.Find("Player").GetComponent <BoxCollider2D>(), GetComponent <PolygonCollider2D>());
        spr        = GetComponent <SpriteRenderer>();
        spr.color  = Substance.Color;
        spr.sprite = Substance.AggrState switch
        {
            "Liquid" => liquidSpr,
            "Solid" => solidSpr,
            "Gas" => gasSpr,
            _ => throw new System.ArgumentException("The chosen aggregate state doesn't have a sprite: " + Substance.AggrState)
        };

        text = transform.GetChild(0).gameObject;
        text.GetComponent <TextMesh>().text = Substance.Formula;

        reactionHandler = GameObject.Find("ReactionHandler").GetComponent <ReactionHandler>();
    }

    void Update()
    {
    }
}
コード例 #11
0
        public async Task <bool> RunAsync()
        {
            if (_firstStart)
            {
                Log.Setup(true, false);
                Log.Info("Starting Ditto...");
            }

            // Try to load the settings from the XML file.
            // Should this not exist, it will automatically create one.
            try
            {
                Settings = await SettingsConfiguration.ReadAsync("data/settings.xml");

                // Write the settings again to update it with any new properties that might have been added.
                await Settings.WriteAsync("data/settings.xml").ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Log.Fatal(ex);
                return(false);
            }

            // Try to initialize the database
            try
            {
                (Database = new DatabaseHandler()).Setup(Settings.Credentials.Sql.Type, Settings.Credentials.Sql.ConnectionString);
            }
            catch (Exception ex)
            {
                Log.Fatal("Unable to create a connection with the database, please check the file \"/data/settings.xml\"", ex);
                return(false);
            }

            // Try to initialise the service 'Google'
            try
            {
                await(Google = new GoogleService()).SetupAsync(Settings.Credentials.GoogleApiKey).ConfigureAwait(false);
            }
            catch (Exception ex)
            {
                Log.Error("Could not initialize Google {0}\n", ex.ToString());
            }

            // Try to initialise 'Giphy'
            try
            {
                Giphy = new Giphy(Settings.Credentials.GiphyApiKey);
            }
            catch (ApiException ex)
            {
                Log.Warn("Could not initialize Giphy {0}\n", ex.ToString());
            }

            // Try to initialise 'Twitch'
            try
            {
                Twitch = new TwitchLib.Api.TwitchAPI();
                Twitch.Settings.ClientId = Settings.Credentials.TwitchApiClientId;
                Twitch.Settings.Secret   = Settings.Credentials.TwitchApiSecret;
                var twitchResult = await Twitch.V5.Auth.CheckCredentialsAsync().ConfigureAwait(false);

                if (Twitch.Settings.ClientId == null || !twitchResult.Result)
                {
                    Twitch = null;
                    throw new ApiException("Twitch credentials check failed.");
                }
            }
            catch (Exception ex)
            {
                Log.Warn("Could not initialize Twitch {0}\n", ex.ToString());
            }

            // Create our discord client
            Client?.Dispose();
            Client = new ObjectLock <DiscordClientEx>(new DiscordClientEx(new DiscordSocketConfig()
            {
                MessageCacheSize = Settings.Cache.AmountOfCachedMessages,
                LogLevel         = LogSeverity.Warning,
                //TotalShards = 1,
                ConnectionTimeout = (int)(Settings.Timeout * 60),
                HandlerTimeout    = (int)(Settings.Timeout * 60),
                DefaultRetryMode  = RetryMode.AlwaysRetry,
                //AlwaysDownloadUsers = true,
            }), 1, 1);

            // Various services
            if (Cache == null)
            {
                (Cache = new CacheHandler()).Setup(TimeSpan.FromSeconds(Settings.Cache.CacheTime));
            }
            CommandHandler?.Dispose();
            await(CommandHandler = new CommandHandler(Client)).SetupAsync().ConfigureAwait(false);


            await Client.DoAsync((client)
                                 => client.Connected += async() =>
            {
                // Setup services
                await CommandHandler.SetupAsync().ConfigureAwait(false);
                ReactionHandler?.Dispose();
                await(ReactionHandler = new ReactionHandler()).SetupAsync(Client).ConfigureAwait(false);
                PlayingStatusHandler.Setup(TimeSpan.FromMinutes(1));
            }
                                 ).ConfigureAwait(false);

            if (_firstStart)
            {
                Connected += async() =>
                {
                    // Start services
                    await CommandHandler.StartAsync().ConfigureAwait(false);

                    PlayingStatusHandler.Start();

                    Connected -= Initialised;
                };

                // Call this once after a successful connection.
                Connected += Initialised;
            }

            await Client.DoAsync((client)
                                 => client.Ready += async() =>
            {
                if (!Running)
                {
                    Running = true;
                    await Connected().ConfigureAwait(false);
                }
                Log.Info("Connected");

                if (Type == BotType.Bot)
                {
                    await client.SetGameAsync(null);
                    await client.SetStatusAsync(UserStatusEx.Online);
                }
            }
                                 ).ConfigureAwait(false);

            await Client.DoAsync((client)
                                 => client.Disconnected += (e) =>
            {
                if (Reconnecting)
                {
                    //_reconnecting = false;
                }
                else
                {
                    Log.Warn("Bot has been disconnected. {0}", (object)(Exiting ? null : $"| {e}"));
                    if (!Exiting && Settings.AutoReconnect && !Reconnecting)
                    {
                        var _ = Task.Run(() => ReconnectAsync());
                    }
                }
                return(Task.CompletedTask);
            }
                                 ).ConfigureAwait(false);

            await Client.DoAsync((client)
                                 => client.LoggedOut += () =>
            {
                Log.Warn("Bot has logged out.");
                if (!Exiting && Settings.AutoReconnect && !Reconnecting)
                {
                    var _ = Task.Run(() => ReconnectAsync());
                }
                return(Task.CompletedTask);
            }
                                 ).ConfigureAwait(false);

            var autoReconnect = Settings.AutoReconnect;

            Settings.AutoReconnect = false;
            try
            {
                await LoginAsync().ConfigureAwait(false);

                Settings.AutoReconnect = autoReconnect;
            }
            catch (Exception ex)
            {
                Log.Fatal("Failed to login, please check your internet connection and bot token.", ex);
                return(false);
            }
            await Client.DoAsync((c) => c.StartAsync()).ConfigureAwait(false);

            _firstStart = false;
            return(true);
        }
コード例 #12
0
        public override async Task PerformAction(SocketReaction option)
        {
            string opt = option.Emote.ToString();

            switch (opt)
            {
            case ReactionHandler.CHECK_STR:
                if (Emote == BotUtils.ZeroSpace || Emote == EmptyOrInvalidEmote)
                {
                    Emote = EmptyOrInvalidEmote;
                    await UpdateEmbed();

                    return;
                }

                if (ReactionHandler.RoleMap.ContainsKey(Emote))
                {
                    if (ServerData.Server.GetRole(ReactionHandler.RoleMap[Emote]) == null)
                    {
                        ulong id = ReactionHandler.RoleMap[Emote];

                        ReactionHandler.RoleMap.Remove(Emote);
                        ReactionHandler.SaveRoleMap();

                        EventQueueManager.RemoveEvent(this);
                        await ReactionHandler.CloseActionEmbedAsync(this);

                        await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Something went wrong! Please use the command again!"));

                        KLog.Info($"[REE] Role was null! ID: {id}");
                        return;
                    }

                    Emote = $"The role {ServerData.Server.GetRole(ReactionHandler.RoleMap[Emote]).Mention} already has that emote!";
                    await UpdateEmbed();

                    break;
                }

                if (ServerData.Server.GetRole(Role.Id) == null)
                {
                    ulong id = ReactionHandler.RoleMap[Emote];

                    EventQueueManager.RemoveEvent(this);
                    await ReactionHandler.CloseActionEmbedAsync(this);

                    await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Something went wrong! Please use the command again!"));

                    KLog.Info($"[REE] Role was null! ID: {id}");
                    return;
                }

                ReactionHandler.RoleMap.Add(Emote, Role.Id);
                ReactionHandler.SaveRoleMap();

                await GeneralHandler.UpdateRoleMessage();

                EventQueueManager.RemoveEvent(this);
                await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Emote Association Added."));

                await Message.DeleteAsync();

                break;

            case ReactionHandler.DECLINE_STR:
                EventQueueManager.RemoveEvent(this);
                await Context.Channel.SendMessageAsync(BotUtils.KamtroText("Action Canceled."));

                await Message.DeleteAsync();

                break;

            default:
                Emote = option.Emote.ToString();
                await UpdateEmbed();

                break;
            }
        }
コード例 #13
0
ファイル: CallbackReaction.cs プロジェクト: dsisco11/CssUI
 public ReactionCallback(ReactionHandler Callback, params object[] Args)
 {
     this.Callback = Callback;
     this.Args     = Args;
 }