Exemplo n.º 1
0
        public static DiscordApiKey Load(string path)
        {
            var dir      = Path.GetDirectoryName(path);
            var fileName = Path.GetFileName(path);
            var e        = Path.GetFullPath(path).Replace(fileName, "");

            if (!Directory.Exists(e))
            {
                Directory.CreateDirectory(e);
            }
            if (!File.Exists(path))
            {
                var twikeys = new DiscordApiKey()
                {
                    ApiKey = ""
                };
                var tex = JsonConvert.SerializeObject(twikeys);
                File.WriteAllText(path, tex);
            }

            var text = File.ReadAllText(path);

            if (text.Contains("\"\""))
            {
                Abbybot.print($"Master I can't talk to my friends without my discord token... It's the {fileName} file in {dir}!!!");
            }

            DiscordApiKey api = JsonConvert.DeserializeObject <DiscordApiKey>(File.ReadAllText(path));

            return(api);
        }
Exemplo n.º 2
0
        public override async Task OnWork(DateTime time)
        {
            var atmms = await Twitter.ts.ListTweetsMentioningMeAsync(new TweetSharp.ListTweetsMentioningMeOptions {
                Count = 5, IncludeEntities = true
            });

            TwitterRateLimitStatus rate = Twitter.ts.Response.RateLimitStatus;

            Abbybot.print("You have used " + rate.RemainingHits + " out of your " + rate.HourlyLimit);

            var tsmm = atmms.Value.ToArray();

            foreach (var tmm in tsmm)
            {
                var test = await AbbybotMentionSql.GetLatestMentionIdsAsync((ulong)tmm.Id);

                if (test.Count > 0)
                {
                    continue;
                }
                await AbbybotMentionSql.AddLatestMentionIdAsync((ulong)tmm.Id);

                var tmt = Regex.Replace(tmm.Text, @"http[^\s]+", "");
                var t   = Regex.Replace(tmt, @"@[^\s]+", "");
                //var twitteruser = AbbybotUser.GetUserFromTwitterUser(tmm.Author.ScreenName);
                //AbbybotTwitterCommandArgs atca = new AbbybotTwitterCommandArgs();
                //atca.Message = t;
                //atca.abbybotUser = (AbbybotUser)twitteruser;

                Abbybot.print($"[\n{t}\n]");
            }
        }
Exemplo n.º 3
0
 static async Task Disconnected(Exception log, DiscordSocketClient _client)
 {
     Abbybot.print($"waa: {log}\n\nreconnecting...");
     //await Task.Delay(1000 * 60);
     // _client.
     // await _client.StartAsync();
 }
Exemplo n.º 4
0
        public static TwitterApiKeys Load(string path)
        {
            var dir      = Path.GetDirectoryName(path);
            var fileName = Path.GetFileName(path);
            var e        = Path.GetFullPath(path).Replace(fileName, "");

            if (!Directory.Exists(e))
            {
                Directory.CreateDirectory(e);
            }
            if (!File.Exists(path))
            {
                var twikeys = new TwitterApiKeys()
                {
                    AccessToken      = "",
                    AcessTokenSecret = "",
                    ConsumerKey      = "",
                    ConsumerSecret   = ""
                };
                var tex = JsonConvert.SerializeObject(twikeys);
                File.WriteAllText(path, tex);
            }

            var text = File.ReadAllText(path);

            if (text.Contains("\"\""))
            {
                Abbybot.print($"uh master... I can't post on twitter without my api keys... Check {fileName} in {dir} for my api keys for me...");
                throw new Exception();
            }

            TwitterApiKeys api = JsonConvert.DeserializeObject <TwitterApiKeys>(File.ReadAllText(path));

            return(api);
        }
Exemplo n.º 5
0
        static async Task Recieved(LogMessage log)
        {
            await Task.CompletedTask;

            Abbybot.print(log.ToString());
            //throw new NotImplementedException();
        }
Exemplo n.º 6
0
        public override async Task DoWork(AbbybotCommandArgs message)
        {
            azr = 0;
            UserData.RegisterType <AbbybotUser>();
            UserData.RegisterType <AbbybotGuild>();
            Script script = new(CoreModules.Preset_SoftSandbox);             //no io/sys calls allowed

            script.Options.DebugPrint = _ => { };
            var luadata = await LuaSql.GetLuaData(message.user.Id);

            foreach (var luaCo in luadata.LuaPieces)
            {
                await TryRunLua(message, script, luaCo);
            }

            script.Options.DebugPrint = async s =>
            {
                if (azr < 3)
                {
                    azr++;
                    //Console.WriteLine($"test {azr}");
                    await message.Send(s);                     //when print is used send message
                }
                else
                {
                    await Task.Delay(100);
                }
            };
            Abbybot.print($"user {message.user}, guild {message.guild}");
            DynValue user = UserData.Create(message.user);

            script.Globals.Set("user", user);

            if (message.guild != null)
            {
                DynValue guild = UserData.Create(message.guild);
                script.Globals.Set("guild", guild);
            }

            script.Globals["buildfc"] = (Func <string, string>)message.BuildAbbybooruTag;

            DynValue dada = script.DoString("say = print");

            var m = message.Message.Split("```");

            foreach (var item in m)
            {
                var lu = item.Split('\n');
                if (lu[0] != "lua")
                {
                    continue;
                }

                StringBuilder sb = new(item);
                sb.Remove(0, 4);

                await TryRunLua(message, script, sb.ToString(), async ww =>
                                await LuaSql.AddLuaData(message.user.Id, ww));
            }
        }
Exemplo n.º 7
0
        public override async Task DoWork(AbbybotCommandArgs a)
        {
            var FavoriteCharacter = a.Replace(Command);


            if (a.user.isGuild && !a.user.admin)
            {
                await a.Send($"silly {a.user.Preferedname}, you're not an admin here!!!");
            }
            Abbybot.print("acadd called");
            if (FavoriteCharacter.Length < 1)
            {
                return;
            }
            a.BuildAbbybooruTag(FavoriteCharacter);

            string pictureurl = "https://img2.gelbooru.com/samples/ee/e2/sample_eee286783bfa37e088d1ffbcf8f098ba.jpg";
            var    o          = new string[1];

            o[0] = FavoriteCharacter.ToString() + "*";

            var ee = await FCSimplification.awa(a, o, "");

            EmbedBuilder eb = new EmbedBuilder();

            eb.ImageUrl = pictureurl;
            var u = a.user;

            if (ee.canrun)
            {
                try
                {
                    await AbbyBooruCharacterSql.AddCharacterAsync(a.channel, a.guild, ee.fc);
                }
                catch (Exception e)
                {
                    Abbybot.print(e.Message);

                    eb.Title       = $"silly!!! {a.user.Preferedname}!!!";
                    eb.Color       = Color.Red;
                    eb.Description = $"silly!! {ee.fc} was already added to this channel!!";
                    await a.Send(eb);

                    return;
                }
                eb.Title       = $"{a.user.Preferedname} Yayy!!";
                eb.Color       = Color.Green;
                eb.Description = $"I added {ee.fc} to the channel master!! ";
            }
            else
            {
                eb.Title       = $"oof... {a.user.Preferedname}...";
                eb.Color       = Color.Red;
                eb.Description = $"sorry {u.Preferedname}... i couldn't find {ee.fc} ({FavoriteCharacter}) ...";
            }
            await a.Send(eb);
        }
Exemplo n.º 8
0
        static async Task Updated(SocketUser olduser, SocketUser newuser)
        {
            Abbybot.print("awawa ");
            if (olduser is SocketGuildUser osgu && newuser is SocketGuildUser nsgu)
            {
                if (osgu.Nickname != nsgu.Nickname)
                {
                    NicknameChangedMessage bm = await NicknameChangedMessage.CreateFromUser(osgu.Nickname, nsgu.Nickname, nsgu.Guild);

                    await MessageHandler.DoGuildMessage(bm);
                }
            }
            //throw new NotImplementedException();
        }
Exemplo n.º 9
0
        public override async Task DoWork(AbbybotCommandArgs a)
        {
            var FavoriteCharacter = a.Replace(Command).Replace("--debugmode", "").Replace("abbybot ", "%");

            var o = await SaybadtaglistSql.GetbadtaglistTags();

            foreach (var oo in o)
            {
                FavoriteCharacter.Replace(oo, "");
            }

            if (!(a.channel is SocketDMChannel))
            {
                await a.Delete();
            }
            Abbybot.print("tried to run say");
            await a.Send(FavoriteCharacter);
        }
Exemplo n.º 10
0
        static void WriteMessage(SocketMessage message)
        {
            var guild = (message.Author is SocketGuildUser gu) ? gu.Guild.Name : "dms";

            var           username = message.Author.Username;
            StringBuilder sb       = new StringBuilder();

            sb.Append(guild).Append('-').Append(username).Append(": ");

            sb.AppendLine(message.Content);

            foreach (var embed in message.Embeds.ToList())
            {
                if (embed.Title is string)
                {
                    sb.AppendLine($"[{embed.Title}]");
                }

                if (embed.Description is string)
                {
                    sb.AppendLine($"[{embed.Description}]");
                }
                if (embed.Image.HasValue)
                {
                    sb.AppendLine($"[{embed.Image.Value.Url}]");
                }
                if (embed.Video.HasValue)
                {
                    sb.AppendLine($"[{embed.Video.Value}]");
                }
                foreach (var field in embed.Fields)
                {
                    sb.AppendLine($"-[{field.Name}]");
                    sb.AppendLine($"-[{field.Value}]");
                }
                if (embed.Footer.HasValue)
                {
                    var foot = embed.Footer.Value;
                    sb.AppendLine($"[{foot.Text}]");
                }
            }

            Abbybot.print(sb.ToString());
        }
Exemplo n.º 11
0
        static async Task Recieved(SocketMessage message)
        {
            bool nowrite = false;
            var  cs      = await AbbybotSql.GetAbbybotChannelIdAsync();

            foreach (var(guildId, channelId) in cs)
            {
                if (message.Channel.Id != channelId)
                {
                    nowrite = true;
                }
            }
            if (!nowrite)
            {
                WriteMessage(message);
            }

            ulong guidId = 0, chanelId = 0;
            ulong abbybotId = Discord.__client.CurrentUser.Id;

            if (message.Author is SocketGuildUser sgu)
            {
                guidId   = sgu.Guild.Id;
                chanelId = message.Channel.Id;

                var pref = await GuildSql.GetGuild(guidId);

                if (pref.PrefAbbybot == 0)
                {
                    await GuildSql.UpdatePrefAbbybot(guidId, abbybotId);

                    pref = await GuildSql.GetGuild(guidId);
                }
                if (pref.PrefAbbybot != abbybotId)
                {
                    Abbybot.print("I'm not the prefered abbybot for this message");
                    return;
                }
            }

            await PassiveUserSql.IncreaseStat(abbybotId, guidId, chanelId, message.Author.Id, "MessagesSent");

            await CommandHandler.Handle(message);
        }
Exemplo n.º 12
0
        public override async Task OnTick(DateTime time)
        {
            if (delay == TimeSpan.Zero)
            {
                Abbybot.print($"A {this.GetType()} has a delay of 0 which is bad pls fix");
                return;
            }

            if (time > tick)
            {
                tick = time.Add(delay);
                if (firstrun)
                {
                    firstrun = false; return;
                }

                await OnWork(time);
            }
        }
Exemplo n.º 13
0
        static async Task StartDiscord()
        {
            bool o = true;

            do
            {
                try
                {
                    DiscordApiKey dak = DiscordApiKey.Load(@"ApiKeys\Discord.json");
                    await __client.LoginAsync(TokenType.Bot, dak.ApiKey);

                    await __client.StartAsync();

                    o = false;
                }
                catch
                {
                    Abbybot.print("Failed to start discord. Trying again in 10 seconds.");
                    await Task.Delay(10000);
                }
            } while (o);
        }
Exemplo n.º 14
0
        public static void Load(string path)
        {
            var dir      = Path.GetDirectoryName(path);
            var fileName = Path.GetFileName(path);
            var e        = Path.GetFullPath(path).Replace(fileName, "");

            if (!Directory.Exists(e))
            {
                Directory.CreateDirectory(e);
            }
            if (!File.Exists(path))
            {
                File.WriteAllText(path, "Replace this text with the path to your mysql bin folder.");
            }

            var text = File.ReadAllText(path);

            mysqlbinpath = text;
            if (text.Contains("Replace") && text.Contains("bin folder"))
            {
                Abbybot.print($"AbbybotMemory: Abbybot's memory is not running and I can't find where abbybot's memory is to turn it back on... Did you forget to give me it? ({fileName} in {dir})");
            }
        }
Exemplo n.º 15
0
        public static async Task SendTweet(Action onSucceed = null, Action <string> onFail = null)
        {
            Abbybot.print("ayo");
            var abbybotchannels = await AbbybotSql.GetAbbybotChannelIdAsync();

            bool  tellnano = abbybotchannels.Count > 0;
            ulong guildId = 0, channelId = 0;
            var   er = r.Next(0, abbybotchannels.Count);

            if (tellnano)
            {
                var(g, ch) = abbybotchannels[er];
                guildId    = g; channelId = ch;
            }
            var c = Discord.__client?.GetGuild(guildId)?.GetTextChannel(channelId);

            if (abbybotchannels.Count > 0)
            {
                await c.SendMessageAsync("nano gonna work");
            }
            PingAbbybotClock.o = 6; //6 is the working state
            Tweet tweet = null;

            Task <Tweet>[] tweets = new Task <Tweet>[] {
                TweetQueueSql.Peek(),
                           TweetArchiveSql.Peek()
            };
            string location = "";
            int    i = 0, olo = 0;

            do
            {
                try {
                    tweet = await tweets[i];
                } catch (Exception e) { i++; if (i < tweets.Length)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            break;
                                        } }
                await AbbyBooru.GetPictureById((ulong)tweet.GelId, post =>
                {
                    tweet.url       = post.fileUrl;
                    tweet.sourceurl = post.source;
                    location        = post.fileUrl;
                });

                if (olo++ > 3)
                {
                    i++;
                    olo = 0;
                }
            } while (location == "" && i < tweets.Length);
            Console.Write($"location found? {location!=""}, i was bigger than or equal to dbs? {i>=tweets.Length}");

            if (i >= tweets.Length)
            {
                onFail?.Invoke("I was not able to find a picture...");
                return;
            }

            if (tweet == null)
            {
                P("no tweet was found");
                if (tellnano)
                {
                    await c.SendMessageAsync("I'm done working nano");

                    PingAbbybotClock.o = 1;
                }
                onFail?.Invoke("I was not able to find a picture...");
                return;
            }

            var tempfilepath = await ImageDownloader.DownloadImage(tweet.url);

            Console.WriteLine(tempfilepath);
            if (tempfilepath == null)
            {
                P("no image found.");
                if (tellnano)
                {
                    await c.SendMessageAsync("I'm done working nano");

                    PingAbbybotClock.o = 1;
                }

                onFail?.Invoke("I was not able to find a picture...");
                return;
            }

            TwitterUploadedMedia me;
            int tsrs = 0;

            do
            {
                FileStream file = new FileStream(tempfilepath, FileMode.Open);

                MediaFile m = new MediaFile {
                    Content = file
                };

                tsrs++;
                TwitterAsyncResult <TwitterUploadedMedia> media = await Twitter.ts.UploadMediaAsync(new UploadMediaOptions { Media = m });

                if (media == null)
                {
                    Abbybot.print("failed to upload media");
                    if (tellnano)
                    {
                        await c.SendMessageAsync("I'm done working nano");

                        PingAbbybotClock.o = 1;
                    }
                    onFail?.Invoke("I twitter didn't let me to upload the picture...");
                    return;
                }
                file.Dispose();
                Abbybot.print(media.Response.Response);

                if (media.Response.Response.ToLower().Contains("unrecognized"))
                {
                    Abbybot.print("media type unregognized");
                    await TweetQueueSql.Remove(tweet);
                    await SendTweet();

                    if (tellnano)
                    {
                        await c.SendMessageAsync("I'm done working nano");

                        PingAbbybotClock.o = 1;
                    }
                    onFail?.Invoke("twitter didn't know what i was trying to post... it was not an image...");
                    return;
                }
                me = media.Value;
            } while ((me == null) && (tsrs < 3));

            if (me == null)
            {
                await TweetArchiveSql.Add(tweet, true);

                await TweetQueueSql.Remove(tweet);
                await SendTweet();

                if (tellnano)
                {
                    await c.SendMessageAsync("I'm done working nano");

                    PingAbbybotClock.o = 1;
                }
                onFail?.Invoke("the media i tried to upload did not upload...");
                return;
            }

            string[]      s     = new string[] { me.Media_Id };
            int           tries = 0;
            TwitterStatus tweetvalue;

            do
            {
                tries++;
                Task <TwitterAsyncResult <TwitterStatus> > o;
                var added          = $"\n\n{tweet.sourceurl} #abigailwilliams #abbybot";
                int tweetCharLimit = 240;

                int characterLimit = tweetCharLimit - added.Length;
                var chrsToRemove   = tweet.message.Length - characterLimit;
                //string manipulation
                StringBuilder sb = new StringBuilder(tweet.message);
                if (chrsToRemove > 0)
                {
                    sb.Remove((sb.Length) - chrsToRemove, chrsToRemove);
                    sb.Remove(sb.Length - 3, 3).Append("...");
                }
                sb.Append(added);


                var containsTwitter  = tweet.sourceurl.Contains("twitter");
                var sendTweetOptions = containsTwitter ?
                                       new SendTweetOptions {
                    Status = sb.ToString()
                } :
                new SendTweetOptions {
                    Status = sb.ToString(), MediaIds = s
                };
                o = Twitter.ts.SendTweetAsync(sendTweetOptions);

                TwitterAsyncResult <TwitterStatus> tweeto = await o;


                string a = tweeto?.Response?.Error?.Message switch {
                    "Status is a duplicate." => await Archive(),
                    _ => tweeto?.Response?.Error?.Message
                };
                if (a == "archived")
                {
                    onFail?.Invoke("twitter said i already posted that tweet");
                    return;
                }
                if (a != null)
                {
                    Console.WriteLine(a);
                }
                tweetvalue = tweeto.Value;
            } while ((tweetvalue == null) && (tries <= 3));

            if ((tweetvalue == null) || (tries >= 3))
            {
                await Archive();

                onFail?.Invoke("no tweet was posted.");
                return;
            }

            if (tweetvalue != null)
            {
                Abbybot.print("sent tweet");
                onSucceed?.Invoke();
                SaveTweet(tweetvalue, tweet);
            }

            await Archive();

            if (tweetvalue == null)
            {
                await SendTweet();

                if (tellnano)
                {
                    await c.SendMessageAsync("I'm done working nano");

                    PingAbbybotClock.o = 1;
                }
                return;
            }
            if (tellnano)
            {
                await c.SendMessageAsync("I'm done working nano");

                PingAbbybotClock.o = 1; //6 is the working state
            }
            async Task <string> Archive()
            {
                try {
                    await TweetArchiveSql.Add(tweet, true);

                    await TweetQueueSql.Remove(tweet);

                    return("archived");
                } catch (Exception e) {
                    return($"Failed to archive {e}");
                }
            }
        }
Exemplo n.º 16
0
 static void P(object st)
 {
     Abbybot.print($"[Tweet Sender Core]: {st}");
 }