Exemplo n.º 1
0
        public async Task <bool> SetMouseToBobber(BotSession session, BobbyLocation bobberPos, CancellationToken cancellationToken)  // move mouse to previous recorded position and check shape
        {
            if (!await MoveMouseAndCheckCursor(bobberPos.X, bobberPos.Y, cancellationToken, 1))
            {
                Log.Information("Bobber lost. ({bx},{by})", bobberPos.X, bobberPos.Y);
                const int  fixr = 24;
                Win32.Rect scanArea;
                scanArea.Left   = bobberPos.X - fixr;
                scanArea.Right  = bobberPos.X + fixr;
                scanArea.Top    = bobberPos.Y - fixr;
                scanArea.Bottom = bobberPos.Y + fixr;
                // initiate a small-area search for bobber
                var loc = await LookForBobberSpiralImpl(session, scanArea, 4, 1, cancellationToken);

                if (loc != null)
                {
                    // search was successful
                    Log.Information("Bobber found. ({bx},{by})", loc.X, loc.Y);
                    return(true);
                }

                Log.Information("Bobber lost. ({bx},{by})", 0, 0);
                return(false);
            }
            return(true);
        }
        public async Task <IActionResult> Post(
            [FromRoute] string botUsername,
            [FromBody] Update update,
            [FromServices] IDictionary <string, BotSession> sessions,
            [FromServices] ILogger logger)
        {
            BotContext context = null;
            BotSession session = null;

            try
            {
                if (update == null)
                {
                    throw new ArgumentException("update is null!");
                }
                sessions.TryGetValue(botUsername, out session);
                if (session == null)
                {
                    throw new ArgumentException("session is null, bot token is not registered!");
                }
                context = new BotContext(null, session, update);
                await session.Router.Route(context);
            }
            catch (Exception ex)
            {
                logger.Log(ex, context?.RouteData);
            }
            return(Ok()); // Suppress Errors ...
        }
Exemplo n.º 3
0
        public async Task <BobbyLocation> LookForBobber(BotSession session, CancellationToken cancellationToken)
        {
            Win32.Rect scanArea;
            if (!Properties.Settings.Default.customScanArea)
            {
                scanArea.Left   = _wowRectangle.X + _wowRectangle.Width / 5;
                scanArea.Right  = _wowRectangle.X + _wowRectangle.Width / 5 * 4;
                scanArea.Top    = _wowRectangle.Y + _wowRectangle.Height / 4;
                scanArea.Bottom = _wowRectangle.Y + _wowRectangle.Height / 4 * 3;
                //Log.Information("Using default area");
            }
            else
            {
                scanArea.Left   = Properties.Settings.Default.minScanXY.X;
                scanArea.Top    = Properties.Settings.Default.minScanXY.Y;
                scanArea.Right  = Properties.Settings.Default.maxScanXY.X;
                scanArea.Bottom = Properties.Settings.Default.maxScanXY.Y;
                //Log.Information("Using custom area");
            }
            Log.Information($"Scanning area: {scanArea.Left} , {scanArea.Top} , {scanArea.Right} , {scanArea.Bottom} cs: {session.BobbyLocations.Count()}");

            foreach (var dp in PointOfScreenDifferences())
            {
                if (await MoveMouseAndCheckCursor(dp.X, dp.X, cancellationToken, 2))
                {
                    Log.Information("Bobber imagescan hit. ({bx},{by})", dp.X, dp.X);
                    return(dp);
                }
            }

            // utilize previous hits
            foreach (var location in session.BobbyLocations)
            {
                // do something with item.Key and item.Value
                if (await MoveMouseAndCheckCursor(location.X, location.Y, cancellationToken, 2))
                {
                    location.Hits++;
                    Log.Information("Bobber position cache hit. ({bx},{by})", location.X, location.Y);
                    return(location);
                }
            }

            var           rnd = new Random();
            BobbyLocation loc;

            _aScanningSteps = rnd.Next(Properties.Settings.Default.ScanningStepsLow, Properties.Settings.Default.ScanningStepsHigh);
            if (Properties.Settings.Default.AlternativeRoute)
            {
                loc = await LookForBobberSpiralImpl(session, scanArea, _aScanningSteps, Properties.Settings.Default.ScanningRetries, cancellationToken);
            }
            else
            {
                loc = await LookForBobberImpl(session, scanArea, _aScanningSteps, Properties.Settings.Default.ScanningRetries, cancellationToken);
            }

            Log.Information("Bobber scan finished. ({bx},{by})", loc?.X, loc?.Y);
            return(loc);
        }
Exemplo n.º 4
0
 public async virtual void Execute(Message message, BotActivity bot, BotSession session)
 {
     if (!String.IsNullOrWhiteSpace(Response.Answer))
     {
         await bot.SendTextMessageAsync(new SendMessageArgs()
         {
             ChatId = message.Chat.Id, Answer = Response.Answer
         });
     }
 }
Exemplo n.º 5
0
        private async Task <BobbyLocation> LookForBobberSpiralImpl(BotSession session, Win32.Rect scanArea, int steps, int retries, CancellationToken cancellationToken)
        {
            var xposstep = (scanArea.Right - scanArea.Left) / steps;
            var yposstep = (scanArea.Bottom - scanArea.Top) / steps;
            var xoffset  = xposstep / retries;
            var yoffset  = yposstep / retries;

            for (var tryCount = 0; tryCount < retries; ++tryCount)
            {
                var x = (scanArea.Left + scanArea.Right) / 2 + xoffset * tryCount;
                var y = (scanArea.Top + scanArea.Bottom) / 2 + yoffset * tryCount;

                for (var i = 0; i <= 2 * steps; i++)
                {
                    for (var j = 0; j <= i / 2; j++)
                    {
                        int dx, dy;
                        if (i % 2 == 0)
                        {
                            if (i / 2 % 2 == 0)
                            {
                                dx = xposstep;
                                dy = 0;
                            }
                            else
                            {
                                dx = -xposstep;
                                dy = 0;
                            }
                        }
                        else
                        {
                            if (i / 2 % 2 == 0)
                            {
                                dx = 0;
                                dy = yposstep;
                            }
                            else
                            {
                                dx = 0;
                                dy = -yposstep;
                            }
                        }
                        x += dx;
                        y += dy;
                        if (await MoveMouseAndCheckCursor(x, y, cancellationToken, 1))
                        {
                            return(session.BobbyLocations.Add(x, y));
                        }
                    }
                }
            }

            return(null);
        }
Exemplo n.º 6
0
        public void AddBotSession(int BotUserID, int TalonID, int AisMFCOfficeID, string ServiceName)
        {
            var session = new BotSession();

            session.TalonID        = TalonID;
            session.BotUserID      = BotUserID;
            session.AisMFCOfficeID = AisMFCOfficeID;
            session.ServiceName    = ServiceName;
            session.StartTime      = DateTime.Now;
            BotSession.Add(session);
        }
Exemplo n.º 7
0
        private static bool ValidateMedia(BotSession session, YoutubeResource resource)
        {
            switch (ValidateMedia(resource))
            {
            case ValidateCode.Ok: return(true);

            case ValidateCode.Restricted: session.Write("The video cannot be played due to youtube restrictions."); return(false);

            case ValidateCode.Timeout: session.Write("No connection could be established to youtube. Please try again later."); return(false);

            case ValidateCode.UnknownError: session.Write("Unknown error occoured"); return(false);

            default: throw new InvalidOperationException();
            }
        }
Exemplo n.º 8
0
        private async Task <BobbyLocation> LookForBobberImpl(BotSession session, Win32.Rect scanArea, int steps, int retries, CancellationToken cancellationToken)
        {
            var xposstep = (scanArea.Right - scanArea.Left) / steps;
            var yposstep = (scanArea.Bottom - scanArea.Top) / steps;
            var xoffset  = xposstep / retries;

            for (var tryCount = 0; tryCount < retries; ++tryCount)
            {
                for (var x = scanArea.Left + xoffset * tryCount; x < scanArea.Right; x += xposstep)
                {
                    for (var y = scanArea.Top; y < scanArea.Bottom; y += yposstep)
                    {
                        if (await MoveMouseAndCheckCursor(x, y, cancellationToken, 1))
                        {
                            return(session.BobbyLocations.Add(x, y));
                        }
                    }
                }
            }
            return(null);
        }
Exemplo n.º 9
0
        public static IServiceCollection AddBotMvc(this IServiceCollection services)
        {
            // use your own implementation of ILogger ...
            var logger = new Logger();

            // use PerSecondScheduler to throttle the outgoing messages to 30 messages per second using a multi-level priority queue...
            var scheduler = new PerSecondScheduler(logger, tasksCount: 30, inSeconds: 1);

            // if your controllers are in a differant assembly change it here ...

            var controllersAssembly = Assembly.GetEntryAssembly();
            // var controllersAssembly = typeof(Controllers.HelloController).Assembly

            var router = new BotRouter(
                factory: new BotControllerFactory(scheduler),
                controllersAssembly: controllersAssembly);

            services.AddSingleton <ILogger>(logger);
            services.AddSingleton(router);
            services.AddSingleton(scheduler);

            // Key-value pair of botUsername : BotSession
            var tokens   = GetTokens();
            var sessions = new Dictionary <string, BotSession>();

            foreach (var token in tokens)
            {
                var session = new BotSession(new TelegramBotClient(token), router, logger, token);
                if (registerCertificate)
                {
                    session.RegisterCertificate(
                        certificateFilePath,
                        Path.Combine(publicBaseUrl, session.Username)).Wait();
                }
                sessions.Add(session.Username, session);
            }
            services.AddSingleton <IDictionary <string, BotSession> >(sessions);
            return(services);
        }
Exemplo n.º 10
0
		private static bool ValidateMedia(BotSession session, YoutubeResource resource)
		{
			switch (ValidateMedia(resource))
			{
			case ValidateCode.Ok: return true;
			case ValidateCode.Restricted: session.Write("The video cannot be played due to youtube restrictions."); return false;
			case ValidateCode.Timeout: session.Write("No connection could be established to youtube. Please try again later."); return false;
			case ValidateCode.UnknownError: session.Write("Unknown error occoured"); return false;
			default: throw new InvalidOperationException();
			}
		}
Exemplo n.º 11
0
        public async Task <IActionResult> GetSessions(int?year, string location)
        {
            if (year.HasValue == false)
            {
                year = DateTime.Now.Year;
            }

            string url = $"https://github.com/punitganshani/azurebootcamp-data/raw/master/{year}/locations/{location}/data.json";

            using (HttpClient client = new HttpClient())
                using (HttpResponseMessage response = await client.GetAsync(url))
                    using (HttpContent content = response.Content)
                    {
                        var contents = await content.ReadAsStringAsync();

                        var locationInfo = JsonConvert.DeserializeObject <LocationInfo>(contents);

                        DateTime eventDate = DateTime.ParseExact(locationInfo.Event.Date, "dd-MM-yyyy", CultureInfo.InvariantCulture);

                        List <BotSession> sessions = new List <Models.BotSession>();
                        foreach (var track in locationInfo.Tracks)
                        {
                            foreach (var current in track.Sessions)
                            {
                                if (current.Speaker == null)
                                {
                                    continue;
                                }
                                if (current.SessionId == "TBD" || current.Title == "TBD")
                                {
                                    continue;
                                }
                                if (sessions.Any(x => x.Code == current.SessionId))
                                {
                                    continue;                                         // avoid dupes
                                }
                                var viewSession = new BotSession();
                                viewSession.Code        = current.SessionId;
                                viewSession.Name        = current.Title;
                                viewSession.SessionType = track.Name.Replace("Track", string.Empty).Trim();
                                var timeRange = current.Time.Split(new[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                                var start     = DateTime.ParseExact(timeRange[0].Trim(), "h:mm tt", CultureInfo.InvariantCulture);
                                var end       = DateTime.ParseExact(timeRange[1].Trim(), "h:mm tt", CultureInfo.InvariantCulture);
                                viewSession.DateTime_Start = new DateTime(eventDate.Year, eventDate.Month, eventDate.Day, start.Hour, start.Minute, 0);
                                viewSession.FinishDateTime = new DateTime(eventDate.Year, eventDate.Month, eventDate.Day, end.Hour, end.Minute, 0).ToString("dd-MM-yyyy h:mm:ss tt");
                                viewSession.StartDateTime  = viewSession.DateTime_Start.ToString("dd-MM-yyyy h:mm:ss tt");
                                viewSession.Room           = current.Room;
                                viewSession.Presenters     = new List <BotPresenter>();
                                viewSession.Description    = current.Speaker.Description;

                                try
                                {
                                    var parts = current.Speaker.Name.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
                                    viewSession.Presenters.Add(new BotPresenter
                                    {
                                        FirstName = parts[0],
                                        LastName  = parts[1]
                                    });
                                }
                                catch
                                {
                                    viewSession.Presenters.Add(new BotPresenter {
                                        FirstName = current.Speaker.Name
                                    });
                                }


                                sessions.Add(viewSession);
                            }
                        }


                        return(Json(sessions));
                    }
        }
Exemplo n.º 12
0
        /// <summary>
        /// Выполнение функции
        /// </summary>
        /// <param name="update"></param>
        /// <param name="botName"></param>
        /// <returns></returns>
        public async Task ExecuteFunctionAsync(Update update, string botName)
        {
            bool        executed = false;
            BotActivity bot      = BotStorage.ActivityBots.FirstOrDefault(b => b.Name == botName);

            if (bot != null)
            {
                BotSession session = await GetSessionByUserIdAsync(update.Message.From.Id);

                // если сессии с этим клиентом нет, создаем новую
                if (session == null)
                {
                    session = new BotSession()
                    {
                        BotId                  = bot.Id,
                        LastActivity           = DateTime.Now,
                        NextFunctionId         = 0,
                        UserId                 = update.Message.From.Id,
                        CurrentCommandFunction = null
                    };
                    context.Sessions.Add(session);
                }

                // функционал бота
                Functional functional = await bot.GetFunctionalAsync();

                // указатель на следующую функцию
                int functionId = session.NextFunctionId;

                // текущая командная функция
                string curBotComFunct = session.CurrentCommandFunction;

                string message = update.Message.Text.ToLower();

                if (message == "cmds")
                {
                    string commands = "";
                    foreach (var func in bot.Functions)
                    {
                        commands += func.Command + " " + func.InputFunctions.Count();
                    }
                    await bot.SendTextMessageAsync(new SendMessageArgs()
                    {
                        ChatId = update.Message.Chat.Id, Answer = "Доступные команды: " + commands + " "
                    });

                    executed = true;
                }
                if (curBotComFunct == null)
                {
                    // выполнение по команде

                    foreach (CommandFunction func in bot.Functions)
                    {
                        string funcCommand = func.Command;
                        if (message.Contains(funcCommand.ToLower()))
                        {
                            func.Execute(update.Message, bot, session);
                            executed = true;
                            // после выполенени командной функции, проверяем следующую на авто
                            var inputFunctions = bot.GetInputFunctions(functional, funcCommand);
                            if (inputFunctions != null)
                            {
                                int inputFunctionsCount = inputFunctions.Count();
                                if (inputFunctionsCount > 0)
                                {
                                    // если функции есть, устанавливам имя на текущую и смотрим, авто ли следующая
                                    session.CurrentCommandFunction = funcCommand;
                                    session.NextFunctionId         = 0;
                                    InputFunction nextFunction = bot.GetInputFunction(functional, funcCommand, session.NextFunctionId);
                                    // пока идут авто функции, выполняем их
                                    while (nextFunction != null && nextFunction.IsAuto)
                                    {
                                        var funct = nextFunction.GetAsFunction();
                                        await funct.ExecuteAsync(bot, new SendMessageArgs()
                                        {
                                            ChatId = update.Message.Chat.Id, Answer = "Hello!", Message = message
                                        });

                                        session.NextFunctionId = IncId(session.NextFunctionId, inputFunctionsCount);
                                        await context.SaveChangesAsync();

                                        // если при выполнении авто функций мы выполнили все функции, выходим из командной функции
                                        if (session.NextFunctionId == 0)
                                        {
                                            session.CurrentCommandFunction = null;
                                            break;
                                        }
                                        nextFunction = bot.GetInputFunction(functional, curBotComFunct, session.NextFunctionId);
                                    }
                                    // если первая функция не авто, то остается имя текущей командной функции и ссылка на первую функцию
                                }
                            }
                            break;
                        }
                    }
                }
                else
                {
                    // количество фукнций в цепочке
                    var cmndf = (await bot.GetFunctionalAsync()).CommandFunctions.FirstOrDefault(f => f.Command == curBotComFunct);
                    if (cmndf != null)
                    {
                        var fus = cmndf.InputFunctions;
                        if (fus != null)
                        {
                            int inputFunctionsCount = fus.Count();
                            if (functionId < inputFunctionsCount)
                            {
                                var function = bot.Functions.FirstOrDefault(f => f.Command == curBotComFunct).InputFunctions[functionId];
                                //InputFunction function = bot.GetInputFunction(functional, curBotComFunct, functionId);
                                if (function != null)
                                {
                                    await function.ExecuteAsync(bot, new SendMessageArgs()
                                    {
                                        ChatId = update.Message.Chat.Id, AuthorId = update.Message.From.Id, Message = message
                                    });

                                    executed = true;
                                    // установление ссылки на след функцию
                                    session.NextFunctionId = IncId(functionId, inputFunctionsCount);
                                    if (session.NextFunctionId == 0)
                                    {
                                        session.CurrentCommandFunction = null;
                                    }
                                    else
                                    {
                                        //// если следующая функция авто, вызываем сразу
                                        InputFunction nextFunction = bot.GetInputFunction(functional, curBotComFunct, session.NextFunctionId);
                                        while (nextFunction != null && nextFunction.IsAuto)
                                        {
                                            var funct = nextFunction.GetAsFunction();
                                            await funct.ExecuteAsync(bot, new SendMessageArgs()
                                            {
                                                ChatId = update.Message.Chat.Id, Answer = "Hello!", Message = message
                                            });

                                            session.NextFunctionId = IncId(session.NextFunctionId, inputFunctionsCount);
                                            // если при выполнении авто функций мы выполнили все функции, выходим из командной функции
                                            if (session.NextFunctionId == 0)
                                            {
                                                session.CurrentCommandFunction = null;
                                                break;
                                            }
                                            nextFunction = bot.GetInputFunction(functional, curBotComFunct, session.NextFunctionId);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                await context.SaveChangesAsync();

                if (!executed)
                {
                    string answer = "Упс, эту команду я не понимаю :)";
                    if (message.Contains("/start"))
                    {
                        answer = "Здравствуйте! Рад встрече :)";
                    }
                    else
                    {
                        await bot.SendTextMessageAsync(new SendMessageArgs()
                        {
                            ChatId = update.Message.Chat.Id, Answer = answer
                        });
                    }
                }
            }
        }
Exemplo n.º 13
0
 public ExecutionInformation(BotSession session, TextMessage textMessage, Lazy <bool> isAdmin)
 {
     Session     = session;
     TextMessage = textMessage;
     IsAdmin     = isAdmin;
 }
Exemplo n.º 14
0
 public ExecutionInformation(BotSession session, TextMessage textMessage, Lazy<bool> isAdmin)
 {
     Session = session;
     TextMessage = textMessage;
     IsAdmin = isAdmin;
 }