Example #1
0
        public Plugin(string DllFile)
        {
            DllFileName = DllFile;

            try { assemblyName = AssemblyName.GetAssemblyName(DllFile); }
            catch (Exception e) { Logger.LogFatal("While loading Plugin " + DllFile + " threw getting assemblyname: " + e); throw e; }

            try { assembly = Assembly.Load(assemblyName); }
            catch (Exception e) { Logger.LogFatal("While loading Plugin " + DllFile + " threw loading assembly: " + e); throw e; }

            if (assembly == null)
            {
                Logger.LogFatal("While loading Plugin " + DllFile + " assembly is null"); throw new NullAssemplyPluginException();
            }

            try { types = assembly.GetTypes(); }
            catch (Exception e) { Logger.LogFatal("While loading Plugin " + DllFile + " failed getting it's types: " + e); throw e; }

            foreach (Type type in types)
            {
                int t = types.Count();
                int i = 1;

                if (type.IsClass)
                {
                    if (type.GetInterface(typeof(IDreadBotPlugin).FullName) != null)
                    {
                        try { plugin = (IDreadBotPlugin)Activator.CreateInstance(type); }
                        catch (Exception e) { Logger.LogFatal("Failed to Activate Plugin instance. " + DllFileName + "\r\nPlugin Will be Skipped. Exception: " + e); throw e; }

                        try
                        {
                            plugin.Init();
                            PluginID = plugin.PluginID;
                            break;
                        }
                        catch (Exception e) { Logger.LogFatal("The Plugin " + DllFile + "failed to Activate and will be skipped. The Exception is Below\r\n\r\n" + e); throw e; }
                    }
                }

                if (i == t)
                {
                    if (plugin == null)
                    {
                        Logger.LogFatal("The Plugin " + DllFile + "does not contain a IDreadBotPlugin interface type and will be skipped.");
                        throw new NoLoadableInterfacesException();
                    }
                }
                i++;
            }
        }
Example #2
0
        internal static void Welcome()
        {
            Console.WriteLine("Welcome to DreadBot!\r\nIn order to setup your bot, you will need an access token provided by @BotFather on Telegram.\r\n");
            Console.Write("Please enter your token here and press enter: ");

            RunningConfig = new BotConfig();

            RunningConfig.token = Console.ReadLine();
            Database.SaveConfig();

            Console.Write("Verifying token...");

            Result <WebhookInfo> res = null;

            res = Methods.getWebhookInfo();
            if (!res.ok)
            {
                Logger.LogFatal(res.description);
            }
            else
            {
                webhookinfo = res.result;
            }


            Result <User> meres = null;

            meres = Methods.getMe();
            if (!meres.ok)
            {
                Logger.LogFatal(meres.description);
                return;
            }
            else
            {
                Me = meres.result;
            }


            if (webhookinfo == null || Me == null)
            {
                Console.WriteLine("Nope.\n\nTheres a problem with the accesstoken. Please test your token in a web browser.\r\n\r\nhttps://api.telegram.org/bot" + RunningConfig.token + "/getMe\r\n\r\nIf you still have problems, verify your token is correct from @BotFather.\r\nPress any key to exit...");
                Console.ReadKey();
                Database.DisposeDB();
                System.IO.File.Delete(Environment.CurrentDirectory + @"Dreadbot.db");
                Environment.Exit(Environment.ExitCode);
            }

            Console.WriteLine("Verified!\r\n\r\nBelow are the details to the bot, and its current settings.");

            Console.WriteLine("Bot ID: " + Me.id);
            Console.WriteLine("Bot Username: @" + Me.username);
            Console.WriteLine("Bot First Name: " + Me.first_name);
            Console.WriteLine("Bot Last Name: " + Me.last_name + "\r\n\r\n");
            Console.Title = "DreadBot: @" + Me.username;

            if (string.IsNullOrEmpty(webhookinfo.url))
            {
                Console.WriteLine("WebHook Status: Disabled");
                RunningConfig.GetupdatesMode = true;
                Database.SaveConfig();
            }
            else
            {
                Console.WriteLine("WebHook Status: Enabled?!?!");
                RunningConfig.GetupdatesMode = false;
                Database.SaveConfig();
            }
        }
Example #3
0
        static void Main()
        {
            #region Bot Initialization Phase

            AppDomain.CurrentDomain.ProcessExit += new EventHandler(ExitCleanUp);

            Database.Init();

            Result <User> res = null;
            while (res == null)
            {
                res = Methods.getMe();
                if (res == null)
                {
                    Logger.LogError("Error getting bot info. Reattempting..");
                }
                else if (!res.ok)
                {
                    Logger.LogFatal("Error getting bot info (" + res.errorCode + ") " + res.description);
                    Logger.LogFatal("Press anykey to terminate...");
                    Console.ReadKey();
                    Environment.Exit(-1);
                }
            }

            Configs.Me = res.result;
            Result <WebhookInfo> webres = Methods.getWebhookInfo();
            if (!webres.ok)
            {
                Logger.LogFatal("Error getting bot info: " + webres.description);
                Environment.Exit(-1);
            }
            Configs.webhookinfo = webres.result;

            ChatCaching.Init();

            PluginManager.Init();

            Cron.CronInit();

            if (Configs.RunningConfig.Owner == 0)
            {
                Console.WriteLine("There is no owner assigned to this bot.\r\nPlease send me the command below to claim ownership.\r\nThis token will be deleted once you use it.\r\n\r\n");
                Console.WriteLine("/token " + Utilities.CreateAdminToken(true));
            }

            if (Configs.RunningConfig.AdminChat < 0 || Configs.RunningConfig.AdminChat > 0)
            {
                string text = "**DreadBot Started**\n" + Utilities.NormalTime(Utilities.EpochTime()) + "\n\n" + PluginManager.getPluginList();
                Methods.sendMessage(Configs.RunningConfig.AdminChat, text);
            }

            Console.Title = "DreadBot v" + Configs.Version + " @" + Configs.Me.username;
            Console.WriteLine(PluginManager.getPluginList() + "\n");
            Console.WriteLine("DreadBot Loaded, and Started!\n");

            if (!String.IsNullOrEmpty(Configs.webhookinfo.url))
            {
                Configs.RunningConfig.GetupdatesMode = false;
            }                                                                                                     //WebHook is enabled. Launch in Webhook mode.

            #endregion

            while (true)
            {
                #region Main GetUpdates Loop

                if (Configs.RunningConfig.GetupdatesMode) //GetUpdates Mode
                {
                    Update[] updates = null;
                    if (UpdateId == 0)
                    {
                        if (Configs.webhookinfo.pending_update_count > 3)
                        {
                            Logger.LogInfo("Playing catchup; " + Configs.webhookinfo.pending_update_count + " updates behind.");
                        }
                        updates = Methods.getFirstUpdates(60);
                        if (updates == null || updates.Length < 1)
                        {
                            continue;
                        }
                    }
                    else
                    {
                        GetUpdates request = new GetUpdates()
                        {
                            timeout = 20,
                            offset  = UpdateId + 1,
                            limit   = Configs.RunningConfig.GULimit
                        };
                        Result <Update[]> updatesres = Methods.getUpdates(request);
                        if (updatesres == null || !updatesres.ok)
                        {
                            Logger.LogError("Error fetching updates: (" + updatesres.errorCode + ") " + updatesres.description);
                            Thread.Sleep(10000);
                            continue;
                        }
                        updates = updatesres.result;
                    }
                    if (updates.Length < 1)
                    {
                        continue;
                    }
                    foreach (Update update in updates)
                    {
                        UpdateId = update.update_id;
                        //Console.WriteLine("Parsing Update: " + UpdateId);
                        Events.ParseUpdate(update);
                    }
                }

                #endregion

                #region WebHook Loop

                else // Webhook mode
                {
                    //// Webhook Not Implemented.
                    Logger.LogError("DreadBot Cannot continue:\n\nWebhook Mode is enabled for this bot. This version of DreadBot does not have Webhook support and will close.\n\n");
                    ExitCleanUp(null, null);
                    Thread.Sleep(10000);
                    throw new NotImplementedException("This version of DreadBot does not have Webhook support and will terminate.");
                }

                #endregion
            }
        }
Example #4
0
        //This method is called by EVERY Telegram method. This is used to handle Most error checking, and the variable 'result' object is returned to the method that called this.
        private static Result <T> sendRequest <T>(Method method, string payload = "", string payloadType = "application/json", MultipartFormDataContent dataPayload = null)
        {
            bool connected = false;

            while (!connected)
            {
                try
                {
                    Ping        myPing      = new Ping();
                    String      host        = "api.telegram.org";
                    byte[]      buffer      = new byte[32];
                    int         timeout     = 1000;
                    PingOptions pingOptions = new PingOptions();
                    PingReply   reply       = myPing.Send(host, timeout, buffer, pingOptions);
                    connected = (reply.Status == IPStatus.Success);
                    if (!connected)
                    {
                        Logger.LogError("Connection Error. Cannot Connect to Telegram.");
                        continue;
                    }
                }
                catch (Exception)
                {
                    Logger.LogError("Connection Error. Cannot Connect to Telegram.");
                    Thread.Sleep(10000);
                    continue;
                }
            }

            //Console.WriteLine(method + " | " + payload);
            string              uriMethod = "https://api.telegram.org/bot" + Configs.RunningConfig.token + "/" + method;
            HttpClient          client    = new HttpClient();
            HttpResponseMessage response  = null;
            int tryCount = 6;

            while (response == null)
            {
                if (tryCount == 0)
                {
                    Logger.LogFatal("Number of retries to send request exceeded. Breaking out.");
                    return(null);
                }
                try
                {
                    //Console.WriteLine(method + " Timeout: " +client.Timeout);
                    if (dataPayload == null)
                    {
                        StringContent content = new StringContent(payload, Encoding.UTF8, payloadType);
                        response = Task.Run(() => client.PostAsync(uriMethod, content)).Result;
                    }
                    else
                    {
                        //string a = Task.Run(() => dataPayload.ReadAsStringAsync()).Result;
                        response = Task.Run(() => client.PostAsync(uriMethod, dataPayload)).Result;
                    }
                }
                catch (ObjectDisposedException e)
                {
                    Logger.LogError("(" + method + ") Object Disposed before it could be used: " + e + "\nBreaking out.");
                    return(null);
                }
                catch (Exception e)
                {
                    Logger.LogError("(" + method + ") Socket Exception: " + e + "\nWaiting 60 seconds before next attempt.");
                    Thread.Sleep(60000);
                }

                tryCount--;
            }
            client.Dispose();
            Stream stream = Task.Run(() => response.Content.ReadAsStreamAsync()).Result;
            DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(Result <T>));
            Result <T> result = (dcjs.ReadObject(stream)) as Result <T>;

            if (!response.IsSuccessStatusCode) //HTTP Error handling
            {
                Logger.LogFatal("Http Status Code: (" + response.StatusCode + ") Reason:" + response.ReasonPhrase);
            }
            if (result == null)
            {
                Logger.LogError("Method Error: Result is null");
            }
            else if (!result.ok)
            {
                Logger.LogError("(" + result.errorCode + ") " + result.description);
            }
            return(result);
        }