public async Task <bool> IssetUser(BotUser user) { var query = new SqlCommand($"SELECT COUNT(*) FROM {Settings.Db.TableName} WHERE({Settings.Db.VkUserId})={ user.UserId} ", Connection); try { await Connection.OpenAsync(); var res = (int)query.ExecuteScalar(); if (res == default(int)) { return(false); } else { return(true); } } catch (Exception ex) { Helper.SendMessage(ex.Message, user.UserId); return(false); } finally { Connection.Close(); } }
public async Task <IResult> Execute(Message msg, BotUser user) { var parameters = msg.Text.Split(' ', 3)[1..]; user = _db.Entry(user).Entity; if (parameters.Length < 2) { return(new FailedResult("Укажите 2 параметра команды." + "Пример использования: установить город Москва / установить группу 123456")); } var whatToSet = parameters[0]; var dataToSet = parameters[1]; if (whatToSet.Contains("город", StringComparison.InvariantCultureIgnoreCase)) { return(await SetCity(dataToSet, user)); } if (whatToSet.Contains("групп", StringComparison.InvariantCultureIgnoreCase)) { return(await SetGroup(dataToSet, user)); } return(new FailedResult("Укажите что вы хотите установить: группу или город. \n" + "Пример использования: установить город Москва / установить группу 123456")); }
public static User AuthorizeVk(this BotUser botUser, string acessToken) { if (botUser == null) { throw new ArgumentNullException(); } var api = new VkApi(); api.Authorize(new ApiAuthParams { AccessToken = acessToken }); var screenName = api.Account.GetProfileInfo().ScreenName; var user = GetUserByScreenName(api, screenName); botUser.VkAccount = new VkAccount { Id = user.Id, AcessToken = acessToken, CurrentPeer = user.Id }; return(user); }
/// <summary> /// Generates a response for client input sentence. /// </summary> /// <param name="dataFromClient"></param> /// <returns>Response generated by AIML Bot engine</returns> protected string ProcessRequestResponse(string dataFromClient) { BotUser user = Server.DefaultUser; dynamic js = JsonConvert.DeserializeObject <dynamic>(dataFromClient); string userid = string.Empty, question = string.Empty; if (js != null && js.userid != null) { userid = js.userid.ToString(); if (Server.Users.ContainsKey(userid)) { user = Server.Users[userid]; } else { user = new BotUser(Guid.Parse(userid), Server.ActiveBot); Server.Users[userid] = user; } question = js.question.ToString(); } Result res = Server.ActiveBot.Chat(new Request(question, user, Server.ActiveBot)); string responseStatement = SkillsRepository.Instance.ProcessSkills(res.Output); return(responseStatement); }
public void ProcessMessage(string messageText, BotUser user) { if (addingLinkCommandListProvider.GetCommands().Contains(messageText)) { var newUserState = container.Get <RegisterTG>(); peopleParser.ChangeState(user.UserId, Infrastructure.UserStates.Register); tgMessageSender.SendNotification(user, new MessageResponse(ResponseType.LinkCancel).response, newUserState.GetKeyboard()); } else if (!messageText.Contains("http") && !messageText.Contains(":")) { tgMessageSender.SendNotification(user, new MessageResponse(ResponseType.LinksError).response, GetKeyboard()); } else if (messageText.Contains("http") && messageText.Contains(":")) { var splittedMessage = messageText.Split(": "); var name = splittedMessage[0]; var link = splittedMessage[1]; messageHandler.AddLink(user, name, link); peopleParser.ChangeState(user.UserId, Infrastructure.UserStates.Register); var newUserState = container.Get <RegisterTG>(); tgMessageSender.SendNotification(user, new MessageResponse(ResponseType.SucessfulLinks).response, newUserState.GetKeyboard()); } else { tgUnknownMessageProcessor.ProcessUnknownCommand(messageText, user, GetKeyboard(), new MessageResponse(ResponseType.Help)); } }
public async Task <IActionResult> Edit(int id, [Bind("Id,DiscordId,Role,ResetCommand")] BotUser botUser) { if (id != botUser.Id) { return(NotFound()); } if (ModelState.IsValid) { try { db.Update(botUser); await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!UserExists(botUser.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(botUser)); }
/// <summary> /// Добавление запроса пользователя /// </summary> /// <param name="botUser"></param> /// <param name="type"></param> /// <param name="answer"></param> /// <param name="query"></param> /// <param name="TimeToStartAnswer"></param> /// <param name="buRequest"></param> public void AddBotQuery(BotUser botUser, FindedInformation answer, DateTime TimeToStartAnswer, BotUserRequest buRequest) { try { buRequest.BotUserID = botUser.BotUserID; buRequest.NowIs = (MallBotWhatIsHappeningNow)botUser.NowIs; if (answer != null && answer.Result != null) { buRequest.Answer = JsonConvert.SerializeObject(answer.Result); } var TimeToAnswer = DateTime.Now.Subtract(TimeToStartAnswer); buRequest.TimeToAnswer = TimeToAnswer.Days.ToString() + ":" + TimeToAnswer.Hours.ToString() + ":" + TimeToAnswer.Minutes.ToString() + ":" + TimeToAnswer.Seconds.ToString() + ":" + TimeToAnswer.Milliseconds.ToString(); buRequest.DateTime = DateTime.Now; buRequest.BotUserID = botUser.BotUserID; buRequest.CustomerCompositeID = botUser.CustomerCompositeID; buRequest.Name = botUser.Name; botUser.LastActivityDate = DateTime.Now; BotUserRequest.Add(buRequest); SaveChanges(); } catch (Exception exc) { Logging.Logger.Error(exc); } }
private async Task RegisterVote(HttpContext context) { if (!context.Request.Headers["Authorization"].Equals(Program.tokens.dblAuth)) { return; } BotUser user = null; try { string bodyContent = await new StreamReader(context.Request.Body).ReadToEndAsync(); if (bodyContent != null && bodyContent.Length > 0) { Log.LogS(bodyContent); var values = JsonConvert.DeserializeObject <Dictionary <string, string> >(bodyContent); user = BotUser.Load(ulong.Parse(values["user"])); await UniqueChannels.Instance.SendToLog($"{user._id}'s vote was received"); } } catch (Exception e) { await UniqueChannels.Instance.SendToLog(e); } if (user != null) { await user.NewVote(); } else { Log.LogS("Failed to register vote"); } }
public MainAnswerHelper(BotUserRequest _thisRequest, object _Bot, SocialNetworkType _type, BotUser _botUser, List <MallBotContext> _dbContextes, List <VKApiRequestModel> _Requests = null) { botUser = _botUser; dbContextes = _dbContextes; Requests = _Requests; Bot = _Bot; type = _type; thisRequest = _thisRequest; #region Кэшируем string CachedItemKey = "MallBotData"; var datafromCache = cacher.Get(CachedItemKey); if (datafromCache == null) { datasOfBot = cacher.Update(CachedItemKey, dbContextes); } else { datasOfBot = (List <CachedDataModel>)datafromCache; } #endregion texter = new BotTextHelper(botUser.Locale, type, datasOfBot[0].Texts); sender = new ApiRouter(type, Bot, botUser, Requests); dataGetter = new GetDataHelper(datasOfBot); if (botUser.NowIs != MallBotWhatIsHappeningNow.SettingCustomer) { char usersdbID = botUser.CustomerCompositeID[0]; var customerID = int.Parse(botUser.CustomerCompositeID.Remove(0, 1)); currentCustomer = dataGetter.GetStructuredCustomers(true).FirstOrDefault(x => x.DBaseID == usersdbID).Customers.FirstOrDefault(x => x.CustomerID == customerID); //дает возможность работы в тц не из тестового режима } }
async Task ICallbackQueryCommand.ExecuteAsync(CallbackQuery callbackQuery, BotUser user) { string password; try { password = user.GenPattern.GeneratePasswordByPattern(); } catch (ArgumentException ex) {
public bool ShowAllShopItems(BotUser sender) { ShopHelper.GetJsonItems(); if (ShopHelper.ShopItems == null || ShopHelper.ShopItems.Count <= 0) { Api.SendMessage("Список магазина пуст", sender.UserId); return(false); } string resualt = "Список всех предметов магазина:\n\n"; for (int i = 0; i < ShopHelper.ShopItems.Count; i++) { var h = ShopHelper.ShopItems[i]; var shortText = string.Empty; if (h.Text.Length > 15) { shortText = h.Text.Substring(0, 15) + "..."; } else { shortText = h.Text; } resualt += $"ID товара [{h.Id}] - {shortText}, дата публикации {h.PostDate.ToShortDateString()}, дата окончания {h.Date.ToShortDateString()},цена {h.Price}\n\n"; } ShopHelper.ClearData(); Api.SendMessage(resualt, sender.UserId); return(true); }
public void ProcessMessage(BotUser user, ICommunicator communicator, string message) { try { var command = _commandFactory.GetCommand(message, user); if (command.HasValue) { ProcessCommandMessage(user, communicator, command.Value); } else { ProcessSimpleMessage(user, communicator, message); } } catch (UnauthorizedException exception) { communicator.SendMessage("У вас нет прав для выполнения этой команды"); _logger.Error(exception); } catch (InvalidOperationException e) { communicator.SendMessage(e.Message); _logger.Error(e); } catch (Exception e) { _logger.Error(e); } }
public void SendMessage(string text, BotUser user) { foreach (var x in user.UserAccounts.Select(x => _communicatorFactory.GetCommunicator(x))) { x.SendMessage(text); } }
public ReactionHandler(IUserMessage message, SocketReaction reaction, GuildSettings gset) { botUser = BotUser.Load(reaction.UserId); this.reaction = reaction; this.message = message; guildSettings = gset; }
async Task IMessageCommand.ExecuteAsync(Message message, BotUser user) //TODO: //Create public static method in HelpCommand that returns help message => await bot.Client.SendTextMessageAsync(message.From.Id, string.Format(Localization.GetMessage("Help", user.Lang), "/add", "/all", "/generator", "/language", "/cancel", "/help"), Telegram.Bot.Types.Enums.ParseMode.Markdown);
public static async Task <string> GetFormattedFinalTextToAdminsAsync(BotUser instance, Purchase purchase = null) { if (purchase == null) { purchase = instance.CurrentPurchase; } var textPatternToAdminsTask = Texts.GetFinalTextToAdminsAsync(); var adressToDeliver = purchase.AdressToDeliver; var lbrds = Join(ElementsSeparator, purchase.Basket); var cost = Math.Round(purchase.Cost, 2); var adressInfo = adressToDeliver ?? NoDeliveryInfo; var linkText = Format(LinkFormat, instance.Name, instance.UserId); var textPatternToAdmins = await textPatternToAdminsTask; var textFormattedToAdminGroup = Format( textPatternToAdmins, linkText, lbrds, cost.ToString(), instance.Name, instance.Phone, adressInfo, purchase.Guid.ToStringHashTag() ); return(textFormattedToAdminGroup); }
/// <summary> /// Добавление пользователя /// </summary> /// <param name="recipientID"></param> /// <param name="isJoinGroup"></param> /// <returns></returns> public MFCBotContext AddBotUser(string recipientID, bool isJoinGroup = false) { try { var btusr = new Models.MFCModels.BotUser(); if (isJoinGroup) { btusr.JoinGroupDate = DateTime.Now; } btusr.BotUserVKID = recipientID; btusr.Locale = "ru_RU"; btusr.LastActivityDate = DateTime.Now; //данные для мфц btusr.NowIs = MFCBotWhatIsHappeningNow.SettingOffice; btusr.TalonID = 0; btusr.OfficeID = 0; btusr.ServiceID = 0; BotUser.Add(btusr); SaveChanges(); return(this); } catch (Exception exc) { Logging.Logger.Error(exc); return(null); } }
private async Task <DialogTurnResult> Step1CheckRegistrationAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken) { _logger.LogTrace("----- ComponentDialogBot.Step1CheckRegistrationAsync - Beginning step"); var context = stepContext.Context; // Check if user is already registered var user = await _botUserServices.FindByChannelUserIdAsync(context.Activity.ChannelId, context.Activity.From.Name); if (user != null) { await _accessors.SetAsync <GreetingState>(stepContext.Context, s => s.CallName = user.CallName, cancellationToken); // Get GreetingState from conversation state await context.SendActivityAsync($"Hi {user.CallName}, nice to talk to you again!"); return(await stepContext.EndDialogAsync()); } await context.SendActivityAsync($"Hi {context.Activity.From.Name}! You are not registered in our database."); var botUser = new BotUser { ChannelId = context.Activity.ChannelId, UserId = context.Activity.From.Name, }; StoreBotUser(stepContext, botUser); return(await stepContext.PromptAsync( TextPromptId, new PromptOptions { Prompt = MessageFactory.Text("Please enter your name") }, cancellationToken)); }
private bool SendHomeWork(string datestr,BotUser sender) { try { HomeWorkHelper.GetJsonItems(); if (HomeWorkHelper.HomeWorks == null) { Api.SendMessage(ExecutorText.CheckHomeWorkExecutor.HomeWorkNull, sender.UserId); return false; } var date = DateTime.ParseExact(datestr, Settings.Path.DateFormat, null); var res = HomeWorkHelper.GetJsonItemByDate(date); if (res == null) { Api.SendMessage(ExecutorText.CheckHomeWorkExecutor.HomeWorkDoesntAdded, sender.UserId); return false; } Api.SendMessage($"Дз на {res.Date.DayOfWeek.ToString().ToUpper()}({res.Date.ToShortDateString()}): \n\n"+res.Text, sender.UserId); if (res.Attachments != null&&res.Attachments.Count>0) { Api.SendMessage("", sender.UserId, res.Attachments.ToList<MediaAttachment>()); } HomeWorkHelper.ClearData(); return true; } catch (Exception ex) { Api.SendMessage(ExecutorText.ExepctionText, sender.UserId); return false; } }
public ILocalisable <EmbedBuilder> GetEmbed() { var builder = new LocalisedEmbedBuilder { Color = new Color(135, 206, 250), //System.Drawing.Color.LightSkyBlue.ToDiscord(), Title = new LocalisedString(SINGLE_TITLE, ReplyType.Info, Command.Name), Timestamp = DateTime.Now, Footer = new LocalisedFooterBuilder().WithRawIconUrl(BotUser.GetAvatarUrl()).WithText(SINGLE_FOOTER, BotUser.Username), }.WithDescription(Command.Description ?? SINGLE_NODESCRIPTION); builder.AddInlineField(f => f.WithName(TBLocalisation.GROUP).WithValue(Group)); if (!string.IsNullOrWhiteSpace(Aliases)) { builder.AddInlineField(f => f.WithName(TBLocalisation.ALIASES).WithRawValue(Format.Sanitize(Aliases))); } builder.AddField(f => f.WithName(TBLocalisation.USAGE).WithValue(Usage)); if (Flags.Count != 0) { builder.AddField(f => f.WithName(TBLocalisation.FLAGS).WithValue(Flag)); } if (Notes != null && !string.IsNullOrWhiteSpace(Notes.Key)) { builder.AddField(f => f.WithName(TBLocalisation.NOTES).WithValue(tr => Notes.Localise(tr) + (Usages.Count > 0 ? NotesFooter.Localise(tr) : ""))); } else if (Usages.Count > 0) { builder.AddField(f => f.WithName(TBLocalisation.NOTES).WithValue(NotesFooter)); } return(builder); }
public async Task GetsUserCallNameAndReplyBackUsingIt() { // Arrange ----------------- var services = GetService <IBotUserServices>(); var testFlow = CreateBotTestFlow <ComponentDialogsBot>() .Send("Hi") .AssertReply("Hi User1! You are not registered in our database.") .AssertReply("Please enter your name") .Send("Miguel") .AssertReply("Thanks Miguel, How do you want me to call you?") .Send("Mike") .AssertReply("Thanks Mike, I'll echo you from now on, just type anything") .Send("anything") .AssertReply("Hi Mike (Turn 1): You typed \"anything\""); // Act --------------------- await testFlow.StartTestAsync(); // Assert ------------------ var users = await services.GetListAsync(); var expectedUsr = new BotUser { ChannelId = "test", UserId = "User1", Name = "Miguel", CallName = "Mike" }; users.Should().BeEquivalentTo(new[] { expectedUsr }); }
public bool GetAllHomeWork(BotUser sender) { HomeWorkHelper.GetJsonItems(); if (HomeWorkHelper.HomeWorks == null) { Api.SendMessage("Список домашних заданий пуст", sender.UserId); return(false); } string resualt = "Список всех домашних заданий:\n\n"; for (int i = 0; i < HomeWorkHelper.HomeWorks.Count; i++) { var h = HomeWorkHelper.HomeWorks[i]; var shortText = string.Empty; if (h.Text.Length > 10) { shortText = h.Text.Substring(0, 10); } else { shortText = h.Text; } resualt += $"Номер [{i}] - {shortText}... , дата {h.PostDate.ToShortDateString()}\n"; } HomeWorkHelper.ClearData(); Api.SendMessage(resualt, sender.UserId); return(true); }
public bool Execute(BotUser sender, Command command, string Label, string[] parameters, Message VkMessage) { if (sender.HasPermission(command.Permission)) { if (parameters.Length <= 0) { return(HomeWorkExecutorHelper.GetAllHomeWork(sender)); } if (parameters.Length < 1) { Api.SendMessage("Вы не вверли необходимый параметер(дату домашнего задания)", sender.UserId); return(false); } var datestr = parameters[0]; var date = DateTime.ParseExact(datestr, Settings.Path.DateFormat, null); HomeWorkHelper.GetJsonItems(); var res = HomeWorkHelper.GetJsonItemByDate(date); if (res == null) { Api.SendMessage(ExecutorText.DeleteHomeWorkExecutor.ErrorDelete, sender.UserId); return(false); } HomeWorkHelper.Remove(res); HomeWorkHelper.UpdateJson(); HomeWorkHelper.ClearData(); Api.SendMessage(ExecutorText.DeleteHomeWorkExecutor.SuccessDelete, sender.UserId); return(true); } Api.SendMessage(ExecutorText.CantPermission, sender.UserId); return(false); }
async Task IMessageCommand.ExecuteAsync(Message message, BotUser user) { if (bot.IsAdmin(user)) { try { IList <User> users = await userService.GetAllBasicInfoAsync(); string response = string.Empty; //TODO: use string builder for (int i = 0; i < users.Count; i++) { response += $"{(i + 1)}. [{ users[i].Id}](tg://user?id={users[i].Id}): {users[i].Accounts.Count}\n\n"; } //TODO: //fix @UPwdBot, get bot nickname from bot and save in in bot class await bot.Client.SendTextMessageAsync(user.Id, "All @UPwdBot users:\nUser: Number of accounts\n" + response, Telegram.Bot.Types.Enums.ParseMode.Markdown); } catch (Exception ex) { await bot.Client.SendTextMessageAsync(user.Id, "Error occured:\n\n" + ex.ToString()); //TODO: Log Exception } } }
// ReSharper disable once UnusedMember.Global protected IEnumerable <CommandResponse> RegisterMode() { if (this.User.Account == null) { yield return(new CommandResponse { Message = "Please identify to NickServ first!", Destination = CommandResponseDestination.PrivateMessage }); yield break; } var mask = new IrcUserMask(string.Format("$a:{0}", this.User.Account), this.Client); var user = new BotUser(mask); this.botUserConfiguration.Add(user); this.botUserConfiguration.Save(); yield return(new CommandResponse { Message = string.Format("Registered using NickServ account {0}.", this.User.Account), Destination = CommandResponseDestination.PrivateMessage }); yield return(new CommandResponse { Message = string.Format( "Please note, to receive notifications via email, you need to provide your email address (=account email <address>). By providing your email address, you agree to the privacy policy: {0}", this.appConfig.PrivacyPolicy), Destination = CommandResponseDestination.PrivateMessage }); }
public async Task <IResult> Execute(Message msg, BotUser user) { var dict = msg.ParsedPayload; var isExists = dict.TryGetValue(Trigger, out var idString); if (!isExists) { return(new FailedResult("Невозожно получить ID преподавателя.")); } var isCorrectId = int.TryParse(idString, out var id); if (!isCorrectId) { return(new FailedResult("Некорректный ID преподавателя.")); } try { var schedule = await _narfuApi.Teachers.GetLimitedSchedule(id); return(new SuccessfulResult { Message = schedule.ToString() }); } catch (HttpRequestException) { return(new FailedResult(DefaultErrors.NarfuSiteIsUnavailable)); } catch (Exception) { return(new FailedResult(DefaultErrors.NarfuUnexpectedError)); } }
public async Task <IResult> Execute(Message msg, BotUser user) { if (string.IsNullOrWhiteSpace(user.WeatherCity)) { return(new FailedResult("Для получения погоды установите город (нужно написать следующее - установить город Москва).")); } var dict = msg.ParsedPayload; var isExists = dict.TryGetValue(Trigger, out var day); if (!isExists) { return(new FailedResult("Невозможно получить значение даты")); } var isCorrectDate = DateTime.TryParse(day, out var dateTime); if (!isCorrectDate) { return(new FailedResult("Некорректное значение даты")); } var weather = await _weatherService.GetDailyWeather(user.WeatherCity, dateTime); weather.Keyboard = DefaultKeyboards.GetDailyWeatherKeyboard(); return(weather); }
public BotCommandContext(DiscordSocketClient client, SocketUserMessage msg) : base(client, msg) { if (!(msg.Author.IsBot || msg.Author.IsWebhook)) { BotUser = Program.GetUser(msg.Author); } }
public bool ShowAllShopItems(BotUser sender) { try { ShopHelper.GetJsonItems(); if (ShopHelper.ShopItems == null || ShopHelper.ShopItems.Count <= 0) { Api.SendMessage("Извините, но в магазине нет неодного товара =(", sender.UserId); return(false); } string resualt = "Товары магазина: \n"; foreach (var item in ShopHelper.ShopItems) { resualt += item.Text + "\n"; resualt += $"Добавлено {item.PostDate.ToShortDateString()} \n"; resualt += $"Действительно до {item.Date.ToShortDateString()}\n"; resualt += "Цена: " + item.Price + "\n"; resualt += "\n"; } Api.SendMessage(resualt, sender.UserId); return(true); } catch (Exception ex) { Api.SendMessage(ExecutorText.ExepctionText, sender.UserId); return(false); } }
public async Task <bool> RemoveUser(BotUser user) { var removeuser = new SqlCommand($"DELETE FROM {Settings.Db.TableName} WHERE {Settings.Db.VkUserId}={user.UserId}", Connection); try { await Connection.OpenAsync(); int res = removeuser.ExecuteNonQuery(); if (res == default(int)) { return(false); } else { return(true); } } catch (Exception ex) { Helper.SendMessage(ex.Message, user.UserId); return(false); } finally { Connection.Close(); } }