Beispiel #1
0
        public static User GetTarget(this Message message, string args, User sourceUser, Instance db)
        {
            if (message == null)
            {
                return(sourceUser);
            }
            if (message?.ReplyToMessage != null)
            {
                var m      = message.ReplyToMessage;
                var userid = m.ForwardFrom?.Id ?? m.From.Id;
                return(db.Users.FirstOrDefault(x => x.UserId == userid) ?? sourceUser);
            }
            if (String.IsNullOrWhiteSpace(args))
            {
                return(sourceUser);
            }
            //check for a user mention
            var mention     = message?.Entities.FirstOrDefault(x => x.Type == MessageEntityType.Mention);
            var textmention = message?.Entities.FirstOrDefault(x => x.Type == MessageEntityType.TextMention);
            var id          = 0;
            var username    = "";

            if (mention != null)
            {
                username = message.Text.Substring(mention.Offset + 1, mention.Length - 1);
            }
            else if (textmention != null)
            {
                id = textmention.User.Id;
            }
            User result = null;

            if (!String.IsNullOrEmpty(username))
            {
                result = db.Users.FirstOrDefault(
                    x =>
                    String.Equals(x.UserName, username,
                                  StringComparison.InvariantCultureIgnoreCase));
            }
            else if (id != 0)
            {
                result = db.Users.FirstOrDefault(x => x.UserId == id);
            }
            else
            {
                result = db.Users.FirstOrDefault(
                    x =>
                    String.Equals(x.UserId.ToString(), args, StringComparison.InvariantCultureIgnoreCase) ||
                    String.Equals(x.UserName, args.Replace("@", ""), StringComparison.InvariantCultureIgnoreCase));
            }
            return(result ?? sourceUser);
        }
Beispiel #2
0
        /// <summary>
        /// Gets a user setting from the database
        /// </summary>
        /// <typeparam name="T">The type the setting should be (bool, int, string)</typeparam>
        /// <param name="user">What user the setting comes from</param>
        /// <param name="field">The name of the setting</param>
        /// <param name="db">The database instance</param>
        /// <param name="def">The default value for the field</param>
        /// <returns></returns>
        public static T GetSetting <T>(this User user, string field, Instance db, T def)
        {
            if (db.Connection.State != ConnectionState.Open)
            {
                db.Connection.Open();
            }
            //verify settings exist
            var columns = new SQLiteCommand("PRAGMA table_info(users)", db.Connection).ExecuteReader();
            var t       = default(T);

            while (columns.Read())
            {
                if (String.Equals(columns[1].ToString(), field))
                {
                    var result = db.Connection.ExecuteScalar($"select [{field}] from users where ID = @ID", new { user.ID });
                    if (t != null)
                    {
                        if (t.GetType() == typeof(bool))
                        {
                            result = result.ToString() == "1"; // convert to boolean
                        }
                        else if (t.GetType() == typeof(int))
                        {
                            result = Convert.ToInt32((long)result); // convert int64 to int32
                        }
                    }
                    return((T)result);
                }
            }
            var type = "BLOB";

            if (t == null)
            {
                type = "TEXT";
            }
            else if (t.GetType() == typeof(int))
            {
                type = "INTEGER";
            }
            else if (t.GetType() == typeof(bool))
            {
                type = "INTEGER";
            }

            var d = def.FormatSQL();

            db.ExecuteNonQuery($"ALTER TABLE users ADD COLUMN [{field}] {type} DEFAULT {d}");
            return(def);
        }
Beispiel #3
0
        /// <summary>
        /// Sets a user setting to the database
        /// </summary>
        /// <typeparam name="T">The type the setting should be (bool, int, string)</typeparam>
        /// <param name="user">What user the setting comes from</param>
        /// <param name="field">The name of the setting</param>
        /// <param name="db">The database instance</param>
        /// <param name="def">The default value for the field</param>
        /// <returns></returns>
        public static bool SetSetting <T>(this User user, string field, Instance db, T def, T value)
        {
            try
            {
                if (db.Connection.State != ConnectionState.Open)
                {
                    db.Connection.Open();
                }
                //verify settings exist
                var columns = new SQLiteCommand("PRAGMA table_info(users)", db.Connection).ExecuteReader();
                var t       = default(T);
                var type    = "BLOB";
                if (t == null)
                {
                    type = "TEXT";
                }
                else if (t.GetType() == typeof(int))
                {
                    type = "INTEGER";
                }
                else if (t.GetType() == typeof(bool))
                {
                    type = "INTEGER";
                }
                bool settingExists = false;
                while (columns.Read())
                {
                    if (String.Equals(columns[1].ToString(), field))
                    {
                        settingExists = true;
                    }
                }
                if (!settingExists)
                {
                    var d = def.FormatSQL();
                    db.ExecuteNonQuery($"ALTER TABLE users ADD COLUMN [{field}] {type} DEFAULT {d}");
                }

                db.ExecuteNonQuery($"UPDATE users set [{field}] = @value where ID = @ID", new { value, user.ID });

                return(true);
            }
            catch
            {
                return(false);
            }
        }
Beispiel #4
0
 public static void Save(this User u, Instance db)
 {
     if (u.ID == null || !ExistsInDb(u, db))
     {
         //need to insert
         db.ExecuteNonQuery(
             "insert into users (Name, UserId, UserName, FirstSeen, LastHeard, Points, Location, Debt, LastState, Greeting, Grounded, GroundedBy, IsBotAdmin, LinkingKey, Description) VALUES (@Name, @UserId, @UserName, @FirstSeen, @LastHeard, @Points, @Location, @Debt, @LastState, @Greeting, @Grounded, @GroundedBy, @IsBotAdmin, @LinkingKey, @Description)",
             u);
         u.ID =
             db.Connection.Query <int>(
                 $"SELECT ID FROM Users WHERE UserId = @UserId", u)
             .First();
     }
     else
     {
         db.ExecuteNonQuery(
             "UPDATE users SET Name = @Name, UserId = @UserId, UserName = @UserName, FirstSeen = @FirstSeen, LastHeard = @LastHeard, Points = @Points, Location = @Location, Debt = @Debt, LastState = @LastState, Greeting = @Greeting, Grounded = @Grounded, GroundedBy = @GroundedBy, IsBotAdmin = @IsBotAdmin, LinkingKey = @LinkingKey, Description = @Description WHERE ID = @ID",
             u);
     }
 }
Beispiel #5
0
        /// <summary>
        /// Gets a user setting from the database
        /// </summary>
        /// <typeparam name="T">The type the setting should be (bool, int, string)</typeparam>
        /// <param name="user">What user the setting comes from</param>
        /// <param name="field">The name of the setting</param>
        /// <param name="db">The database instance</param>
        /// <param name="def">The default value for the field</param>
        /// <returns></returns>
        public static T GetSetting <T>(this User user, string field, Instance db, object def)
        {
            if (db.Connection.State != ConnectionState.Open)
            {
                db.Connection.Open();
            }
            //verify settings exist
            var columns = new SQLiteCommand("PRAGMA table_info(users)", db.Connection).ExecuteReader();
            var t       = default(T);

            while (columns.Read())
            {
                if (String.Equals(columns[1].ToString(), field))
                {
                    var result = new SQLiteCommand($"select {field} from users where ID = {user.ID}", db.Connection).ExecuteScalar();
                    if (t != null && t.GetType() == typeof(bool))
                    {
                        result = (result.ToString() == "1"); //make it a boolean value
                    }
                    return((T)result);
                }
            }
            var type = "BLOB";

            if (t == null)
            {
                type = "TEXT";
            }
            else if (t.GetType() == typeof(int))
            {
                type = "INTEGER";
            }
            else if (t.GetType() == typeof(bool))
            {
                type = "INTEGER";
            }

            new SQLiteCommand($"ALTER TABLE users ADD COLUMN {field} {type} DEFAULT {(type == "INTEGER" ? def : $"'{def}'")};", db.Connection)
Beispiel #6
0
 public static void RemoveFromDb(this User user, Instance db)
 {
     db.ExecuteNonQuery("DELETE FROM Users WHERE ID = @ID", user);
 }
Beispiel #7
0
        public static bool ExistsInDb(this User user, Instance db)
        {
            var rows = db.Connection.Query("SELECT COUNT(1) as 'Count' FROM Users WHERE ID = @ID", user);

            return((int)rows.First().Count > 0);
        }
Beispiel #8
0
        public Cleverbot(Instance db, Setting settings, TelegramBotClient bot)
        {
            var me = bot.GetMeAsync().Result;

            bot.OnUpdate += (sender, args) =>
            {
                new Task(() =>
                {
                    try
                    {
                        //check to see if it was to me, a reply to me, whatever
                        var message = args.Update.Message;
                        if (message?.Date == null)
                        {
                            return;
                        }
                        if (message.Date < DateTime.UtcNow.AddSeconds(-10))
                        {
                            return;
                        }
                        if (message?.Text == null)
                        {
                            return;
                        }

                        var text = message.Text.ToLower();

                        if (text.StartsWith("!") || text.StartsWith("/"))
                        {
                            return;                                               //ignore commands
                        }
                        if (text.Contains(me.FirstName.ToLower()) || text.Contains(me.Username.ToLower()) ||
                            message.ReplyToMessage?.From.Id == me.Id || message.Chat.Type == ChatType.Private)
                        {
                            DB.Models.User u = db.GetUserById(message.From.Id);
                            if (u.Grounded == true)
                            {
                                return;
                            }
                            DB.Models.Group g = null;
                            if (message.Chat.Type != ChatType.Private)
                            {
                                //check if group has AI enabled
                                g           = db.GetGroupById(message.Chat.Id);
                                var enabled = g.GetSetting <bool>("MitsukuEnabled", db, false);
                                if (!enabled)
                                {
                                    return;
                                }
                            }
                            if (message.Text.Contains("ZBERT"))
                            {
                                bot.SendTextMessageAsync(message.Chat.Id, $"User {message.From.FirstName} is now ignored.", replyToMessageId: message.MessageId);
                                u            = db.GetUserById(message.From.Id);
                                u.Grounded   = true;
                                u.GroundedBy = "Mitsuku";
                                u.Save(db);
                                return;
                            }
                            var cookieCode = "";
                            if (message.Chat.Type == ChatType.Private || text.Contains("my") || text.Contains("i am"))
                            {
                                //personal message

                                cookieCode = u.GetSetting <string>("MitsukuCookie", db, "");
                            }
                            else
                            {
                                //group message
                                g          = db.GetGroupById(message.Chat.Id);
                                cookieCode = g.GetSetting <string>("MitsukuCookie", db, "");
                            }
                            text = text.Replace(me.FirstName.ToLower(), "Mitsuku").Replace("@", "").Replace(me.Username.ToLower(), "Mitsuku");
                            //change this to use webrequest, so we can use cookies.

                            //var request = WebRequest.Create("https://kakko.pandorabots.com/pandora/talk?botid=f326d0be8e345a13&skin=chat");
                            var values = new NameValueCollection()
                            {
                                { "message", text }
                            };
                            //var response = request.GetResponse()
                            var wc = new CookieAwareWebClient();
                            if (!String.IsNullOrEmpty(cookieCode))
                            {
                                wc.CookieContainer.Add(new Cookie
                                {
                                    Domain = "kakko.pandorabots.com",
                                    Name   = "botcust2",
                                    Value  = cookieCode
                                });
                            }
                            var response =
                                Encoding.UTF8.GetString(
                                    wc.UploadValues(
                                        "https://kakko.pandorabots.com/pandora/talk?botid=f326d0be8e345a13&skin=chat", values
                                        ));


                            //sample botcust2=94b4d935be0b9c19
                            var cookie = GetAllCookies(wc.CookieContainer).First();
                            if (cookie.Value != cookieCode)
                            {
                                if (u != null)
                                {
                                    u.SetSetting <string>("MitsukuCookie", db, "", cookie.Value);
                                }
                                if (g != null)
                                {
                                    g.SetSetting <string>("MitsukuCookie", db, "", cookie.Value);
                                }
                            }
                            //wc.CookieContainer
                            var matches = Regex.Matches(response, "(Mіtsuku:</B>(.*))(<B>You:</B>)", RegexOptions.CultureInvariant);
                            var match   = matches[0].Value;
                            if (match.Contains("<B>You:</B>"))
                            {
                                match = match.Substring(0, match.IndexOf("<B>You:</B>"));
                            }
                            match =
                                match.Replace("Mіtsuku:", "")
                                .Replace("Mitsuku:", "")
                                .Replace("</B> ", "")
                                .Replace(" .", ".")
                                .Replace("<br>", "  ")
                                .Replace("Mitsuku", "Seras")
                                .Replace("Мitsuku", "Seras")
                                .Replace("Mіtsuku", "Seras")
                                .Replace(" < P ALIGN=\"CENTER\">", "")
                                .Replace("</P>", " ")
                                .Trim();
                            match = match.Replace("<B>", "```").Replace("You:", "").Replace("Μitsuku:", "").Trim();
                            match = match.Replace("Mousebreaker", "Para");

                            //[URL]http://www.google.co.uk/search?hl=en&amp;q=dot net&amp;btnI=I%27m+Feeling+Lucky&amp;meta=[/URL]
                            if (match.Contains("[URL]"))
                            {
                                //parse out the url
                                var url = Regex.Match(match, @"(\[URL\].*\[/URL\])").Value;
                                match   = "[" + match.Replace(url, "") + "]";
                                url     = url.Replace("[URL]", "").Replace("[/URL]", "").Replace(".co.uk", ".com");
                                match  += $"({url})"; //markdown linking
                                Console.WriteLine(match);

                                bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match, replyToMessageId: message.MessageId, parseMode: ParseMode.Markdown);
                            }
                            //<P ALIGN="CENTER"><img src="http://www.square-bear.co.uk/mitsuku/gallery/donaldtrump.jpg"></img></P>
                            else if (match.Contains("img src=\""))
                            {
                                var img = Regex.Match(match, "<img src=\"(.*)\"></img>").Value;
                                match   = match.Replace(img, "").Replace("<P ALIGN=\"CENTER\">", "").Trim();

                                ;
                                img = img.Replace("<img src=\"", "").Replace("\"></img>", "");
                                //download the photo
                                var filename = args.Update.Message.MessageId + ".jpg";
                                new WebClient().DownloadFile(img, filename);
                                //create the file to send
                                var f2S = new Telegram.Bot.Types.InputFiles.InputOnlineFile(new FileStream(filename, FileMode.Open, FileAccess.Read), filename);
                                Console.WriteLine(match);
                                bot.SendPhotoAsync(args.Update.Message.Chat.Id, f2S, match);
                                //bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match);
                            }
                            else
                            {
                                Console.WriteLine(match);
                                bot.SendTextMessageAsync(args.Update.Message.Chat.Id, match, replyToMessageId: message.MessageId, parseMode: ParseMode.Markdown);
                            }
                        }
                    }
                    catch
                    {
                        // ignored
                    }
                }).Start();
            };
        }