static async Task Main(string[] args) { var options = new ConfigurationBuilder().AddJsonFile("appsettings.Development.json").Build() ?? throw new ArgumentNullException( "new ConfigurationBuilder().AddJsonFile(\"appsettings.Development.json\").Build()"); ServiceCollection services = new ServiceCollection(); services.AddScoped <IMongoDatabase>(x => new MongoClient(options["MongoDbConnectionString"]).GetDatabase("GameBot")); services.AddSingleton <ITelegramBotClient>(x => new TelegramBotClient(options.GetSection("GameBot")["ApiToken"])); services.AddSingleton <GameBot>(); services.AddScoped <ExceptionHandler>(); services.AddScoped <GameObjectBuilder>(); services.AddScoped <UserStateReaction>(); services.AddScoped <StartCommand>(); services.AddScoped <HelpCommand>(); services.AddScoped <SosCommand>(); services.AddScoped <InlineQueryResolver>(); services.AddScoped <BasicTextInputsResolver>(); services.AddScoped <QuestExampleHandler>(); services.AddScoped <ExampleCallbackQuery>(); services.AddScoped <ExampleButtonHandler>(); var manager = new UpdatePollingManager <GameBot>(ConfigureBot(), new BotServiceProvider(services.BuildServiceProvider())); var requestFilter = new GetUpdatesRequest(); requestFilter.AllowedUpdates = new[] { UpdateType.Message, UpdateType.CallbackQuery, UpdateType.InlineQuery }; await manager.RunAsync(); }
private void fetchUpdates() { if (fetchReq != null) { return; } fetchReq = new GetUpdatesRequest(lastMessageId); fetchReq.Success += updates => { if (updates?.Presence != null) { foreach (var channel in updates.Presence) { addChannel(AvailableChannels.Find(c => c.Id == channel.Id)); } foreach (var group in updates.Messages.GroupBy(m => m.ChannelId)) { careChannels.Find(c => c.Id == group.Key)?.AddNewMessages(group.ToArray()); } lastMessageId = updates.Messages.LastOrDefault()?.Id ?? lastMessageId; } fetchReq = null; }; fetchReq.Failure += delegate { fetchReq = null; }; api.Queue(fetchReq); }
public void Should_Properly_Serialize_Request_With_Custom_Json_Settings() { GetUpdatesRequest request = new GetUpdatesRequest { Offset = 12345 }; var settings = new JsonSerializerSettings { NullValueHandling = NullValueHandling.Include, ContractResolver = new CamelCasePropertyNamesContractResolver { IgnoreSerializableAttribute = true, IgnoreShouldSerializeMembers = true }, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Unspecified }; string serializeRequest = JsonConvert.SerializeObject(request, settings); Assert.DoesNotContain(@"""MethodName""", serializeRequest); Assert.DoesNotContain(@"""method_name""", serializeRequest); Assert.DoesNotContain(@"""IsWebhookResponse""", serializeRequest); Assert.DoesNotContain(@"""is_webhook_response""", serializeRequest); Assert.Contains(@"""offset"":12345", serializeRequest); Assert.DoesNotContain(@"""allowed_updates""", serializeRequest); }
public async Task GetUpdatesAsync(CancellationToken token) { _isReceiving = true; GetUpdatesRequest getUpdates = new GetUpdatesRequest() { Offset = 0, Timeout = (int)TimeSpan.FromMinutes(1).TotalSeconds, AllowedUpdates = new string[] { "message" } }; while (!token.IsCancellationRequested) { using var response = await _client.PostJsonAsync($"/bot{_botToken}/getUpdates", getUpdates); var updates = await response.DeserializeFromJson <TelegramResponse <IReadOnlyList <Update> > >(); _logger.LogDebug($"Telegram got {updates.Result?.Count} updates"); if (updates.Result == null) { continue; } foreach (var u in updates.Result) { OnMessageReceived?.Invoke(this, new MessageReceivedEventArgs() { Message = u.Message }); getUpdates.Offset = u.UpdateId + 1; } } _isReceiving = false; }
public async Task GetUpdates(Player player) { try { Log("*** GetUpdates: player {0}", player.Id); var request = new GetUpdatesRequest { Player = player }; using (var call = client.GetUpdates(request)) { var responseStream = call.ResponseStream; Log("waiting"); while (await responseStream.MoveNext()) { Log("awaiting"); var update = responseStream.Current; Log(update.Player); this.assignment = new Assignment(); this.assignment.ConnectionString = update.Player.Assignment; } } } catch (RpcException e) { Log("RPC failed " + e); throw; } }
public void Should_Serialize_Request() { GetUpdatesRequest request = new GetUpdatesRequest { Offset = 12345 }; string serializeRequest = JsonConvert.SerializeObject(request); Assert.DoesNotContain(@"""MethodName""", serializeRequest); Assert.DoesNotContain(@"""IsWebhookResponse""", serializeRequest); }
public void Should_Serialize_Request() { GetUpdatesRequest request = new GetUpdatesRequest { Offset = 12345 }; string serializeRequest = JsonSerializer.Serialize(request, new JsonSerializerOptions(JsonSerializerDefaults.Web)); Assert.DoesNotContain(@"""MethodName""", serializeRequest); Assert.DoesNotContain(@"""IsWebhookResponse""", serializeRequest); }
public async Task RunAsync( GetUpdatesRequest requestParams = default, CancellationToken cancellationToken = default ) { var bot = (TBot)_rootProvider.GetService(typeof(TBot)); await bot.Client.DeleteWebhookAsync(cancellationToken : cancellationToken) .ConfigureAwait(false); requestParams ??= new GetUpdatesRequest { Offset = 0, Timeout = 500, AllowedUpdates = Array.Empty <UpdateType>(), }; while (!cancellationToken.IsCancellationRequested) { try { Update[] updates = await bot.Client.MakeRequestAsync( requestParams, cancellationToken ).ConfigureAwait(false); foreach (var update in updates) { using var scopeProvider = _rootProvider.CreateScope(); var context = new UpdateContext(bot, update, scopeProvider); // ToDo deep clone bot instance for each update await _updateDelegate(context, cancellationToken) .ConfigureAwait(false); } if (updates.Length > 0) { requestParams.Offset = updates[updates.Length - 1].Id + 1; } } catch (HttpRequestException e) { Console.WriteLine($"[{DateTime.Now}] {e.Message}"); } catch (Exception e) { Console.WriteLine($"[{DateTime.Now}] {e}"); } } cancellationToken.ThrowIfCancellationRequested(); }
public async Task RunAsync( GetUpdatesRequest requestParams = default, CancellationToken cancellationToken = default ) { var bot = (TBot)_rootProvider.GetService(typeof(TBot)); await bot.Client.DeleteWebhookAsync(cancellationToken) .ConfigureAwait(false); requestParams = requestParams ?? new GetUpdatesRequest { Offset = 0, Timeout = 500, AllowedUpdates = new UpdateType[0], }; while (!cancellationToken.IsCancellationRequested) { Update[] updates = await bot.Client.MakeRequestAsync( requestParams, cancellationToken ).ConfigureAwait(false); foreach (var update in updates) { using (var scopeProvider = _rootProvider.CreateScope()) { var context = new UpdateContext(bot, update, scopeProvider); // update telegram bot user state. var stateService = scopeProvider.GetService <IStateCacheService>(); if (stateService != null) { stateService.CacheContext(context); } // ToDo deep clone bot instance for each update await _updateDelegate(context) .ConfigureAwait(false); } } if (updates.Length > 0) { requestParams.Offset = updates[updates.Length - 1].Id + 1; } } cancellationToken.ThrowIfCancellationRequested(); }
protected override Task Poll() { if (!api.IsLoggedIn) { return(base.Poll()); } var fetchReq = new GetUpdatesRequest(lastMessageId); var tcs = new TaskCompletionSource <bool>(); fetchReq.Success += updates => { if (updates?.Presence != null) { foreach (var channel in updates.Presence) { // we received this from the server so should mark the channel already joined. channel.Joined.Value = true; joinChannel(channel); } //todo: handle left channels handleChannelMessages(updates.Messages); foreach (var group in updates.Messages.GroupBy(m => m.ChannelId)) { JoinedChannels.FirstOrDefault(c => c.Id == group.Key)?.AddNewMessages(group.ToArray()); } lastMessageId = updates.Messages.LastOrDefault()?.Id ?? lastMessageId; } if (!channelsInitialised) { channelsInitialised = true; // we want this to run after the first presence so we can see if the user is in any channels already. initializeChannels(); } tcs.SetResult(true); }; fetchReq.Failure += _ => tcs.SetResult(false); api.Queue(fetchReq); return(tcs.Task); }
private void fetchUpdates() { fetchMessagesScheduleder?.Cancel(); fetchMessagesScheduleder = Scheduler.AddDelayed(() => { var fetchReq = new GetUpdatesRequest(lastMessageId); fetchReq.Success += updates => { if (updates?.Presence != null) { foreach (var channel in updates.Presence) { if (!channel.Joined.Value) { // we received this from the server so should mark the channel already joined. channel.Joined.Value = true; JoinChannel(channel); } } if (!channelsInitialised) { channelsInitialised = true; // we want this to run after the first presence so we can see if the user is in any channels already. initializeChannels(); } //todo: handle left channels handleChannelMessages(updates.Messages); foreach (var group in updates.Messages.GroupBy(m => m.ChannelId)) { JoinedChannels.FirstOrDefault(c => c.Id == group.Key)?.AddNewMessages(group.ToArray()); } lastMessageId = updates.Messages.LastOrDefault()?.Id ?? lastMessageId; } fetchUpdates(); }; fetchReq.Failure += delegate { fetchUpdates(); }; api.Queue(fetchReq); }, update_poll_interval); }
public void Should_Properly_Serialize_Request_With_Custom_Json_Settings() { GetUpdatesRequest request = new GetUpdatesRequest { Offset = 12345 }; string serializeRequest = JsonSerializer.Serialize(request, new JsonSerializerOptions(JsonSerializerDefaults.Web)); Assert.DoesNotContain(@"""MethodName""", serializeRequest); Assert.DoesNotContain(@"""method_name""", serializeRequest); Assert.DoesNotContain(@"""IsWebhookResponse""", serializeRequest); Assert.DoesNotContain(@"""is_webhook_response""", serializeRequest); Assert.Contains(@"""offset"":12345", serializeRequest); Assert.DoesNotContain(@"""allowed_updates""", serializeRequest); }
/// <summary> /// Will attempt to throw the last update using offset set to -1. /// </summary> /// <param name="botClient"></param> /// <param name="cancellationToken"></param> /// <returns> /// Update ID of the last <see cref="Update"/> increased by 1 if there were any /// </returns> internal static async Task <int> ThrowOutPendingUpdatesAsync( this ITelegramBotClient botClient, CancellationToken cancellationToken = default) { var request = new GetUpdatesRequest { Limit = 1, Offset = -1, Timeout = 0, AllowedUpdates = Array.Empty <UpdateType>(), }; var updates = await botClient.MakeRequestAsync(request : request, cancellationToken : cancellationToken) .ConfigureAwait(false); #if NETCOREAPP3_1_OR_GREATER if (updates.Length > 0) { return(updates[^ 1].Id + 1);
public GetUpdatesResponse GetUpdates(GetUpdatesRequest request) { return(Post <GetUpdatesResponse>("GetUpdates", request)); }
public GetUpdatesResponse GetUpdates(GetUpdatesRequest getUpdatesRequest) { Log.Info(nameof(GetUpdates)); return(GetUpdatesResponse.Parse(ExecuteAction(getUpdatesRequest))); }
public GetUpdatesResponse GetUpdates(GetUpdatesRequest getUpdatesRequest) { return(GetUpdatesResponse.Parse(ExecuteAction(getUpdatesRequest))); }
/// <inheritdoc /> public async Task ReceiveAsync( IUpdateHandler updateHandler, CancellationToken cancellationToken = default) { if (updateHandler is null) { throw new ArgumentNullException(nameof(updateHandler)); } var allowedUpdates = _receiverOptions?.AllowedUpdates; var limit = _receiverOptions?.Limit ?? default; var messageOffset = _receiverOptions?.Offset ?? 0; var emptyUpdates = EmptyUpdates; if (_receiverOptions?.ThrowPendingUpdates is true) { try { messageOffset = await _botClient.ThrowOutPendingUpdatesAsync( cancellationToken : cancellationToken ); } catch (OperationCanceledException) { // ignored } } while (!cancellationToken.IsCancellationRequested) { var timeout = (int)_botClient.Timeout.TotalSeconds; var updates = emptyUpdates; try { var request = new GetUpdatesRequest { Limit = limit, Offset = messageOffset, Timeout = timeout, AllowedUpdates = allowedUpdates, }; updates = await _botClient.MakeRequestAsync( request : request, cancellationToken : cancellationToken ).ConfigureAwait(false); } catch (OperationCanceledException) { // Ignore } catch (Exception exception) { try { await updateHandler.HandleErrorAsync( botClient : _botClient, exception : exception, cancellationToken : cancellationToken ).ConfigureAwait(false); } catch (OperationCanceledException) { // ignored } } foreach (var update in updates) { try { await updateHandler.HandleUpdateAsync( botClient : _botClient, update : update, cancellationToken : cancellationToken ).ConfigureAwait(false); messageOffset = update.Id + 1; } catch (OperationCanceledException) { // ignored } } } }
public GetUpdatesResponse GetUpdates(GetUpdatesRequest getUpdatesRequest) { return GetUpdatesResponse.Parse(ExecuteAction(getUpdatesRequest)); }