Beispiel #1
0
        public async Task <bool> IsInRole(string role, IPalBot bot, Message msg)
        {
            if (Roles == null)
            {
                LoadRoles();
            }

            var roles = role.Split(',').Select(t => t.Trim().ToLower()).ToArray();

            foreach (var r in Roles)
            {
                if (!roles.Any(t => t == r.Name.ToLower().Trim()))
                {
                    continue;
                }

                if (msg.MesgType == MessageType.Group && !(await IsInGroupRole(r, bot, msg)))
                {
                    return(false);
                }

                if (msg.MesgType == MessageType.Private && !(await IsInPrivateRole(r, bot, msg)))
                {
                    return(false);
                }
            }

            return(true);
        }
Beispiel #2
0
 public static async Task <byte[]> GetBytes(this IPalBot bot, string url)
 {
     using (var client = new WebClient())
     {
         return(await client.DownloadDataTaskAsync(url));
     }
 }
Beispiel #3
0
        private async Task <bool> IsInGroupRole(IRole role, IPalBot bot, Message msg)
        {
            var group = bot.GetGroup(msg.ReturnAddress);

            if (group == null)
            {
                return(false);
            }

            var members = bot.GetGroupMembers(group.Id).ToArray();

            if (members == null)
            {
                return(false);
            }

            var gu = members.Where(t => t.Id == msg.UserId).FirstOrDefault();

            if (gu == null)
            {
                return(false);
            }

            if (!(await role.ValidateGm(bot, msg, group, gu)))
            {
                role.OnRejected(bot, msg);
                return(false);
            }

            return(true);
        }
Beispiel #4
0
        private string CheckCommand(IPalBot bot, ICommand cmd, Message message, string msg, out Message msgToUser)
        {
            msgToUser = message;
            if (!cmd.MessageType.HasFlag(message.MesgType))
            {
                return(null);
            }

            if (!string.IsNullOrEmpty(cmd.Grouping) &&
                bot.Groupings != null &&
                bot.Groupings.Length > 0 &&
                !bot.Groupings.Any(t =>
                                   t.ToLower().Trim() == cmd.Grouping.ToLower().Trim()))
            {
                return(null);
            }

            var comp = comparitors.FirstOrDefault(t => t.AttributeType == cmd.GetType());

            if (comp == null)
            {
                return(null);
            }


            if (comp.IsMatch(bot, message, msg, cmd, out string capped, out msgToUser))
            {
                return(capped.Trim());
            }

            return(null);
        }
Beispiel #5
0
        public void Process(IPalBot bot, IPacketMap pkt)
        {
            if (pkt is Message && bot.EnablePlugins)
            {
                var msg = (Message)pkt;
                ProcessMessage(bot, msg);
                broadcast.BroadcastMessage(bot, msg);
                return;
            }

            if (packets == null)
            {
                LoadPacketReflectors();
            }

            var reflected = packets.Where(t => t.Command == pkt.Command).ToArray();

            foreach (var reflect in reflected)
            {
                try
                {
                    reflect.Method.Invoke(reflect.Instance, new object[] { pkt, bot });
                }
                catch (Exception ex)
                {
                    broadcast.BroadcastException(ex, $"Error running packet watcher {reflect.Command}");
                }
            }
        }
Beispiel #6
0
        public bool IsMatch(IPalBot bot, Message msg, string cmd, ICommand atr, out string capped, out Message nm)
        {
            nm = msg;
            if (msg is LangMessage && !string.IsNullOrEmpty(((LangMessage)msg).LanguageKey))
            {
                return(IsMatchAlready(bot, (LangMessage)msg, cmd, atr, out capped));
            }

            capped = cmd;

            var localizations = bot.Languages.Storage.Get(atr.Comparitor);

            if (localizations.Length <= 0)
            {
                return(false);
            }

            var local = localizations.FirstOrDefault(t => cmd.ToLower().StartsWith(t.Text.ToLower()));

            if (local == null)
            {
                return(false);
            }

            nm     = new LangMessage(msg, local.LanguageKey);
            capped = cmd.Remove(0, local.Text.Length);
            return(true);
        }
Beispiel #7
0
        public static IPalBot UseConsoleLogging(this IPalBot bot, bool logUnhandled = false)
        {
            if (logUnhandled)
            {
                bot.On.UnhandledPacket += (p) =>
                                          Extensions.ColouredConsole($"^w[^g{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}^w] ^rUNHANDLED ^w{p.Command}");
            }

            bot.On.PacketReceived += (p) =>
                                     Extensions.ColouredConsole($"^w[^g{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}^w] ^c<< ^w{p.Command} - ^b{p.ContentLength}");

            bot.On.PacketSent += (p) =>
                                 Extensions.ColouredConsole($"^w[^g{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}^w] ^e>> ^w{p.Command} - ^b{p.ContentLength}");

            bot.On.Disconnected += () =>
                                   Extensions.ColouredConsole($"^w[^g{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}^w] ^yDisconnected..");

            bot.On.Exception += (e, n) =>
                                Extensions.ColouredConsole($"^w[^g{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}^w] ^rERROR {n} - {e.ToString()}");

            bot.On.LoginFailed += (b, r) =>
                                  Extensions.ColouredConsole($"^w[^g{DateTime.Now.ToString("yyyy-MM-dd HH:mm")}^w] ^rLogin Failed: {r.Reason}");

            return(bot);
        }
Beispiel #8
0
        [LCommand("plugin.command")] //This relates to the localization.lang file in the root of the CLI project
        public async void Test(IPalBot bot, LangMessage msg, string cmd)
        {
            await bot.Reply(msg, "plugin.response");

            //This is an example of how to use the parameters localization files.
            await bot.Reply(msg, "plugin.cant", (await bot.GetUser(msg.UserId)).Nickname, msg.LanguageKey);
        }
Beispiel #9
0
 public static IPalBot RemoveDouche(this IPalBot bot, params int[] ids)
 {
     foreach (var id in ids)
     {
         Plugins.Defaults.DoucheRole.Douches.Remove(id);
     }
     return(bot);
 }
Beispiel #10
0
 public static IPalBot RemoveAuth(this IPalBot bot, params int[] ids)
 {
     foreach (var id in ids)
     {
         Plugins.Defaults.AuthRole.AuthorizedUsers.Remove(id);
     }
     return(bot);
 }
Beispiel #11
0
        public static async Task <Bitmap> GetImage(this IPalBot bot, string url)
        {
            using (var client = new WebClient())
            {
                var data = await client.DownloadDataTaskAsync(url);

                return(data.ToBitmap());
            }
        }
Beispiel #12
0
        /// <summary>
        /// Called when attempting to authorize a private plugin call
        /// </summary>
        /// <param name="bot">The bot that was triggered</param>
        /// <param name="msg">The message that triggered the plugin</param>
        /// <param name="user">The user who triggered the plugin</param>
        /// <returns>Whether or not the user can activate the plugin</returns>
        public async Task <bool> ValidatePm(IPalBot bot, Message msg, User user)
        {
            var profile = await bot.GetUser(msg.UserId);

            if (profile.HasTag || profile.Premium)
            {
                return(true);
            }

            return(false);
        }
Beispiel #13
0
        private async Task <bool> IsInPrivateRole(IRole role, IPalBot bot, Message msg)
        {
            var user = await bot.GetUser(msg.UserId);

            if (!(await role.ValidatePm(bot, msg, user)))
            {
                role.OnRejected(bot, msg);
                return(false);
            }

            return(true);
        }
        public async void CustomRoleRestricted(IPalBot bot, Message msg, string cmd)
        {
            await bot.Reply(msg, "Only people who meet the conditions of the \"CustomRole.cs\" role and people who are \"Authorized\" can use this plugin.");

            //Possible roles:
            //Auth - Only people who are Authorized within the bot.
            //Owner - Only Auth and the Owner of the group
            //Admin - Only Owners, Authorized people, and Admins of the group
            //Mod - Only Owners, Authorized people, Admins and Mods of the group
            //See PalApi.Plugins.Defaults for the instances of the roles.
            //Any custom roles you create.
        }
Beispiel #15
0
        public bool IsMatch(IPalBot bot, Message msg, string cmd, ICommand atr, out string capped, out Message nm)
        {
            capped = cmd;
            nm     = msg;

            if (!cmd.ToLower().StartsWith(atr.Comparitor.ToLower()))
            {
                return(false);
            }

            capped = cmd.Remove(0, atr.Comparitor.Length);
            return(true);
        }
Beispiel #16
0
        public async void TestPlugins(IPalBot bot, Message msg, string cmd)
        {
            //Make the bot reply to the calling user with "Hello world!"
            await bot.Reply(msg, "Hello world!");

            //Make the bot send a PM to the calling user
            await bot.Private(msg.UserId, "Hey there! Thanks for testing the bot!");

            //If the message was sent in a group, send a message back to the group
            if (msg.MesgType == MessageType.Group)
            {
                await bot.Group(msg.GroupId.Value, "Is this group any fun to chat in?");
            }
        }
Beispiel #17
0
        public async void Inspire(IPalBot bot, Message msg, string cmd)
        {
            try
            {
                using (var cli = new WebClient())
                {
                    var url   = cli.DownloadString(QuoteUrl);
                    var image = await bot.GetImage(url);

                    await bot.Reply(msg, image);
                }
            }
            catch (Exception ex)
            {
                await bot.Reply(msg, "Something went wrong: " + ex.ToString());
            }
        }
Beispiel #18
0
        public async void TestQuestionPlugins(IPalBot bot, Message msg, string cmd)
        {
            //Ask the user what their favourite colour is
            await bot.Reply(msg, "Hello! Whats your favourite colour?");

            //Get the reponse from the user
            var colourResponse = await bot.NextMessage(msg);

            //Get the users age
            await bot.Reply(msg, $"So your favourite colour is {colourResponse.Content}. How old are you?");

            //Get the response from the user
            var ageResponse = await bot.NextMessage(msg);

            //Make sure the age is valid.
            if (!int.TryParse(ageResponse.Content, out int age) || age <= 0 || age > 125)
            {
                //Let the user know their response was not valid.
                await bot.Reply(msg, $"I'm sorry but \"{ageResponse.Content}\" is not a valid age! Please try again later...");

                return;
            }

            if (age >= 21)
            {
                await bot.Reply(msg, $"You can drink in the states!");

                return;
            }

            if (age >= 18)
            {
                await bot.Reply(msg, $"You're legal! Awesome!");

                return;
            }

            if (age < 17)
            {
                await bot.Reply(msg, $"You shouldn't be on here! Palringo has an age restriction of 17+");

                return;
            }

            await bot.Reply(msg, $"So you're 17... huh... boring age... Haha");
        }
Beispiel #19
0
        private bool IsMatchAlready(IPalBot bot, LangMessage msg, string cmd, ICommand atr, out string capped)
        {
            capped = cmd;
            var local = bot.Languages[msg.LanguageKey, atr.Comparitor];

            if (local == null)
            {
                return(false);
            }

            if (!cmd.ToLower().StartsWith(local.ToLower()))
            {
                return(false);
            }

            capped = cmd.Remove(0, local.Length);
            return(true);
        }
Beispiel #20
0
        public void GroupUpdateHandler(GroupUpdate update, IPalBot bot)
        {
            var map = update.Payload;

            broadcast.BroadcastGroupUpdate(bot, update);

            if (!((PalBot)bot).SubProfiling.Users.ContainsKey(update.UserId))
            {
                ((PalBot)bot).SubProfiling.Users.Add(update.UserId, new User(update.UserId));
            }

            if (!((PalBot)bot).SubProfiling.Groups.ContainsKey(update.GroupId))
            {
                return;
            }

            if (update.Type == GroupUpdateType.Leave &&
                ((PalBot)bot).SubProfiling.Groups[update.GroupId].Members.ContainsKey(update.UserId))
            {
                ((PalBot)bot).SubProfiling.Groups[update.GroupId].Members.Remove(update.UserId);
            }

            if (update.Type == GroupUpdateType.Join)
            {
                var nextMap = new DataMap(map);

                if (nextMap.ContainsKey("contacts"))
                {
                    nextMap = nextMap.GetValueMap("contacts");
                }
                if (nextMap.ContainsKey(update.UserId.ToString()))
                {
                    nextMap = nextMap.GetValueMap(update.UserId.ToString());
                }

                ((PalBot)bot).SubProfiling.Users[update.UserId].Process(nextMap);

                if (!((PalBot)bot).SubProfiling.Groups[update.GroupId].Members.ContainsKey(update.UserId))
                {
                    ((PalBot)bot).SubProfiling.Groups[update.GroupId].Members.Add(update.UserId, Role.User);
                }
                return;
            }
        }
Beispiel #21
0
        public async void PermaSilence(IPalBot bot, Message msg, string cmd)
        {
            if (!int.TryParse(cmd, out int userid))
            {
                await bot.Reply(msg, "Who is the user you want to silence? (User Id)");

                var resp = await bot.NextMessage(msg);

                if (!int.TryParse(resp.Content.Trim(), out userid))
                {
                    await bot.Reply(msg, $"\"{resp.Content}\" is not a valid user id. Please try again.");

                    return;
                }
            }

            var user = await bot.GetUser(userid);

            await bot.Reply(msg, $"Ok! I will silence {user.Nickname} whenever they speak! Say \"stop silencing\" to stop the bot!");

            var actionResp = await bot.AdminAction(AdminActions.Silence, userid, msg.GroupId.Value);

            if (actionResp.Code != Code.OK)
            {
                await bot.Reply(msg, $"Does not look like the admin action was successful for some reason?\r\nResponse: {actionResp.ToString()}");

                return;
            }

            while (true)
            {
                var userMessage = await bot.NextMessage(m => m.UserId == userid || m.UserId == msg.UserId);

                if (userMessage.UserId == msg.UserId && msg.Content.ToLower().Trim() == "stop silencing")
                {
                    return;
                }

                if (userMessage.UserId == userid)
                {
                    await bot.AdminAction(AdminActions.Silence, userid, msg.GroupId.Value);
                }
            }
        }
Beispiel #22
0
        public void AdminActionHandler(AdminAction action, IPalBot oBot)
        {
            var bot = (PalBot)oBot;

            if (!bot.SubProfiling.Groups.ContainsKey(action.GroupId))
            {
                return;
            }

            var group = bot.SubProfiling.Groups[action.GroupId];

            if (!group.Members.ContainsKey(action.TargetId))
            {
                return;
            }

            group.Members[action.TargetId] = action.Action.ToRole();
            broadcast.BroadcastAdminAction(bot, action);
        }
Beispiel #23
0
        public void SubProfileQueryResponse(SubProfileQueryResult result, IPalBot bot)
        {
            var map = result.Data;

            if (!map.ContainsKey("sub-id"))
            {
                return;
            }

            var id = map.GetValueInt("sub-id");

            if (!((PalBot)bot).SubProfiling.Users.ContainsKey(id))
            {
                ((PalBot)bot).SubProfiling.Users.Add(id, new User());
            }

            foreach (var m in map.EnumerateMaps())
            {
                ((PalBot)bot).SubProfiling.Users[id].Process(m);
            }
        }
Beispiel #24
0
        private async Task <bool> DoDefaults(IPalBot bot, IPlugin plugin, Message message, ICommand cmd)
        {
            var defs = defaults.Where(t => t.Instance == plugin).ToArray();

            if (defs.Length <= 0)
            {
                return(true);
            }

            foreach (var d in defs)
            {
                if (!d.InstanceCommand.MessageType.HasFlag(message.MesgType))
                {
                    continue;
                }

                if (!string.IsNullOrEmpty(d.InstanceCommand.Roles) &&
                    !await roleManager.IsInRole(d.InstanceCommand.Roles, bot, message))
                {
                    continue;
                }

                try
                {
                    d.Method.Invoke(d.Instance,
                                    d.Method.GetParameters().Length == 3 ?
                                    new object[] { bot, message, "" } : //Fill in "string cmd" blank.
                                    new object[] { bot, message });
                    return(false);
                }
                catch (Exception ex)
                {
                    broadcast.BroadcastException(ex, $"Error running default plugin {cmd?.Comparitor} {d.Method.Name} with \"{message.Content}\" from {message.UserId}");
                }
            }

            return(true);
        }
Beispiel #25
0
 public async void PingHandler(PingRequest ping, IPalBot bot)
 {
     var sent = await bot.Write(templates.Ping());
 }
Beispiel #26
0
        private async void ProcessMessage(IPalBot bot, Message message)
        {
            if (message.ContentType != DataType.Text)
            {
                return;
            }

            if (plugins == null || defaults == null)
            {
                LoadPlugins();
            }

            foreach (var plugin in plugins)
            {
                string  msg  = message.Content.Trim();
                Message tmpM = message.Clone();

                if (message is LangMessage)
                {
                    ((LangMessage)message).LanguageKey = null;
                }

                if (plugin.InstanceCommand != null)
                {
                    if (!string.IsNullOrEmpty(plugin.InstanceCommand.Roles) &&
                        !await roleManager.IsInRole(plugin.InstanceCommand.Roles, bot, message))
                    {
                        continue;
                    }

                    var c2 = CheckCommand(bot, plugin.InstanceCommand, message, msg, out tmpM);
                    if (c2 == null)
                    {
                        continue;
                    }

                    msg = c2;

                    if (string.IsNullOrEmpty(msg))
                    {
                        var defs = await DoDefaults(bot, plugin.Instance, message, plugin.InstanceCommand);

                        if (defs)
                        {
                            continue;
                        }

                        return;
                    }
                }

                if (!string.IsNullOrEmpty(plugin.MethodCommand.Roles) &&
                    !await roleManager.IsInRole(plugin.MethodCommand.Roles, bot, message))
                {
                    continue;
                }

                var c = CheckCommand(bot, plugin.MethodCommand, tmpM, msg, out tmpM);
                if (c == null)
                {
                    continue;
                }

                msg = c;

                new Thread(() =>
                {
                    try
                    {
                        ExecuteMethod(plugin.Method, plugin.Instance, bot, tmpM, msg);
                        return;
                    }
                    catch (Exception ex)
                    {
                        broadcast.BroadcastException(ex, $"Error running plugin {plugin.InstanceCommand?.Comparitor} {plugin.MethodCommand.Comparitor} with \"{message.Content}\" from {message.UserId}");
                    }
                }).Start();
            }
        }
Beispiel #27
0
 public void BalanceQueryResultHandle(BalanceQueryResult res, IPalBot bot)
 {
     ((PalBot)bot).SubProfiling.Process(res.Payload, null, null);
 }
Beispiel #28
0
 public void SubProfileHandler(SubProfilePacket sub, IPalBot bot)
 {
     ((PalBot)bot).SubProfiling.Process(sub.Data, sub.IV, sub.RK);
 }
Beispiel #29
0
 public void ThrottleHandler(Throttle throttle, IPalBot bot)
 {
     broadcast.BroadcastThrottle(bot, throttle);
 }
Beispiel #30
0
 public static async Task <bool> Avatar(this IPalBot bot, byte[] image)
 {
     return(await((PalBot)bot).UpdateAvatar(image));
 }