Пример #1
0
        private static async Task WhoAmICommand(IBotService botService, Message message, BotDbContext dbContext)
        {
            var client        = botService.Client;
            var profilePhotos = await client.GetUserProfilePhotosAsync(message.From.Id, 0, 1);

            if (profilePhotos.TotalCount != 0)
            {
                await client.SendPhotoAsync
                (
                    message.Chat.Id,
                    profilePhotos.Photos[0][0].FileId,
                    $@"You are
<b>{message.From.FirstName} {message.From.LastName}{(message.From.IsBot ? "🤖" : "")}</b>
@{message.From.Username}
<code>{message.From.Id}</code>",
                    replyToMessageId : message.MessageId,
                    parseMode : ParseMode.Html
                );
            }
            else
            {
                await client.SendTextMessageAsync
                (
                    message.Chat.Id,
                    $@"You are
<b>{message.From.FirstName} {message.From.LastName}{(message.From.IsBot ? "🤖" : "")}</b>
@{message.From.Username}
<code>{message.From.Id}</code>",
                    replyToMessageId : message.MessageId,
                    parseMode : ParseMode.Html
                );
            }
        }
Пример #2
0
 public MessagesController(
     IMessageService messageService,
     IBotService botService)
 {
     _messageService = messageService;
     _botService     = botService;
 }
Пример #3
0
 public UpdateService(IBotService botService, IAnonymousService anonymousService, ILogger <UpdateService> logger)
 {
     _botService       = botService;
     _anonymousService = anonymousService;
     _logger           = logger;
     _anonymousService.GenerateAnoymousNames();
 }
Пример #4
0
        private void ReceivedMessageEvent(IBotService sender, AcceptedMessage message)
        {
            var sendingService = Services.OrderByDescending(v => v.Level).First();

            if (message.IsGroupMessage)
            {
                if (_groupCache == null || _groupCache.All(v => v.GroupId != message.FromGroup))
                {
                    _groupCache = GetRequesterService().GetGroupsAsync().GetAwaiter().GetResult();
                }
                if (!_groupMembersCache.ContainsKey(message.FromGroup))
                {
                    _groupMembersCache.Add(message.FromGroup,
                                           GetRequesterService().GetGroupMembersAsync(message.FromGroup).GetAwaiter().GetResult());
                }
                message.FromGroupName = _groupCache?.FirstOrDefault(v => v.GroupId == message.FromGroup)?.GroupName;
                var memberInfo = _groupMembersCache[message.FromGroup].FirstOrDefault(v => v.Id == message.FromUser);
                message.FromGroupCard = string.IsNullOrEmpty(memberInfo?.CardName)
                    ? memberInfo?.NickName
                    : memberInfo.CardName;
                LogHelper.Info($"[{BotName}] - 收到来自群 {message.FromGroupName}({message.FromGroup}) 内用户 {message.FromGroupCard}({message.FromUser}) 的消息: {message.Content}");
                ReceivedGroupMessageEvent?.Invoke(this, sendingService, message);
                return;
            }
            LogHelper.Info($"[{BotName}] - 收到来自好友 {message.FromUser} 的消息: {message.Content}");
            ReceivedPrivateMessageEvent?.Invoke(this, sendingService, message);
        }
        /// <summary>
        /// Boots this instance.
        /// </summary>
        public void Boot()
        {
            DotNetEnv.Env.Load(new DotNetEnv.Env.LoadOptions(parseVariables: false));

            var builder = new ConfigurationBuilder();

            // tell the builder to look for the appsettings.json file
            builder
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddEnvironmentVariables();

            var configuration = builder.Build();

            ServiceCollection = new ServiceCollection();
            ServiceCollection.AddCoreServices(configuration);

            ServiceProvider = ServiceCollection.BuildServiceProvider();

            _logger = Resolve <IGraphLogger>();

            try
            {
                _settings = Resolve <IOptions <AzureSettings> >().Value;
                _settings.Initialize();
                Resolve <IEventPublisher>();
                _botService = Resolve <IBotService>();
            }
            catch (Exception e)
            {
                _logger.Error(e, "Unhandled exception in Boot()");
            }
        }
        public static void ScheduleRequest(IBotService botService, IServiceProxy serviceProxy,
                                           long chatId, RequestParams requestParams, CancellationToken token = default)
        {
            Task.Factory.StartNew(() =>
            {
                _logger.Info("Try to send request to service.");
                try
                {
                    var response  = serviceProxy.SendPostRequest(requestParams).Result;
                    var converted = ConvertResultsToDict(response.RatingDataContainers);

                    _logger.Info("Got response. Output message to chat.");

                    botService.Client.SendTextMessageAsync(
                        chatId,
                        CreateResponseMessage(converted)
                        ).Wait();
                }
                catch (Exception ex)
                {
                    _logger.Error(ex, "Exception occurred during data processing request.");
                }
                _logger.Info("Request was processed.");
            }, token, TaskCreationOptions.LongRunning, TaskScheduler.Default);
        }
Пример #7
0
 public AddCommand(
     IBotService botService,
     IEnvironmentStorage environmentStorage)
 {
     this.botService         = botService;
     this.environmentStorage = environmentStorage;
 }
 public TranslatorHostedService(ILogger <TranslatorHostedService> logger, ITranslationService translationService, IBotService bot, IServerConfigurationService serverConfig)
 {
     _logger       = logger;
     _translation  = translationService;
     _bot          = bot;
     _serverConfig = serverConfig;
 }
        public void LoadData()
        {
            botService = Program.kernel.Get <IBotService>();

            dishBS.DataSource     = botService.GetTelegramDishes();
            dishesGrid.DataSource = dishBS;
        }
Пример #10
0
 public CommandHostedService(ILogger <CommandHostedService> logger, IServiceProvider provider, IBotService botService, CommandService commandService)
 {
     _logger         = logger;
     _provider       = provider;
     _botService     = botService;
     _commandService = commandService;
 }
Пример #11
0
 public MembersController(IBotService botService, IMapper mapper,
                          UserManager <User> userManager)
 {
     _botService  = botService;
     _mapper      = mapper;
     _userManager = userManager;
 }
Пример #12
0
 public StartController(ILogger <MarketController> logger, IMultiTaskService multiTaskService, IBotService botService, IScanService scanService)
 {
     _logger = logger;
     this.multiTaskService = multiTaskService;
     this.botService       = botService;
     this.scanService      = scanService;
 }
Пример #13
0
 public BotReplyService(IOptions <BotConfiguration> config, IBotService botService, ILogger <BotReplyService> logger, IServiceScopeFactory serviceScopeFactory)
 {
     _config = config.Value;
     _logger = logger;
     _client = botService.Client;
     _serviceScopeFactory = serviceScopeFactory;
 }
        private static async Task ScheduleRequestImplementation(IBotService botService,
                                                                IServiceProxy serviceProxy, long chatId, RequestParams requestParams)
        {
            _logger.Info("Trying to send request to ProjectV service.");

            try
            {
                ProcessingResponse?response = await serviceProxy.SendPostRequest(requestParams);

                if (response is null)
                {
                    throw new InvalidOperationException("Request has not successful status.");
                }

                IReadOnlyDictionary <string, IList <double> > converted =
                    ConvertResultsToDict(response.RatingDataContainers);

                _logger.Info("Got response. Output message to Telegram chat.");

                await botService.Client.SendTextMessageAsync(
                    chatId,
                    CreateResponseMessage(converted)
                    );
            }
            catch (Exception ex)
            {
                _logger.Error(ex, "Exception occurred during data processing request.");
                await botService.Client.SendTextMessageAsync(
                    chatId,
                    $"Cannot process request. Error: {ex.Message}"
                    );
            }

            _logger.Info("Request was processed.");
        }
Пример #15
0
        }                                        //"Command wasn't recognized. Please try again.";
        public SimpleSessionRouter(IUpdateHelper updateHelper,
                                   IMenuLoader menuLoader,

                                   IRoomService room,
                                   IUsersService users,
                                   IBotService botService,

                                   ILockTrackerService lockTrackerService,
                                   ILogHelper logHelper,
                                   INotificationRouter notificationRouter,
                                   ILocalizationHelper localizationHelper)
        {
            _menuLoader = menuLoader;

            _logHelper = logHelper;

            _updateHelper       = updateHelper;
            _notificationRouter = notificationRouter;

            _users = users;

            _room                = room;
            _botService          = botService;
            _lockTrackerService  = lockTrackerService;
            _localizationHelper  = localizationHelper;
            CommandNotRecognized = _localizationHelper.GetLocalizedString(StringToLocalize.CommandNotRecognized);
        }
 public ManageBotService(IBotService botService, IUnitOfWork uow, IConfiguration Configuration, IHttpClientFactory client)
 {
     _botService    = botService;
     _uow           = uow;
     _configuration = Configuration;
     _client        = client;
 }
Пример #17
0
        public static void StartPosting(IBotService botService)
        {
            DbManager db = new DbManager();

            _tasksWorkerPost   = new List <TaskWorker>();
            _tasksWorkerAdvert = new List <TaskWorker>();
            _botService        = botService;

            var groups = db.GetGroupsWithAvailableContent();

            if (groups.Count > 0)
            {
                foreach (var group in groups)
                {
                    StartNewPosting(group);

                    var adverts = db.GetAdvertsByGroup(group);
                    //coz group may content multiple adverts
                    //and it doesn't make sense	to post advert without content
                    foreach (var advert in adverts)
                    {
                        StartNewAdvert(advert);
                    }
                }
            }
        }
Пример #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MessagesController"/> class.
 /// </summary>
 /// <param name="botService">The botService.</param>
 /// <param name="container">A <see cref="IComponentContext"/>.</param>
 /// <param name="dialogInvoker">A <see cref="IDialogInvoker"/>.</param>
 /// <param name="telemetryClient">A <see cref="TelemetryClient"/>.</param>
 public MessagesController(IBotService botService, IComponentContext container, IDialogInvoker dialogInvoker, TelemetryClient telemetryClient)
 {
     this.botService      = botService;
     this.container       = container;
     this.dialogInvoker   = dialogInvoker;
     this.telemetryClient = telemetryClient;
 }
Пример #19
0
 public LearningController(
     IBotService botService,
     IMessageService messageService)
 {
     _botService     = botService;
     _messageService = messageService;
 }
Пример #20
0
 public EmailCommand(
     IBotService botService,
     IUsersRepository usersRepository)
 {
     this.botService      = botService;
     this.usersRepository = usersRepository;
 }
Пример #21
0
        private static async Task ClearWarnsCommand(IBotService botService, Message message)
        {
            var client          = botService.Client;
            var dbms            = botService.Dbms;
            var originMessage   = message.ReplyToMessage;
            var database        = dbms.GetDatabase("UserRecords");
            var warnsCollection = database.GetCollection <UserWarns>("Warns");
            var filter          = new BsonDocument("UserId", originMessage.From.Id);
            var results         = warnsCollection.FindSync(filter).ToList().ToArray();

            if (results.Length != 0)
            {
                await client.SendTextMessageAsync(
                    message.Chat.Id,
                    $@"Warns reset for <b>{originMessage.From.FirstName} {originMessage.From.LastName}</b>
@{originMessage.From.Username}
<code>{originMessage.From.Id}</code>",
                    replyToMessageId : message.MessageId,
                    parseMode : ParseMode.Html
                    );

                var up = new BsonDocument("$set", new BsonDocument("WarnCount", 0));
                warnsCollection.UpdateOne(filter, up);
            }
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="DemoController" /> class.

        /// </summary>
        public DemoController()
        {
            _logger         = AppHost.AppHostInstance.Resolve <IGraphLogger>();
            _eventPublisher = AppHost.AppHostInstance.Resolve <IEventPublisher>();
            _botService     = AppHost.AppHostInstance.Resolve <IBotService>();
            _settings       = AppHost.AppHostInstance.Resolve <IOptions <AzureSettings> >().Value;
        }
Пример #23
0
        private static async Task UnbanCommand(IBotService botService, Message message)
        {
            var client = botService.Client;

            if (message.ReplyToMessage != null)
            {
                var originMessage = message.ReplyToMessage;
                var originUser    = originMessage.From;
                await client.SendTextMessageAsync(
                    message.Chat.Id,
                    $@"Unbanned <b>{originMessage.From.FirstName} {originMessage.From.LastName}</b>
@{originMessage.From.Username}
<code>{originMessage.From.Id}</code>",
                    parseMode : ParseMode.Html
                    );

                await client.UnbanChatMemberAsync(message.Chat.Id, originUser.Id);
            }
            else
            {
                await client.SendTextMessageAsync(
                    message.Chat.Id,
                    "No User Specified",
                    replyToMessageId : message.MessageId
                    );
            }
        }
Пример #24
0
        public override async Task ExecuteAsync(Message message, IBotService botService)
        {
            var today = DateTime.Today.ToString("dd-MM-yyyy");
            var url   = myGazetaUrl + _sign + "/гороскоп-"
                        + _sign + "-" + today + ".html";

            using var client = new HttpClient();
            var response = await client.GetAsync(url);

            if (response == null || response.StatusCode != HttpStatusCode.OK)
            {
                return;
            }

            var source = await response.Content.ReadAsStringAsync();

            var domParser = new HtmlParser();
            var document  = await domParser.ParseDocumentAsync(source);

            var    result = Parser.Parse(document);
            string toSend = $"[{_sign}] - {today} \n";
            var    i      = 0;

            foreach (var elem in result)
            {
                i++;
                if ((i % 2 == 0) && (i != 22) && (i < 25))
                {
                    toSend += elem + "\n";
                }
            }

            await botService.Client.SendTextMessageAsync(message.Chat.Id, toSend);
        }
Пример #25
0
        private static async Task ClearWelcomeCommand(IBotService botService, Message message, BotDbContext dbContext)
        {
            var client        = botService.Client;
            var table         = dbContext.WelcomeMessages;
            var existingEntry = table.Where(welcome => welcome.ChatId == message.Chat.Id).FirstOrDefault();

            if (existingEntry != null)
            {
                await client.SendTextMessageAsync
                (
                    message.Chat.Id,
                    "Updated Welcome Message",
                    replyToMessageId : message.MessageId
                );

                table.Remove(existingEntry);
            }
            else
            {
                await client.SendTextMessageAsync
                (
                    message.Chat.Id,
                    "No Welcome Message",
                    replyToMessageId : message.MessageId
                );
            }
            dbContext.SaveChanges();
        }
Пример #26
0
        private static async Task ListAdminsCommand(IBotService botService, Message message, BotDbContext dbContext)
        {
            var client = botService.Client;
            var admins = await client.GetChatAdministratorsAsync(message.Chat.Id);

            var adminString = admins
                              .Select
                              (
                (admin) =>
                $@"• <b>{admin.User.FirstName} {admin.User.LastName}{(admin.User.IsBot ? "🤖" : "")}</b>
  @{admin.User.Username}
  <code>{admin.User.Id}</code>"
                              )
                              .Aggregate
                              (
                (s1, s2) => s1 + "\n\n" + s2
                              );
            await client.SendTextMessageAsync
            (
                message.Chat.Id,
                adminString,
                replyToMessageId : message.MessageId,
                parseMode : ParseMode.Html
            );
        }
Пример #27
0
 public PollingService(
     IBotService botService,
     IBotUpdateHandler updateHandler)
 {
     this.botService    = botService;
     this.updateHandler = updateHandler;
 }
        public MainPageViewModel(IBotService botService)
        {
            this.BotService = botService;

            this.SendMessageCommand = new DelegateCommand(async() => await this.SendMessageExecuteAsync())
                                      .ObservesCanExecute(() => this.CanSendMessage);
        }
Пример #29
0
 public TakeCommand(
     IEnvironmentStorage environmentStorage,
     IBotService botService)
 {
     this.environmentStorage = environmentStorage;
     this.botService         = botService;
 }
Пример #30
0
 public UpdateServiceAsync(IBotService botService, IServiceProxy serviceProxy,
                           IUserCache userCache)
 {
     _botService   = botService.ThrowIfNull(nameof(botService));
     _serviceProxy = serviceProxy.ThrowIfNull(nameof(serviceProxy));
     _userCache    = userCache.ThrowIfNull(nameof(userCache));
 }
Пример #31
0
        public Form1()
        {
            InitializeComponent();

            ChannelFactory<IBotService> factory =
                new ChannelFactory<IBotService>(new NetNamedPipeBinding(),
                    new EndpointAddress("net.pipe://localhost/BotService"));

            service = factory.CreateChannel();
        }