/// <summary> /// Default constructor /// </summary> /// <param name="bot"></param> /// <param name="watchThrottle"></param> /// <param name="cli"></param> public MessageQueue(PalBot bot, bool watchThrottle, Client cli) { _bot = bot; _watch = watchThrottle; _client = cli; bot.On.Throttle += (r) => _wait = r; }
private void LoadPacketHandlers(PalBot bot) { try { var types = AppDomain.CurrentDomain.GetAssemblies() .SelectMany(t => t.GetTypes()) .Where(typeof(IPacketHandler).IsAssignableFrom) .Where(t => !t.IsInterface && !t.IsAbstract) .ToArray(); PacketHandlers = new Dictionary <string, Type>(); foreach (var type in types) { var i = (IPacketHandler)Activator.CreateInstance(type); if (!PacketHandlers.ContainsKey(i.Command.ToUpper())) { PacketHandlers.Add(i.Command.ToUpper(), type); } } } catch (Exception ex) { bot.On.Trigger("e", ex); } }
public Program() { Bot = PalBot.Create(); Bot .UseConsoleLogging() .RegisterTestPlugin(); }
private void OnMessage(PalBot bot, Message msg) { foreach (var plug in Plugs.ToArray().Where(t => t.Matches(bot, msg.Clone()))) { plug.Run(bot, msg.Clone()); } }
private void OnMessage(PalBot bot, Message message) { try { if (message.MesgType == Subprofile.Types.MessageType.Group && GroupInstances.ContainsKey(message.GroupId) && GroupInstances[message.GroupId].ContainsKey(message.SourceId)) { var p = GroupInstances[message.GroupId][message.SourceId]; RunQuestionnaire(p, message, bot); return; } if (message.MesgType == Subprofile.Types.MessageType.Private && PrivateInstances.ContainsKey(message.SourceId)) { var p = PrivateInstances[message.SourceId]; RunQuestionnaire(p, message, bot); return; } } catch (Exception ex) { bot.On.Trigger("e", ex); return; } DoTyping(bot, message, null, message.Content, null); }
private List <MethodInstance <Plugin> > PluginsFromCollection(PalBot bot, TypeInstance <PluginCollection> col, string language = null) { return(col.Type.GetMethods() .Where(t => Attribute.IsDefined(t, typeof(Plugin))) .Select(b => { var m = new MethodInstance <Plugin>(b, b.GetCustomAttribute <Plugin>()); m.Language = language; if (m.Language == null || m.Value.TranslationKey == null) { return m; } var trans = bot.Translations[m.Value.TranslationKey]. Where(t => t.Language == m.Language).ToArray(); if (trans.Length <= 0) { return m; } var x = trans[0]; m.Value.Trigger = x.Value; return m; }).ToList()); }
/// <summary> /// Watches for a response to the a user profile request /// </summary> /// <param name="Bot">The bot instance to attach to</param> /// <param name="uid">The user id to look for</param> /// <param name="resp">The action to do upon finishing</param> /// <returns>This instance of the packet (for string-able-ness)</returns> public Packet Watch(PalBot Bot, UserId uid, Action <User> resp) { if (resp == null) { return(this); } Bot.Callbacks.Watch("SUB PROFILE QUERY RESULT", resp, (packet) => { var bytes = Static.PalringoEncoding.GetBytes(packet.Payload); var map = new DataMap(bytes); if (map.ContainsKey("sub-id")) { int id = map.GetValueInt("sub-id"); if (!Bot.Information.UserCache.ContainsKey(id)) { Bot.Information.UserCache.Add(id, new User()); } foreach (var m in map.EnumerateMaps()) { Bot.Information.UserCache[id].Parse(Bot, m); } return(Bot.Information.UserCache[id]); } return(null); }, (t) => t.Id == uid); return(this); }
/// <summary> /// Parses the information from the DataMap given by subprofile /// </summary> /// <param name="bot"></param> /// <param name="map"></param> public new void Parse(PalBot bot, DataMap map) { if (map.ContainsKey("sub-id")) { Id = int.Parse(map.GetValue("sub-id")); } if (map.ContainsKey("name")) { Name = map.GetValue("name"); } if (map.ContainsKey("name1")) { FirstName = map.GetValue("name1"); } if (map.ContainsKey("name2")) { MiddleNames = map.GetValue("name2"); } if (map.ContainsKey("name3")) { Surname = map.GetValue("name3"); } if (map.ContainsKey("lang")) { Language = (Language)int.Parse(map.GetValue("lang")); } if (map.ContainsKey("sex")) { Gender = (Sex)int.Parse(map.GetValue("sex")); } if (map.ContainsKey("relstatus")) { RelationshipStatus = (Relationship)int.Parse(map.GetValue("relstatus")); } if (map.ContainsKey("after")) { LookingFor = (LookingFor)int.Parse(map.GetValue("after")); } if (map.ContainsKey("about")) { AboutMe = map.GetValue("about"); } if (map.ContainsKey("dob_d")) { DobDay = map.GetValueInt("dob_d"); } if (map.ContainsKey("dob_m")) { DobMonth = map.GetValueInt("dob_m"); } if (map.ContainsKey("dob_y")) { DobYear = map.GetValueInt("dob_y"); } base.Parse(bot, map); }
/// <summary> /// Initial load of the Forum Plugins /// </summary> /// <param name="bot"></param> public void Load(PalBot bot) { try { bot.On.GroupMessage += (m) => OnMessage(bot, m); bot.On.PrivateMessage += (m) => OnMessage(bot, m); var plugs = typeof(IIForum) .GetAllTypes() .Select(t => new KeyValuePair <System.Type, Dictionary <MethodInfo, List <Forum> > >(t, t .GetMethods() .Where(a => Attribute.IsDefined(a, typeof(Forum))) .ToDictionary(b => b, b => Attribute.GetCustomAttributes(b, typeof(Forum)).Cast <Forum>().ToList()))); foreach (var item in plugs) { Plugins.Add(item.Key, new Dictionary <MethodInfo, List <Forum> >()); foreach (var Forum in item.Value) { Plugins[item.Key].Add(Forum.Key, new List <Forum>()); foreach (var atr in Forum.Value) { if (atr.For != null && bot.Title != null && !atr.For.Contains(bot.Title)) { continue; } foreach (var alias in atr.Aliases) { Plugins[item.Key][Forum.Key].Add(atr.Clone(alias)); } if (bot.Translations != null) { var trans = bot.Translations[atr.TranslationKey]; foreach (var t in trans) { var c = atr.Clone(t.Value); c.Language = t.Language; Plugins[item.Key][Forum.Key].Add(c); } } Plugins[item.Key][Forum.Key].Add(atr); } } } } catch (Exception ex) { bot.On.Trigger("e", ex); } }
/// <summary> /// Watches a packet for a RESPONSE packet /// </summary> /// <param name="bot">The bot instance to attach to</param> /// <param name="resp">The action to do upon obtaining the response</param> /// <returns>This instance of the packet (for string-able-ness)</returns> public Packet Watch(PalBot bot, rs resp) { if (resp == null) { return(this); } //bot.Callbacks.Watch("RESPONSE", MessageId, resp, (p) => p.Map<Response>()); Watch(bot, "RESPONSE", resp, (p) => p.Map <Response>(), (r) => r.MessageId == MessageId); return(this); }
public async void PingHandler(PingRequest ping, PalBot bot) { try { var sent = await bot.Write(templates.Ping()); } catch (Exception ex) { Console.WriteLine(ex); } }
public static T GetManager <T>(this PalBot bot) where T : IManager { foreach (var p in bot.Plugins.Triggered) { if (p is T) { return((T)p); } } throw new ArgumentException("Invalid Manager Type!"); }
public static void Main(string[] args) { var settings = Settings.FromFile("bot.settings.json"); Bot = new PalBot("TestBot", true); Bot.On.LoginSuccess += () => LoginSuccess(); Bot.On.LoginFailed += (reason) => Console.WriteLine("Palringo bot not logged in: " + reason); Bot.Login(settings); Console.ReadKey(); }
private void DoTyping(PalBot bot, Message message, object state, string descriptor, Func <string, string> remover) { var group = message.GroupId.GetGroup(bot); var user = message.SourceUser.GetUser(bot); string msg = descriptor.Trim(); foreach (var p in Plugs) { var col = p.Value; if (!col.Type.HasFlag(message.MesgType) || (bot.Title != null && col.For != null && col.For.Length > 0 && !col.For.Contains(bot.Title)) || !msg.ToLower().StartsWith(col.Trigger)) { continue; } if (!col.PermissionEngine.CheckPermissions(col.Permissions, user, group)) { bot.On.Trigger("pf", bot, new FailedPermissionsReport(message, col.Permissions, col.Trigger, PluginType.Questionnaire)); continue; } var submsg = remover == null?msg.Remove(0, col.Trigger.Length).Trim() : remover(message.Content); var i = (IIQuestionnaire)Activator.CreateInstance(p.Type); i.AttributeInstance = p.Value; if (message.MesgType == Subprofile.Types.MessageType.Group) { AddQuestionnaire(i, i.Start, message.GroupId, message.SourceId, bot); } else { AddQuestionnaire(i, i.Start, message.SourceId, bot); } try { i.Language = p.Language; i.Message = message; i.Bot = bot; i.State = state; i.Start(submsg); } catch (Exception ex) { bot.On.Trigger("e", ex); } } }
public void GroupUpdateHandler(GroupUpdate update, PalBot 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; } }
public void AdminActionHandler(AdminAction action, PalBot 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); }
/// <summary> /// Parse the users profile from subprofile /// </summary> /// <param name="bot"></param> /// <param name="data"></param> public void Parse(PalBot bot, DataMap data) { if (data.ContainsKey("sub-id")) { Id = data.GetValueInt("sub-id"); } if (data.ContainsKey("status")) { Status = data.GetValue("status"); } if (data.ContainsKey("rep_lvl")) { RepLevel = double.Parse(data.GetValue("rep_lvl")); } if (data.ContainsKey("nickname")) { Nickname = data.GetValue("nickname"); } if (data.ContainsKey("rep")) { Reputation = long.Parse(data.GetValue("rep")); } if (data.ContainsKey("privileges")) { Privileges = uint.Parse(data.GetValue("privileges")); } if (data.ContainsKey("online-status")) { OnlineStatus = (Status)int.Parse(data.GetValue("online-status")); } if (data.ContainsKey("device-type")) { DeviceType = (Device)int.Parse(data.GetValue("device-type")); } if (data.ContainsKey("contact") && data.GetValue("contact") == "1" && !bot.Information.Contacts.ContainsKey(Id)) { bot.Information.Contacts.Add(Id, this); } Updated(); }
/// <summary> /// The processing system /// </summary> /// <param name="bot">The bot to attach to</param> /// <param name="inPacket">The packet coming in</param> /// <param name="client">The client to attach to</param> public void Process(PalBot bot, Packet inPacket, Client client) { Packet packet; if (!CheckPacket(inPacket, out packet)) { return; } if (PacketHandlers == null || PacketHandlers.Count == 0) { LoadPacketHandlers(bot); } if (!PacketHandlers.ContainsKey(packet.Command.ToUpper())) { bot.On.Trigger("pk", packet); return; } if (packet["COMPRESSION"] == "1") { packet.Payload = packet.DecompressPayload(); } try { bot.Callbacks.Activate(packet); var plug = PacketHandlers[packet.Command.ToUpper()]; var i = (IPacketHandler)Activator.CreateInstance(plug); i.Bot = bot; i.Client = client; i.Process(packet); } catch (Exception ex) { bot.On.Trigger("e", ex); } }
/// <summary> /// Start the bot. /// </summary> public async void Start() { //Create a new PalBot var bot = PalBot.Create() //Tell the PalBot to log packet activity to the Console .UseConsoleLogging() //Call our Register Extension we created for the example .RegisterProjectPlugin() //Set Groupings for this bot .SetGroupings("TestGroup") //Add the owner's pal ID to the Authorized users list. .AddAuth(1234) //Print out Login Failed reason .LoginFailed(reason => Console.WriteLine("Login Failed: " + reason)) //Print out that the bot got disconnected .Disconnected(() => Console.WriteLine("Bot was disconnected")) //Print out that there was a handled error within the bot .Error((error, note) => Console.WriteLine("An error occurred: " + note + "\r\nStack Trace: " + error.ToString())) //Print out that the bot coulnd't connect .CouldNotConnect(() => Console.WriteLine("Bot could not connect to Palringo")) //Load localizations - Don't include this if you aren't going to use localizations (multiple languages) .LanguagesFromFlatFile("localizations.lang") //Automatically relogin when the bot gets throttled .ReloginOnThrottle(); bot.On.GroupUpdate += (b, u) => Console.WriteLine($"User {u.UserId} {u.Type}ed {u.GroupId}"); bot.On.AdminAction += (b, u) => Console.WriteLine($"User {u.SourceId} {u.Action}ed {u.TargetId}"); //Start the login sequence. Only Email and Password are required. Rest will default await bot.Login( //Email Address "*****@*****.**", //Password "asdf", //Authorization Status (Away, Invisible, Online, ect) AuthStatus.Away, //What device to mask the bot as (Suggest PC / Web / Generic) DeviceType.Generic, //Span filter (Suggest false, cause its a bot...) false); }
/// <summary> /// Does the strart up handling for Questionnaires for the QuestionnaireCanceled and QuestionniareFinished delegates /// </summary> /// <param name="bot"></param> public void _doStartUp(PalBot bot) { if (!DoneStartUp) { bot.GetManager <QuestionnaireManager>().QuestionnaireCanceled += (i) => { if (i == this) { OnCancel(); } }; bot.GetManager <QuestionnaireManager>().QuestionnaireFinished += (i) => { if (i == this) { OnFinish(); } }; DoneStartUp = true; } }
public void SubProfileQueryResponse(SubProfileQueryResult result, PalBot bot) { var map = result.Data; if (!map.ContainsKey("sub-id")) { return; } var id = map.GetValueInt("sub-id").ToString(); 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); } }
private async void Button_Clicked(object sender, EventArgs e) { try { var loggedIn = await PalBot.Create().Login(Email.Text, Password.Text, "whats this ??", BotsDotNet.Palringo.Types.AuthStatus.Online, BotsDotNet.Palringo.Types.DeviceType.Android, false); if (!loggedIn) { Log.Text += "Login failed...\n"; return; } else { Log.Text += "Connected...\n"; } } catch (Exception ex) { throw ex; } }
/// <summary> /// Called to load plugins /// </summary> /// <param name="bot"></param> public void Load(PalBot bot) { bot.On.GroupMessage += (gm) => OnMessage(bot, gm.Clone()); bot.On.PrivateMessage += (pm) => OnMessage(bot, pm.Clone()); if (bot.Translations == null) { Plugins = typeof(IIPlugin) .GetAllTypes() .Where(t => Attribute.IsDefined(t, typeof(PluginCollection))) .Select(t => new TypeInstance <PluginCollection>(t, t.GetCustomAttribute <PluginCollection>())) .ToDictionary(t => t, t => PluginsFromCollection(bot, t)); return; } var plugins = typeof(IIPlugin).GetAllTypes() .Where(t => Attribute.IsDefined(t, typeof(PluginCollection))) .Select(t => new TypeInstance <PluginCollection>(t, t.GetCustomAttribute <PluginCollection>())) .ToArray(); Plugins = plugins.Where(t => t.Value.TranslationKey == null) .ToDictionary(t => t, t => PluginsFromCollection(bot, t)); var other = plugins.Where(t => !Plugins.Keys.Contains(t)).ToArray(); foreach (var collection in other) { var trans = bot.Translations[collection.Value.TranslationKey]; foreach (var item in trans) { var clone = new TypeInstance <PluginCollection>(collection.Type, collection.Value.Clone(item.Value)); clone.Language = item.Language; Plugins.Add(clone, PluginsFromCollection(bot, clone, item.Language)); } Plugins.Add(collection, PluginsFromCollection(bot, collection, null)); } }
private void OnMessage(PalBot bot, Message msg) { try { if (msg.MesgType == MessageType.Group && GroupInstances.ContainsKey(msg.GroupId) && GroupInstances[msg.GroupId].ContainsKey(msg.SourceUser)) { GroupInstances[msg.GroupId][msg.SourceUser](msg); return; } if (msg.MesgType == MessageType.Private && PrivateInstances.ContainsKey(msg.SourceUser)) { PrivateInstances[msg.SourceUser](msg); return; } } catch (Exception ex) { bot.On.Trigger("e", ex); return; } DoPluginSort(bot, msg); }
public void ProcessPacket(PalBot bot, IPacketMap packet) { if (packetHandlers == null) { LoadHandlers(); } var handlers = packetHandlers.Where(t => t.Handlers.ContainsKey(packet.Command.ToUpper())); foreach (var handler in handlers) { var method = handler.Handlers[packet.Command.ToUpper()]; try { method.Invoke(handler.Instance, new object[] { packet, bot }); } catch (Exception ex) { broadcast.BroadcastException(ex, $"Error processing handler {method.Name} for {packet.Command.ToUpper()}"); } } }
/// <summary> /// What to do on loading the plugins /// </summary> /// <param name="bot">Bot to attach the instance to</param> public void Start(PalBot bot) { _triggered = new List <IManager>(); try { foreach (var m in PluginHandlers) { try { m.Load(bot); bot.On.Trigger("ll", $"[{m.GetType().Name}] Loaded"); _triggered.Add(m); } catch (Exception ex) { bot.On.Trigger("e", $"[{m.GetType().Name}] Error => {ex.Message}"); } } } catch (Exception ex) { bot.On.Trigger("e", $"Plugin Handlers failed to load: " + ex.Message); } }
/// <summary> /// Initial load of all questionnaire plugins /// </summary> /// <param name="bot"></param> public void Load(PalBot bot) { bot.On.GroupMessage += (m) => OnMessage(bot, m); bot.On.PrivateMessage += (m) => OnMessage(bot, m); var ps = typeof(IIQuestionnaire).GetAllTypes() .Where(t => Attribute.IsDefined(t, typeof(Questionnaire))) .Select(t => new TypeInstance <Questionnaire>(t, t.GetCustomAttribute <Questionnaire>())).ToList(); foreach (var plug in ps) { if (bot.Translations != null) { foreach (var tr in bot.Translations[plug.Value.TranslationKey]) { var c = new TypeInstance <Questionnaire>(plug.Type, plug.Value.Clone(tr.Value)); c.Language = tr.Language; Plugs.Add(c); } } Plugs.Add(plug); } }
/// <summary> /// Intial load of the plugins /// </summary> /// <param name="bot"></param> public void Load(PalBot bot) { Plugs = new List <CommandHolder>(); bot.On.GroupMessage += (gm) => OnMessage(bot, gm.Clone()); bot.On.PrivateMessage += (pm) => OnMessage(bot, pm.Clone()); }
private void RunQuestionnaire(KeyValuePair <IIQuestionnaire, Action <string> > p, Message message, PalBot bot) { p.Key.Message = message; p.Key.Bot = bot; if (!string.IsNullOrEmpty(p.Key.AttributeInstance.CancelWord) && message.Content.ToLower().Trim() == p.Key.AttributeInstance.CancelWord) { QuestionnaireCanceled(p.Key); p.Key.Finish(); return; } p.Value(message.Content); }
private void AddQuestionnaire(IIQuestionnaire quest, Action <string> method, int userid, PalBot bot) { PrivateInstances.Add(userid, new KeyValuePair <IIQuestionnaire, Action <string> >(quest, method)); quest.Next = (a) => PrivateInstances[userid] = new KeyValuePair <IIQuestionnaire, Action <string> >(quest, a); quest.Finish = () => { QuestionnaireFinished(quest); PrivateInstances.Remove(userid); }; quest.MoveToPrivate = () => false; quest.MoveToGroup = (i) => { if (!GroupInstances.ContainsKey(i)) { GroupInstances.Add(i, new Dictionary <int, KeyValuePair <IIQuestionnaire, Action <string> > >()); } if (GroupInstances[i].ContainsKey(userid)) { return(false); } AddQuestionnaire(quest, PrivateInstances[userid].Value, i, userid, bot); PrivateInstances.Remove(userid); return(true); }; ((IQuestionnaire)quest)._doStartUp(bot); }