// When the bot stops, output a final item-stats report so it is as up-to-date as can be private void FunkyBotStop(IBot bot) { // Issue final reports OutputReport(); PlayerMover.iTotalAntiStuckAttempts = 1; PlayerMover.vSafeMovementLocation = Vector3.Zero; PlayerMover.vOldPosition = Vector3.Zero; PlayerMover.iTimesReachedStuckPoint = 0; PlayerMover.timeLastRecordedPosition = DateTime.Today; PlayerMover.timeStartedUnstuckMeasure = DateTime.Today; hashUseOnceID = new HashSet<int>(); dictUseOnceID = new Dictionary<int, int>(); dictRandomID = new Dictionary<int, int>(); Bot.Stats.iMaxDeathsAllowed=0; Bot.Stats.iDeathsThisRun=0; initTreeHooks=false; //Total Stats Bot.BotStatistics.ItemStats.Update(); Bot.BotStatistics.GameStats.Update(); Bot.BotStatistics.ProfileStats.OutputReport(); RemoveHandlers(); ResetTreehooks(); }
public Sequence this[IBot.IBot bot] { get { var seq = new Sequence( new Decorator(ret => bot.isRunning, new TreeSharp.Action(ret => RunStatus.Success)), //first we must have a valid target new Decorator(ret => Util.Targeting.HasValidTarget(bot.CurrentTarget), new TreeSharp.Action(ret => RunStatus.Success)), //if we are already busy, don't continue. new Decorator(ret => !bot.isInAction, new TreeSharp.Action(ret => RunStatus.Success)), //send the attack action. new TreeSharp.Action(ret => { bot.Attack(bot.CurrentTarget); }), //wait for the action to complete (or we time out). new Wait(1, ret => bot.isInAction, new TreeSharp.Action(ret => RunStatus.Success)) ); return seq; } }
public bool Handle(ChatMessage message, IBot bot) { try { using (var _database = new TwitterNotifierSprocketRepository()) { _database.RecordActivity(message.FromUser); InviteUserIfNeccessary(message.FromUser, bot, _database); var twitterUsers = GetUserNamesFromMessage(message.Content, _database); var user = _database.FetchOrCreateUser(message.FromUser); if (twitterUsers.Count() > 0) { foreach (var u in twitterUsers) { if (ShouldNotifyUser(u.ScreenName, _database)) { NotifyUserOnTwitter(message, user, u); _database.MarkUserNotified(u.ScreenName); } } return true; } } } catch (Exception e) { bot.PrivateReply(message.FromUser, e.GetBaseException().Message); } return false; }
/// <summary>Runs it all.</summary> public void DoRun(IBot bot, IEnumerable<IInstruction> instructions) { if (bot == null) { throw new ArgumentNullException("bot"); } if (instructions == null) { throw new ArgumentNullException("instructions"); } var settings = new Settings(); var state = new GameState(); foreach (var instruction in instructions) { if (settings.Apply(instruction)) { bot.ApplySettings(settings); } else if (state.Apply(instruction)) { } else if (instruction is RequestMoveInstruction) { bot.Update(state); try { var response = bot.GetResponse(((RequestMoveInstruction)instruction).Time); Writer.WriteLine(response.Move); if (!String.IsNullOrEmpty(response.Log)) { Logger.WriteLine(response.Log); } } catch (Exception x) { Writer.WriteLine(new MoveInstruction(Move.Center)); Logger.WriteLine(x); } } } }
/// <summary>Runs the bot.</summary> public static void Run(IBot bot) { using (var platform = new ConsolePlatform()) { platform.DoRun(bot); } }
private static void CheckForkStatus(KeyValuePair<dynamic, dynamic> fork, IDictionary<string, string> existingForkStatus, IBot bot) { string id = fork.Key.ToString(); string url = fork.Value.ToString() + "/commits"; var commits = url.GetResponse<IEnumerable<dynamic>>().ToList(); bot.ProcessForkStatus(id, existingForkStatus, commits); }
public new IProcessingResult Command(IBot bot, IProcessingResult pr, IChatMessage msg, string cmd, string arg, string cmdOriginal, string argOriginal) { switch (cmd) { default: return pr; // core commands case "about": return About(bot, pr, arg); case "help": return Help(bot, pr, arg); case "commands": return GetCommandList(bot, pr, arg); case "uptime": return Uptime(bot, pr); case "modules": return Modules(bot, pr); case "edit": return Edit(pr, bot, msg, arg); case "unonebox": case "unbox": return Unonebox(pr, bot, msg, arg); case "undo": return Undo(bot, pr, arg); case "status": return Status(bot, pr); case "trust": return TrustedUsers(bot, pr, arg); case "ignore": return BannedUsers(bot, pr, arg); case "say": return Say(pr, arg); case "tell": return Tell(pr, arg); case "alias": return Alias(pr, bot, msg, arg); case "save": return Save(bot, pr, msg.UserID); case "shutdown": return Shutdown(bot, pr, arg, msg.UserID); // hoihoi-san borrowed case "google": return Google(pr, msg, arg); case "wiki": return Wiki(pr, msg, arg); case "urban": return Urban(pr, msg, arg); case "youtube": return Youtube(pr, msg, arg); case "weather": return Weather(pr, msg, arg); // advanfaged case "id": return ID(bot, pr, msg, arg); case "isch": return Isch(bot, pr, msg, arg); case "whois": case "what": case "last": return LastPostedImageID(bot, pr, msg, arg); // bonus case "hats": return Hats(pr); case "meme": return Meme(bot, pr, msg, arg); } }
public ASubBot(IBot bot) { this.InitializeComponent(); this.bot = bot; this.updateTimer = new System.Timers.Timer(); updateTimer.Elapsed += delegate { onTick(); }; }
//: base(bot, id, name, smiley, xPos, yPos, isGod, isMod, hasChat, coins, purple, isFriend, level) public Player(IBot bot, int id, string name, int smiley, double xPos, double yPos, bool isGod, bool isMod, bool hasChat, int coins, bool purple, bool isFriend, int level) { this.id = id; this.bot = bot; physicsPlayer = new PhysicsPlayer(bot, id, name, smiley, xPos, yPos, isGod, isMod, hasChat, coins, purple, isFriend, level); afkStopwatch.Start(); }
public BotRunner() { var botTemp = new Bot2(); botTemp.BotProfile = BotProfile.GetBotProfileFromDb(); bot = botTemp; authentication = new AuthenticationService(); }
private void FunkyBotStart(IBot bot) { if (!ErrorClickerThread.ThreadState.HasFlag(ThreadState.Running)) { ErrorClickerThread.Start(); DBLog.Info("[Funky] Error Clicking Thread Started."); } }
private static IEnumerable<string> GetAllUsersInSameRoomsAsJibber(IBot bot) { var rooms = GetRooms(bot); var users = rooms.SelectMany<dynamic, dynamic>(r => r.Users); var userNames = users.Select(u => u.Name); var distinctUserNames = userNames.Distinct().Cast<string>(); return distinctUserNames; }
public void Loaded(IPlugin plugin, IBot bot) { foreach(AliasData alias in Aliases) { IExpression aliasExpression = Parse(bot.Command, alias.Expression); Add(bot.Command, plugin, alias, aliasExpression, false); } }
public BlockMap(IBot bot, int width = 0, int height = 0) { backgroundMap = new Stack<IBlock>[width + 1, height + 1]; foregroundMap = new Stack<IBlock>[width + 1, height + 1]; currentForegroundMap = new int[width + 1, height + 1]; this.width = width; this.height = height; Reset(); }
public FurnitureManager(IBot bot) { this.bot = bot; furnitureTypes.Add("door", new FurnitureDoor(0, 0)); furnitureTypes.Add("switch", new FurnitureSwitch(0, 0)); furnitureTypes.Add("switchdoor", new FurnitureSwitchDoor(0, 0)); furnitureTypes.Add("empty", new FurnitureEmpty(0, 0)); furnitureTypes.Add("spawn", new FurnitureSpawn(0, 0)); }
public Minimap(IBot bot, int width, int height) : base(bot) { this.bot = bot; this.width = width; this.height = height; this.bitmap = new Bitmap(width, height); updateThread = new SafeThread(UpdateMinimap); updateThread.Start(); }
public HouseBuilding(IBot bot) : base(bot) { this.furnitureManager = new FurnitureManager(bot); this.houseManager = new HouseManager(bot); HouseType tinyHouse = new HouseType("tinyhouse", 7, 7, 46, 48, 541); tinyHouse.AddCost("stone", 25); HouseType smallHouse = new HouseType("smallhouse", 9, 9, 93, 93); smallHouse.AddCost("stone", 100); HouseType mediumHouse = new HouseType("mediumhouse", 11, 11, 1023, 1024); mediumHouse.AddCost("stone", 400); mediumHouse.AddCost("copper", 20); HouseType largeHouse = new HouseType("largehouse", 13, 13, 14, 1018, 505); largeHouse.AddCost("stone", 600); largeHouse.AddCost("iron", 30); HouseType veryLargeHouse = new HouseType("verylargehouse", 15, 15, 1021, 42); veryLargeHouse.AddCost("stone", 800); veryLargeHouse.AddCost("gold", 50); HouseType hugeHouse = new HouseType("hugehouse", 17, 17, 196, 195, 618); hugeHouse.AddCost("stone", 1000); hugeHouse.AddCost("copper", 50); hugeHouse.AddCost("iron", 50); hugeHouse.AddCost("gold", 50); HouseType weirdHouse = new HouseType("weirdhouse", 17, 5, 80, 82, 548); weirdHouse.AddCost("stone", 400); HouseType strangeHouse = new HouseType("strangehouse", 3, 15, 50, 156, 575); strangeHouse.AddCost("stone", 300); HouseType candyHouse = new HouseType("candyhouse", 11, 11, 67, 60, 539); candyHouse.AddCost("stone", 400); candyHouse.AddCost("copper", 50); HouseType basicHouse = new HouseType("basichouse", 11, 11, 9, 10, 501); basicHouse.AddCost("stone", 400); HouseType brickHouse = new HouseType("brickhouse", 11, 11, 1024, 1023, 647); brickHouse.AddCost("stone", 400); HouseType coinHouse = new HouseType("coinhouse", 5, 5, 41, 100, 581); coinHouse.AddCost("stone", 400); this.houseManager.RegisterHouseType(tinyHouse); this.houseManager.RegisterHouseType(smallHouse); this.houseManager.RegisterHouseType(mediumHouse); this.houseManager.RegisterHouseType(largeHouse); this.houseManager.RegisterHouseType(veryLargeHouse); this.houseManager.RegisterHouseType(hugeHouse); this.houseManager.RegisterHouseType(weirdHouse); this.houseManager.RegisterHouseType(strangeHouse); this.houseManager.RegisterHouseType(candyHouse); this.houseManager.RegisterHouseType(basicHouse); this.houseManager.RegisterHouseType(brickHouse); this.houseManager.RegisterHouseType(coinHouse); EnableTick(5000); }
public ModuleService(IBot bot) { this.bot = bot; this.storageCatalog = new AzureStorageCatalog(string.Empty, string.Empty); this.aggregateCatalog = new AggregateCatalog(this.storageCatalog); this.moduleContainer = new CompositionContainer(this.aggregateCatalog); this.moduleContainer.ExportsChanged += this.ModuleContainerOnExportsChanged; this.storageCatalog.Changed += this.StorageCatalogOnChanged; }
/// <summary>Runs it all.</summary> public void DoRun(IBot bot) { if (bot == null) { throw new ArgumentNullException("bot"); } var settings = new Settings(); var match = new GameState(settings); string line; while ((line = this.Reader.ReadLine()) != null) { #if !DEBUG try { #endif var instruction = Instruction.Parse(line); switch (instruction.InstructionType) { case InstructionType.Player: match.UpdatePlayer(instruction); HandleOpponentReaction(bot, match, instruction); if (match.Result != RoundResult.NoResult) { bot.Result(match); } break; case InstructionType.Match: match.UpdateMatch(instruction); break; case InstructionType.Settings: settings.Update(instruction); match.Update(settings); break; case InstructionType.Action: match.UpdateAction(instruction); var action = bot.Action(match); Writer.WriteLine(action); break; case InstructionType.None: case InstructionType.Output: default: break; } #if !DEBUG } catch (Exception x) { Console.Error.WriteLine(line); Console.Error.WriteLine(x); } #endif } }
public override void DoRun(IBot bot) { base.DoRun(bot); var log = Logger.ToString(); Console.Error.Write(log); if (log.Contains("Exception")) { Assert.Fail("The log output contains at least on exception."); } }
public void ExecuteTask(IBot bot, string baseUrl, string repositoryName) { var url = baseUrl.Append(ProjectWatchersFeed); var currentWatchers = url.GetResponse<IEnumerable<dynamic>>(); var existingWatchers = _settings.GetValue<IList<string>>(WatchersKey, () => new List<string>()); existingWatchers = bot.ProcessWatchers(repositoryName, existingWatchers, currentWatchers); _settings.Set(WatchersKey, existingWatchers); _settings.Save(); }
public void Loaded(IPlugin plugin, IBot bot) { foreach(MessageParserData data in Data) { Regex regex = ParseRegex(data.Pattern); IExpression expression = ParseExpression(bot.Command, data.Expression); Add(data, regex, expression, false); } _messageDisposable = bot.Messages.Subscribe(ParseMessage); }
public void Initialize(IBot bot) { DoMigrations(); if (!String.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["Application.Gravatar"])) { //bot.Gravatar(System.Configuration.ConfigurationManager.AppSettings["Application.Gravatar"]); } foreach (var r in this._database.OccupiedRooms) { bot.JoinRoom(r.Name); } }
public Zombie(int x, int y, IBot bot) { this.bot = bot; this.x = x; this.y = y; pathFinding = new PathFinding(); System.Timers.Timer updateTimer = new System.Timers.Timer(); updateTimer.Elapsed += delegate { Tick(); }; playerTickStopwatch.Start(); updateTimer.Start(); }
private void FillBotsInfoUI(IBot bot) { lblCharName.Text = bot.CharName; lblSkill.Text = bot.SkillPoint; lblGold.Text = bot.Gold; lblExp.Text = bot.Experience; lblLvl.Text = bot.Level; lblItems.Text = bot.PickItems; lblDied.Text = bot.DiedCount; lblLoop.Text = bot.LoopCount; lblStatus.Text = bot.Status.ToString(); lblExpPerHour.Text = bot.ExperiencePetHour; lblGoldPerHour.Text = bot.GoldPetHour; lblSkillPerHour.Text = bot.SkillPointPetHour; lblDCCount.Text = bot.DCCount.ToString(); lblTryConnectCount.Text = bot.TryConnectCount.ToString(); //pbCharHP.Minimum = bot.CharHPProgressBar[0]; //pbCharHP.Maximum = bot.CharHPProgressBar[1]; pbCharHP.Value = bot.CharHPProgressBar[2]; //pbCharMP.Minimum = bot.CharMPProgressBar[0]; //pbCharMP.Maximum = bot.CharMPProgressBar[1]; pbCharMP.Value = bot.CharMPProgressBar[2]; //pbCharExp.Minimum = bot.CharExpProgressBar[0]; //pbCharExp.Maximum = bot.CharExpProgressBar[1]; pbCharExp.Value = bot.CharExpProgressBar[2]; //pbCharBerzerg.Minimum = bot.CharBerzerkProgressBar[0]; //pbCharBerzerg.Maximum = bot.CharBerzerkProgressBar[1]; pbCharBerzerg.Value = bot.CharBerzerkProgressBar[2]; //pbPetHP.Minimum = bot.PetHPProgressBar[0]; //pbPetHP.Maximum = bot.PetHPProgressBar[1]; pbPetHP.Value = bot.PetHPProgressBar[2]; //pbPetHGP.Minimum = bot.PetHGPProgressBar[0]; //pbPetHGP.Maximum = bot.PetHGPProgressBar[1]; pbPetHGP.Value = bot.PetHGPProgressBar[2]; //pbTransHP.Minimum = bot.TransHPProgressBar[0]; //pbTransHP.Maximum = bot.TransHPProgressBar[1]; pbTransHP.Value = bot.TransHPProgressBar[2]; //if (tabControlBotInfo.SelectedTab == tabPageBotLog) //{ // lbBotLog.Items.Clear(); // lbBotLog.Items.AddRange(bot.StatusLogList.ToArray()); // //lbBotLog.SelectedIndex = lbBotLog.Items.Count - 1; //} }
private int zombieTime = 30; //seconds before zombie turns to human #endregion Fields #region Constructors public ZombiesSubbot(IBot bot) : base(bot) { // Adds the SubBot to the SubBot handler so the SubBot will get callbacks. bot.SubBotHandler.AddSubBot(this, true); if (this.HasTab) this.InitializeComponent(); // 10ms is the player physics. this.EnableTick(10); }
public VoicemailSprocketTest() { mockBot = new Mock<IBot>(); mockBot.Setup(b => b.Name).Returns(Jibbr); bot = mockBot.Object; dynamic room1 = new DynamicRoom() { Name = "room1", Users = new List<DynamicUser> { new DynamicUser() { Name = "Claire" }, new DynamicUser() { Name = "mads" } } }; dynamic room2 = new DynamicRoom() { Name = "room2", Users = new List<DynamicUser> { new DynamicUser() { Name = "Claire" }, new DynamicUser() { Name = "bryce" }, new DynamicUser() { Name = "vicky" } } }; mockBot.Setup(b => b.GetRooms()).Returns(new List<dynamic>() { room1, room2 }); voicemailSprocket = new VoicemailSprocket.VoicemailSprocket(); }
public override void OnPush(IBot bot, IPlayer player, House house, int dx, int dy) { int blockId = bot.Room.getBlock(0, X + 2 * dx, Y + 2 * dy).Id; if (blockId == 414 || blockId == 4) { int xx = X + 2 * dx + 1; int yy = Y + 2 * dy + 1; string text = "/teleport " + player.Name + " " + xx + " " + yy; if (player.Name == house.builder) bot.ChatSayer.Say(text); } }
public bool Handle(ChatMessage message, IBot bot) { var acceptedCommands = new string[] { bot.Name + " help", "@" + bot.Name + " help" }; if (acceptedCommands.Contains(message.Content.Trim())) { bot.PrivateReply(message.Sender, "A list of commands this bot currently supports:\n\thelp"); return true; } return false; }
public Room(IBot bot) : base(bot) { this.bot = bot; this.blockMap = new BlockMap(bot); this.blockDrawerPool = new BlockDrawerPool(bot, this); this.blockDrawer = blockDrawerPool.CreateBlockDrawer(15); this.blockDrawer.Start(); playerTickThread = new SafeThread(UpdatePhysics); EnableTick(50); }
/// <summary> /// Creates a turn context and runs the middleware pipeline for an incoming activity. /// </summary> /// <param name="httpRequest">The incoming HTTP request.</param> /// <param name="httpResponse">When this method completes, the HTTP response to send.</param> /// <param name="bot">The bot that will handle the incoming activity.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <exception cref="ArgumentNullException"><paramref name="httpRequest"/>, /// <paramref name="httpResponse"/>, or <paramref name="bot"/> is <c>null</c>.</exception> public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, CancellationToken cancellationToken = default) { if (httpRequest == null) { throw new ArgumentNullException(nameof(httpRequest)); } if (httpResponse == null) { throw new ArgumentNullException(nameof(httpResponse)); } if (bot == null) { throw new ArgumentNullException(nameof(bot)); } Dictionary <string, string> bodyDictionary; using (var bodyStream = new StreamReader(httpRequest.Body)) { bodyDictionary = TwilioHelper.QueryStringToDictionary(await bodyStream.ReadToEndAsync().ConfigureAwait(false)); } if (!_twilioClient.ValidateSignature(httpRequest, bodyDictionary)) { throw new Exception("WARNING: Webhook received message with invalid signature. Potential malicious behavior!"); } var activity = TwilioHelper.PayloadToActivity(bodyDictionary); // create a conversation reference using (var context = new TurnContext(this, activity)) { context.TurnState.Add("httpStatus", HttpStatusCode.OK.ToString("D")); await RunPipelineAsync(context, bot.OnTurnAsync, cancellationToken).ConfigureAwait(false); var statusCode = Convert.ToInt32(context.TurnState.Get <string>("httpStatus"), CultureInfo.InvariantCulture); var text = context.TurnState.Get <object>("httpBody") != null?context.TurnState.Get <object>("httpBody").ToString() : string.Empty; await TwilioHelper.WriteAsync(httpResponse, statusCode, text, Encoding.UTF8, cancellationToken).ConfigureAwait(false); } }
protected abstract void ProcessMatch(Match match, ChatMessage message, IBot bot);
/// <inheritdoc/> public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, CancellationToken cancellationToken = default) { if (httpRequest == null) { throw new ArgumentNullException(nameof(httpRequest)); } if (httpResponse == null) { throw new ArgumentNullException(nameof(httpResponse)); } if (bot == null) { throw new ArgumentNullException(nameof(bot)); } if (httpRequest.Method == HttpMethods.Get) { throw new NotImplementedException("web sockets is not yet implemented"); } else { // Deserialize the incoming Activity var activity = await HttpHelper.ReadRequestAsync <Activity>(httpRequest).ConfigureAwait(false); if (string.IsNullOrEmpty(activity?.Type)) { httpResponse.StatusCode = (int)HttpStatusCode.BadRequest; return; } // Grab the auth header from the inbound http request var authHeader = httpRequest.Headers["Authorization"]; try { // Process the inbound activity with the bot var invokeResponse = await ProcessActivityAsync(authHeader, activity, bot.OnTurnAsync, cancellationToken).ConfigureAwait(false); // write the response, potentially serializing the InvokeResponse await HttpHelper.WriteResponseAsync(httpResponse, invokeResponse).ConfigureAwait(false); } catch (UnauthorizedAccessException) { // handle unauthorized here as this layer creates the http response httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized; } } }
public Game(IBot crosses, IBot naughts, ArrayBoard board) : this(crosses, naughts) { this.board = board; }
public SlackController(SlackAdapter adapter, IBot bot) { _adapter = adapter; _bot = bot; }
/// <summary> /// Accepts an incoming webhook request, creates a turn context, /// and runs the middleware pipeline for an incoming TRUSTED activity. /// </summary> /// <param name="httpRequest">Represents the incoming side of an HTTP request.</param> /// <param name="httpResponse">Represents the outgoing side of an HTTP request.</param> /// <param name="bot">The code to run at the end of the adapter's middleware pipeline.</param> /// <param name="cancellationToken">A cancellation token that can be used by other objects /// or threads to receive notice of cancellation.</param> /// <returns>A task that represents the work queued to execute.</returns> /// <exception cref="AuthenticationException">The webhook receives message with invalid signature.</exception> public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, CancellationToken cancellationToken = default) { if (httpRequest.Query["hub.mode"] == HubModeSubscribe && _options.VerifyIncomingRequests) { await _facebookClient.VerifyWebhookAsync(httpRequest, httpResponse, cancellationToken).ConfigureAwait(false); return; } string stringifiedBody; using (var sr = new StreamReader(httpRequest.Body)) { stringifiedBody = await sr.ReadToEndAsync().ConfigureAwait(false); } if (!_facebookClient.VerifySignature(httpRequest, stringifiedBody) && _options.VerifyIncomingRequests) { await FacebookHelper.WriteAsync(httpResponse, HttpStatusCode.Unauthorized, string.Empty, Encoding.UTF8, cancellationToken).ConfigureAwait(false); throw new AuthenticationException("WARNING: Webhook received message with invalid signature. Potential malicious behavior!"); } FacebookResponseEvent facebookResponseEvent = null; facebookResponseEvent = JsonConvert.DeserializeObject <FacebookResponseEvent>(stringifiedBody); foreach (var entry in facebookResponseEvent.Entry) { var payload = entry.Changes.Count > 0 ? entry.Changes : entry.Messaging.Count > 0 ? entry.Messaging : entry.Standby.Count > 0 ? entry.Standby : new List <FacebookMessage>(); foreach (var message in payload) { message.IsStandby = entry.Standby.Count > 0; var activity = FacebookHelper.ProcessSingleMessage(message); using (var context = new TurnContext(this, activity)) { await RunPipelineAsync(context, bot.OnTurnAsync, cancellationToken).ConfigureAwait(false); } } } }
public ZoomController(ZoomAdapter adapter, IBot bot) { Adapter = adapter; Bot = bot; }
public SkillHandlerInstanceForTests(BotAdapter adapter, IBot bot, SkillConversationIdFactoryBase testConversationIdFactory, ICredentialProvider credentialProvider, AuthenticationConfiguration authConfig, IChannelProvider channelProvider = null, ILogger logger = null) : base(adapter, bot, testConversationIdFactory, credentialProvider, authConfig, channelProvider, logger) { }
public BotController(IBotFrameworkHttpAdapter httpAdapter, WebSocketEnabledHttpAdapter webSocketEnabledHttpAdapter, IBot bot) { _adapter = httpAdapter; _webSocketEnabledHttpAdapter = webSocketEnabledHttpAdapter; _bot = bot; }
public BotInfo(IBot bot) { Bot = bot; Abilities = new List <IBotAbility>(); }
void BotMain_OnStop(IBot bot) { Stop(); }
void BotMain_OnStart(IBot bot) { HandleTimer(); }
/// <summary> /// Initializes a new instance of the <see cref="BotController"/> class. /// </summary> /// <param name="adapter">The BotFramework adapter.</param> /// <param name="activityHandler">The underlying activity handler.</param> public BotController(IBotFrameworkHttpAdapter adapter, IBot activityHandler) { this.botFrameworkHttpAdapter = adapter; this.activityHandler = activityHandler; }
public void Init(IBot bot, ILoggerService logger) { }
int IBotRequestUnitProduction.RequestedProductionCount(IBot bot, string requestedActor) { return(queuedBuildRequests.Count(r => r == requestedActor)); }
public BotHostedService( ILogger <BotHostedService> logger, IBot bot) { _logger = logger; _bot = bot; }
public async Task ProcessAsync(HttpRequest httpRequest, HttpResponse httpResponse, IBot bot, CancellationToken cancellationToken = default) { if (httpRequest == null) { throw new ArgumentNullException(nameof(httpRequest)); } if (httpResponse == null) { throw new ArgumentNullException(nameof(httpResponse)); } if (bot == null) { throw new ArgumentNullException(nameof(bot)); } var route = GetRoute(httpRequest); if (route == null) { httpResponse.StatusCode = (int)HttpStatusCode.NotFound; return; } object result = null; var statusCode = (int)HttpStatusCode.OK; try { // grab the auth header from the inbound http request var authHeader = httpRequest.Headers["Authorization"]; var claimsIdentity = await JwtTokenValidation.ValidateAuthHeader(authHeader, _credentialsProvider, _channelProvider, "unknown").ConfigureAwait(false); switch (route.Method) { // [Route("/v3/conversations")] case ChannelApiMethods.CreateConversation: var parameters = HttpHelper.ReadRequest <ConversationParameters>(httpRequest); result = await _skillAdapter.CreateConversationAsync(claimsIdentity, route.Parameters["conversationId"].Value, parameters, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/activities/{activityId}")] case ChannelApiMethods.DeleteActivity: // TODO: ask Tom why we use the value from the route and not from the activity here. await _skillAdapter.DeleteActivityAsync(claimsIdentity, route.Parameters["conversationId"].Value, route.Parameters["activityId"].Value, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/members/{memberId}")] case ChannelApiMethods.DeleteConversationMember: await _skillAdapter.DeleteConversationMemberAsync(claimsIdentity, route.Parameters["conversationId"].Value, route.Parameters["memberId"].Value, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/activities/{activityId}/members")] case ChannelApiMethods.GetActivityMembers: result = await _skillAdapter.GetActivityMembersAsync(claimsIdentity, route.Parameters["conversationId"].Value, route.Parameters["activityId"].Value, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/members")] case ChannelApiMethods.GetConversationMembers: result = await _skillAdapter.GetConversationMembersAsync(claimsIdentity, route.Parameters["conversationId"].Value, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/pagedmembers")] case ChannelApiMethods.GetConversationPagedMembers: var pageSize = string.IsNullOrWhiteSpace(route.Parameters["pageSize"].Value) ? -1 : int.Parse(route.Parameters["pageSize"].Value, CultureInfo.InvariantCulture); result = await _skillAdapter.GetConversationPagedMembersAsync(claimsIdentity, route.Parameters["conversationId"].Value, pageSize, route.Parameters["continuationToken"].Value, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations")] case ChannelApiMethods.GetConversations: result = await _skillAdapter.GetConversationsAsync(claimsIdentity, route.Parameters["conversationId"].Value, cancellationToken : cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/activities/{activityId}")] case ChannelApiMethods.ReplyToActivity: var replyToActivity = HttpHelper.ReadRequest <Activity>(httpRequest); result = await _skillAdapter.ReplyToActivityAsync(claimsIdentity, replyToActivity.Conversation.Id, route.Parameters["activityId"].Value, replyToActivity, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/activities/history")] case ChannelApiMethods.SendConversationHistory: var history = HttpHelper.ReadRequest <Transcript>(httpRequest); result = await _skillAdapter.SendConversationHistoryAsync(claimsIdentity, route.Parameters["conversationId"].Value, history, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/activities")] case ChannelApiMethods.SendToConversation: var sendToConversationActivity = HttpHelper.ReadRequest <Activity>(httpRequest); result = await _skillAdapter.SendToConversationAsync(claimsIdentity, sendToConversationActivity.Conversation.Id, sendToConversationActivity, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/activities/{activityId}")] case ChannelApiMethods.UpdateActivity: var updateActivity = HttpHelper.ReadRequest <Activity>(httpRequest); result = await _skillAdapter.UpdateActivityAsync(claimsIdentity, route.Parameters["conversationId"].Value, route.Parameters["activityId"].Value, updateActivity, cancellationToken).ConfigureAwait(false); break; // [Route("/v3/conversations/{conversationId}/attachments")] case ChannelApiMethods.UploadAttachment: var uploadAttachment = HttpHelper.ReadRequest <AttachmentData>(httpRequest); result = await _skillAdapter.UploadAttachmentAsync(claimsIdentity, route.Parameters["conversationId"].Value, uploadAttachment, cancellationToken).ConfigureAwait(false); break; default: httpResponse.StatusCode = (int)HttpStatusCode.NotFound; return; } } catch (UnauthorizedAccessException) { // handle unauthorized here as this layer creates the http response statusCode = (int)HttpStatusCode.Unauthorized; } HttpHelper.WriteResponse(httpResponse, statusCode, result); }
/// <summary> /// Initiliazes a new <see cref="BotRank"/> class instance. /// </summary> /// <param name="bot">The bot.</param> /// <param name="score">The score.</param> public BotRank(IBot bot, float score) { Bot = bot; Score = score; }
private async Task InitializeSkill(DialogContext dc) { try { var skillDefinition = dc.ActiveDialog.State[ActiveSkillStateKey] as SkillDefinition; var skillConfiguration = _skills[skillDefinition.Id]; IStorage storage; if (skillConfiguration.CosmosDbOptions != null) { var cosmosDbOptions = skillConfiguration.CosmosDbOptions; cosmosDbOptions.CollectionId = skillDefinition.Name; storage = new CosmosDbStorage(cosmosDbOptions); } else { storage = new MemoryStorage(); } // Initialize skill state var userState = new UserState(storage); var conversationState = new ConversationState(storage); // Create skill instance try { var skillType = Type.GetType(skillDefinition.Assembly); _activatedSkill = (IBot)Activator.CreateInstance(skillType, skillConfiguration, conversationState, userState, null, true); } catch (Exception e) { var message = $"Skill ({skillDefinition.Name}) could not be created."; throw new InvalidOperationException(message, e); } _inProcAdapter = new InProcAdapter { // set up skill turn error handling OnTurnError = async(context, exception) => { await context.SendActivityAsync(context.Activity.CreateReply(CommonResponses.ErrorMessage_SkillError)); await dc.Context.SendActivityAsync(new Activity(type : ActivityTypes.Trace, text : $"Skill Error: {exception.Message} | {exception.StackTrace}")); // Log exception in AppInsights skillConfiguration.TelemetryClient.TrackException(exception); }, }; _inProcAdapter.Use(new EventDebuggerMiddleware()); _inProcAdapter.Use(new SetLocaleMiddleware(dc.Context.Activity.Locale ?? "en-us")); _inProcAdapter.Use(new AutoSaveStateMiddleware(userState, conversationState)); _skillInitialized = true; } catch { // something went wrong initializing the skill, so end dialog cleanly and throw so the error is logged _skillInitialized = false; await dc.EndDialogAsync(); throw; } }
public override ITurnAction Update(IBot ownBot, IBattlefield battlefield) { if (!Corners.Any()) { Corners.Add(new Point(10, 10)); Corners.Add(new Point(10, battlefield.Height - 10)); Corners.Add(new Point(battlefield.Width - 10, battlefield.Height - 10)); Corners.Add(new Point(battlefield.Width - 10, 10)); } if (ownBot.EquippedWeapon.Ammunition.Remaining == 0) { var weapon = battlefield.Weapons.OrderBy(a => a.DistanceTo(ownBot)).FirstOrDefault(); if (weapon != null) { return(ownBot.DistanceTo(weapon) > ownBot.Radius ? TurnAction.MoveTowards(weapon) : TurnAction.PickUpWeapon()); } } if (ownBot.HitPoints.Percent < 50) { if (ownBot.HasResource) { return(TurnAction.DropDownResource()); } var firstAidKit = battlefield.FirstAidKits.OrderBy(f => ownBot.DistanceTo(f)).FirstOrDefault(); if (firstAidKit != null) { if (ownBot.DistanceTo(firstAidKit) < ownBot.Radius) { return(TurnAction.PickUpFirstAidKit()); } return(TurnAction.MoveTowards(firstAidKit.Position)); } } if (ownBot.HasResource) { return(ownBot.DistanceTo(ownBot.Home) > ownBot.Radius ? TurnAction.MoveTowards(ownBot.Home) : TurnAction.DropDownResource()); } var target = battlefield.Bots.Except(new[] { ownBot }) .Where(b => b.HasResource) .OrderBy(b => b.DistanceTo(ownBot)) .FirstOrDefault(); if (target != null) { return(ownBot.DistanceTo(target) < ownBot.EquippedWeapon.MaxRange ? TurnAction.ShootAt(target) : TurnAction.MoveTowards(target)); } if (myAttacker != null) { if (ownBot.HasResource) { return(TurnAction.DropDownResource()); } if (battlefield.Bots.Contains(myAttacker)) { return(ownBot.DistanceTo(myAttacker) < ownBot.EquippedWeapon.MaxRange ? TurnAction.ShootAt(myAttacker) : TurnAction.MoveTowards(myAttacker)); } myAttacker = null; } if (battlefield.Resources.Any()) { var resource = battlefield.Resources.OrderBy(r => r.DistanceTo(ownBot)).First(); if (ownBot.DistanceTo(resource) < ownBot.Radius) { return(TurnAction.PickUpResource()); } return(TurnAction.MoveTowards(resource.Position)); } return(TurnAction.Idle); }
public async static Task <IScheduler> InitializeScheduler(AggregationService service, IBot bot) { NameValueCollection props = new NameValueCollection { { "quartz.serializer.type", "binary" } }; StdSchedulerFactory factory = new StdSchedulerFactory(props); var scheduler = await factory.GetScheduler(); await scheduler.Start(); scheduler.JobFactory = new UpdateJobFactory(bot, service); var details = JobBuilder.Create <UpdateRateJob>().WithIdentity("aggregation", "major").Build(); var trigger = TriggerBuilder .Create() .WithIdentity("aggregation", "major") .StartNow() .WithSimpleSchedule(s => s.WithIntervalInMinutes(5).RepeatForever()) .Build(); await scheduler.ScheduleJob(details, trigger); return(scheduler); }
public TwitterController(TwitterConversationAdapter adapter, IBot bot) { _adapter = adapter; _bot = bot; }
public JSScheduleArgument(IBot bot, IJSScheduler scheduler) { this.Bot = bot; this.Scheduler = scheduler; }
public Game(IBot crosses, IBot naughts) { botCross = crosses; botNaught = naughts; }
void IBotRequestUnitProduction.RequestUnitProduction(IBot bot, string requestedActor) { queuedBuildRequests.Add(requestedActor); }
public BotController(IBotFrameworkHttpAdapter httpAdapter, IBot bot) { _adapter = httpAdapter; _bot = bot; }
public SquadCA(IBot bot, SquadManagerBotModuleCA squadManager, SquadTypeCA type) : this(bot, squadManager, type, null) { }
public void Execute(Fooxboy.NucleusBot.Models.Message msg, IMessageSenderService sender, IBot bot) { if (Main.Api.Users.IsBanned(msg)) { return; } //проверка на регистрацию. if (_api.Users.CheckUser(msg)) { var kb2 = new KeyboardBuilder(bot); kb2.AddButton(ButtonsHelper.ToHomeButton()); sender.Text("✔ Вы уже зарегистрированы, перейдите на главный экран!", msg.ChatId, kb2.Build()); return; } //регистрация нового юзера. var user = new HydraBot.Models.User(); user.Access = 0; user.IsBanned = false; user.Level = 1; user.Prefix = "Игрок"; user.Score = 0; user.TimeBan = 0; user.BonusDay = 1; user.SubOnNews = true; user.Money = 100000; user.DriverLicense = ""; user.IsAvailbleBonus = true; user.TimeBonus = 0; if (msg.Platform == MessengerPlatform.Vkontakte) { //устанавливаем id ВКонтакте в зависимости от того куда написал пользователь. В беседу или в лс. if (msg.ChatId < 2000000000) { user.VkId = msg.ChatId; } else { user.VkId = msg.MessageVK.FromId.Value; } //устанавливаем никнейм var vkapi = new VkApi(); vkapi.Authorize(new ApiAuthParams() { AccessToken = Main.Token }); var userName = vkapi.Users.Get(new List <long>() { msg.MessageVK.FromId.Value })[0].FirstName; user.Name = userName; } //устанавливаем id Телеграмма. else { user.TgId = msg.MessageTG.From.Id; user.Name = msg.MessageTG.From.FirstName; } //добавляем пользователя в бд. var id = _api.Users.AddUser(user); user.Id = id; var garage = new Models.Garage() { Cars = "", PhoneNumber = null, Name = "no", IsPhone = false, Engines = "", Fuel = 9999999999999, GarageModelId = -1, SelectCar = -1, ParkingPlaces = 0, UserId = id }; Main.Api.Garages.RegisterGarage(garage); var skills = new Skills(); skills.UserId = id; using (var db = new Database()) { db.Skillses.Add(skills); db.SaveChanges(); } var kb = new KeyboardBuilder(bot); kb.AddButton(ButtonsHelper.ToHomeButton()); sender.Text("✔ Вы успешно зарегистрировались! Перейдите на главный экран, нажав на кнопку домой.", msg.ChatId, kb.Build()); }
public BotController(IBotFrameworkHttpAdapter adapter, IBot bot) { Adapter = adapter; Bot = bot; }
public ConsoleBot(IBot bot) { _bot = bot; }