Exemple #1
0
        public static async Task GetCustomWebhookInfoAsync()
        {
            ///TODO: GetWebhookInfo
            WebhookInfo webhookInfo = await Consts.botClient.GetWebhookInfoAsync();

            string allUpd = "[";

            if (webhookInfo.AllowedUpdates != null)
            {
                foreach (var item in webhookInfo.AllowedUpdates)
                {
                    allUpd += item.ToString() + "|";
                }
                allUpd += "]";
            }
            else
            {
                allUpd = "null";
            }

            await Consts.botClient.SendTextMessageAsync(Consts.chatId, "CustomMiddleware GetWebhookInfoAsync:" +
                                                        "\nUrl : " + webhookInfo.Url +
                                                        "\nHas cust sert : " + webhookInfo.HasCustomCertificate.ToString() +
                                                        "\nPending upd : " + webhookInfo.PendingUpdateCount.ToString() +
                                                        "\nLastErrorDate : " + webhookInfo.LastErrorDate.ToString() +
                                                        "\nLastErrorMsg : " + webhookInfo.LastErrorMessage +
                                                        "\nMax conn : " + webhookInfo.MaxConnections.ToString() +
                                                        "\nAllowedUpdates : " + allUpd);
        }
Exemple #2
0
        public async Task Should_Set_Webhook_With_SelfSigned_Cert()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldSetWebhookWithCertificate);

            const string url            = "https://www.telegram.org/";
            const int    maxConnections = 5;

            using (var stream = File.OpenRead(Constants.FileNames.Certificate.PublicKey))
            {
                await BotClient.SetWebhookAsync(
                    url : url,
                    certificate : stream,
                    maxConnections : maxConnections,
                    allowedUpdates : new UpdateType[0]
                    );
            }

            WebhookInfo info = await BotClient.GetWebhookInfoAsync();

            Assert.Equal(url, info.Url);
            Assert.True(info.HasCustomCertificate);
            Assert.Equal(maxConnections, info.MaxConnections);
            Assert.Null(info.AllowedUpdates);

            await BotClient.DeleteWebhookAsync();
        }
Exemple #3
0
        public async Task Should_Get_Deleted_Webhook_Info()
        {
            WebhookInfo info = await BotClient.GetWebhookInfoAsync();

            Assert.Empty(info.Url);
            Assert.False(info.HasCustomCertificate);
            Assert.Equal(0, info.MaxConnections);
            Assert.Null(info.AllowedUpdates);
        }
Exemple #4
0
        public async Task Should_Get_Deleted_Webhook_Info()
        {
            await _fixture.SendTestCaseNotificationAsync(FactTitles.ShouldGetDeletedWebhookInfo);

            WebhookInfo info = await BotClient.GetWebhookInfoAsync();

            Assert.Empty(info.Url);
            Assert.False(info.HasCustomCertificate);
            Assert.Equal(default, info.MaxConnections);
Exemple #5
0
        /// <summary>
        ///     Creates a webhook.
        /// </summary>
        /// <param name="authorization">
        ///     An &lt;a href&#x3D;\&quot;#\&quot; onclick&#x3D;\&quot;this.href&#x3D;oauthDoc()\&quot;
        ///     oncontextmenu&#x3D;\&quot;this.href&#x3D;oauthDoc()\&quot; target&#x3D;\&quot;oauthDoc\&quot;&gt;OAuth Access Token
        ///     &lt;/a&gt; with scopes:&lt;ul&gt;&lt;li style&#x3D;&#39;list-style-type: square&#39;&gt;&lt;a href&#x3D;\&quot;#\
        ///     &quot; onclick&#x3D;\&quot;this.href&#x3D;oauthDoc(&#39;webhook_write&#39;)\&quot; oncontextmenu&#x3D;\&quot;
        ///     this.href&#x3D;oauthDoc(&#39;webhook_write&#39;)\&quot; target&#x3D;\&quot;oauthDoc\&quot;&gt;webhook_write&lt;/a
        ///     &gt;&lt;/li&gt;&lt;/ul&gt;in the format &lt;b&gt;&#39;Bearer {accessToken}&#39;.
        /// </param>
        /// <param name="webhookInfo">Information about the webhook that you want to create</param>
        /// <param name="xApiUser">
        ///     The userId or email of API caller using the account or group token in the format &lt;b&gt;
        ///     userid:{userId} OR email:{email}.&lt;/b&gt; If it is not specified, then the caller is inferred from the token.
        /// </param>
        /// <param name="xOnBehalfOfUser">
        ///     The userId or email in the format &lt;b&gt;userid:{userId} OR email:{email}.&lt;/b&gt; of
        ///     the user that has shared his/her account
        /// </param>
        /// <returns>WebhookCreationResponse</returns>
        public WebhookCreationResponse CreateWebhook(string authorization, WebhookInfo webhookInfo, string xApiUser, string xOnBehalfOfUser)
        {
            // verify the required parameter 'authorization' is set
            if (authorization == null)
            {
                throw new ApiException(400, "Missing required parameter 'authorization' when calling CreateWebhook");
            }

            // verify the required parameter 'webhookInfo' is set
            if (webhookInfo == null)
            {
                throw new ApiException(400, "Missing required parameter 'webhookInfo' when calling CreateWebhook");
            }


            string path = "/webhooks";

            path = path.Replace("{format}", "json");

            Dictionary <string, string>        queryParams  = new Dictionary <string, string>();
            Dictionary <string, string>        headerParams = new Dictionary <string, string>();
            Dictionary <string, string>        formParams   = new Dictionary <string, string>();
            Dictionary <string, FileParameter> fileParams   = new Dictionary <string, FileParameter>();
            string postBody = null;

            if (authorization != null)
            {
                headerParams.Add("Authorization", ApiClient.ParameterToString(authorization));                        // header parameter
            }
            if (xApiUser != null)
            {
                headerParams.Add("x-api-user", ApiClient.ParameterToString(xApiUser));                   // header parameter
            }
            if (xOnBehalfOfUser != null)
            {
                headerParams.Add("x-on-behalf-of-user", ApiClient.ParameterToString(xOnBehalfOfUser)); // header parameter
            }
            postBody = ApiClient.Serialize(webhookInfo);                                               // http body (model) parameter

            // authentication setting, if any
            string[] authSettings = { };

            // make the HTTP request
            IRestResponse response = (IRestResponse)ApiClient.CallApi(path, Method.POST, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

            if ((int)response.StatusCode >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling CreateWebhook: " + response.Content, response.Content);
            }
            if ((int)response.StatusCode == 0)
            {
                throw new ApiException((int)response.StatusCode, "Error calling CreateWebhook: " + response.ErrorMessage, response.ErrorMessage);
            }

            return((WebhookCreationResponse)ApiClient.Deserialize(response.Content, typeof(WebhookCreationResponse), response.Headers));
        }
        /// <summary>Initializer method.</summary>
        public static void Initialize(Dictionary <ulong, string> initDict)
        {
            webhooks = new WebhookInfo[initDict.Count];

            int i = 0;

            foreach (ulong id in initDict.Keys)
            {
                string token = initDict[id];

                webhooks[i++] = new WebhookInfo(id, token);
            }
        }
Exemple #7
0
    public static HtmlMessage ParseWebHookInfo(this WebhookInfo webhookInfo)
    {
        var htmlMessage = HtmlMessage.Empty
                          .Bold("EngineMode: ").TextBr("WebHook")
                          .Bold("URL: ").TextBr(webhookInfo.Url)
                          .Bold("Custom Cert: ").TextBr(webhookInfo.HasCustomCertificate.ToString())
                          .Bold("Allowed Updates: ").TextBr(webhookInfo.AllowedUpdates?.ToString())
                          .Bold("Pending Count: ").TextBr((webhookInfo.PendingUpdateCount - 1).ToString())
                          .Bold("Max Connection: ").TextBr(webhookInfo.MaxConnections.ToString())
                          .Bold("Last Error: ").TextBr(webhookInfo.LastErrorDate?.ToDetailDateTimeString())
                          .Bold("Error Message: ").TextBr(webhookInfo.LastErrorMessage);

        return(htmlMessage);
    }
Exemple #8
0
        static void Main(string[] args)
        {
            // Disable Cache

            bot.DeleteWebhookAsync();
            // bot.SetWebhookAsync("https://tahaelectric.com");
            WebhookInfo inf = bot.GetWebhookInfoAsync().Result;

            OnMessageRecived += Program_OnMessageRecived;
            Console.Title     = "Server is Running . . .";
            while (true)
            {
                OnMessageRecived("But is Runing ...", ConsoleColor.Green);
                GetUpdates();
                string Input = Console.ReadLine();
            }
        }
Exemple #9
0
        public BotService(IOptions <BotConfiguration> config)
        {
            _config = config.Value;
            Client  = new TelegramBotClient(_config.BotToken);
            WebhookInfo webhoks = Client.GetWebhookInfoAsync().Result;

            if (webhoks != null)
            {
                Client.DeleteWebhookAsync().Wait();
            }

            if (!string.IsNullOrEmpty(_config.CallbackUrl))
            {
                var hook = _config.CallbackUrl;
                Client.SetWebhookAsync(hook).Wait();
            }
        }
Exemple #10
0
        public async Task Should_Set_Webhook_With_SelfSigned_Cert()
        {
            await using (Stream stream = File.OpenRead(Constants.PathToFile.Certificate.PublicKey))
            {
                await BotClient.SetWebhookAsync(
                    url : "https://www.telegram.org/",
                    certificate : stream,
                    maxConnections : 3,
                    allowedUpdates : Array.Empty <UpdateType>() // send all types of updates
                    );
            }

            WebhookInfo info = await BotClient.GetWebhookInfoAsync();

            Assert.Equal("https://www.telegram.org/", info.Url);
            Assert.True(info.HasCustomCertificate);
            Assert.Equal(3, info.MaxConnections);
            Assert.Null(info.AllowedUpdates);
        }
Exemple #11
0
        public async Task Start(CancellationToken cancellationToken = default)
        {
            _client = await _clientFactory.Create(_options.Connection.ApiToken);

            // webhooks not supported
            WebhookInfo webhookInfo = await _client.GetWebhookInfoAsync(cancellationToken);

            if (!string.IsNullOrEmpty(webhookInfo.Url))
            {
                _logger.LogWarning("A webhook is set up on the server. Deleting...");
                await _client.DeleteWebhookAsync(cancellationToken);
            }

            _client.OnMessage       += OnClientMessage;
            _client.OnCallbackQuery += OnCallbackQuery;
            _client.StartReceiving(AllowedUpdates, cancellationToken);
            _logger.LogInformation("Started receiving updates.");

            _cancellationToken = cancellationToken;
        }
Exemple #12
0
        private static async Task <WebhookCreationResponse> CreateWebhook()
        {
            HttpClient client = CreateClient(_apiAccessPoint);

            WebhookInfo model = new WebhookInfo
            {
                Name  = "Webhook 1",
                Scope = StaticData.Scope.User,
                State = "ACTIVE",
                WebhookSubscriptionEvents = new[]
                {
                    //StaticData.Event.AgreementCreated,
                    StaticData.Event.AgreementActionCompleted,
                },
                WebhookUrlInfo = new WebhookUrlInfo {
                    Url = AzureFunctionUrl
                },
                ApplicationName          = "ApplicationName",
                ApplicationDisplayName   = "ApplicationDisplayName",
                WebhookConditionalParams = new WebhookConditionalParams
                {
                    WebhookAgreementEvents = new WebhookAgreementEvents
                    {
                        IncludeDetailedInfo = true,
                        //IncludeDocumentsInfo = true,
                        IncludeSignedDocuments = true,
                    }
                }
            };

            string json = JsonConvert.SerializeObject(model);
            HttpResponseMessage responseMesage = await client.PostAsync("webhooks", new StringContent(json, Encoding.UTF8, "application/json"));

            WebhookCreationResponse response = await HandleResponseMessageAsync <WebhookCreationResponse>(responseMesage);

            return(response);
        }
        /// <summary>
        /// Updates a webhook.
        /// </summary>
        /// <param name="ifMatch">The server will only update the resource if it matches the listed ETag otherwise error RESOURCE_MODIFIED(412) is returned.</param>
        /// <param name="webhookId">The webhook identifier, as returned by the webhook creation API or retrieved from the API to fetch webhooks.</param>
        /// <param name="webhookInfo">Information necessary to update a webhook</param>
        /// <param name="xApiUser">The userId or email of API caller using the account or group token in the format &lt;b&gt;userid:{userId} OR email:{email}.&lt;/b&gt; If it is not specified, then the caller is inferred from the token.</param>
        /// <param name="xOnBehalfOfUser">The userId or email in the format &lt;b&gt;userid:{userId} OR email:{email}.&lt;/b&gt; of the user that has shared his/her account</param>
        /// <returns></returns>
        public void UpdateWebhook(string ifMatch, string webhookId, WebhookInfo webhookInfo, string xApiUser = null, string xOnBehalfOfUser = null)
        {
            // verify the required parameter 'authorization' is set


            // verify the required parameter 'ifMatch' is set
            if (ifMatch == null)
            {
                throw new ApiException(400, "Missing required parameter 'ifMatch' when calling UpdateWebhook");
            }

            // verify the required parameter 'webhookId' is set
            if (webhookId == null)
            {
                throw new ApiException(400, "Missing required parameter 'webhookId' when calling UpdateWebhook");
            }

            // verify the required parameter 'webhookInfo' is set
            if (webhookInfo == null)
            {
                throw new ApiException(400, "Missing required parameter 'webhookInfo' when calling UpdateWebhook");
            }


            var path = "/webhooks/{webhookId}";

            path = path.Replace("{format}", "json");
            path = path.Replace("{" + "webhookId" + "}", ApiClient.ParameterToString(webhookId));

            var    queryParams  = new Dictionary <String, String>();
            var    headerParams = new Dictionary <String, String>();
            var    formParams   = new Dictionary <String, String>();
            var    fileParams   = new Dictionary <String, FileParameter>();
            String postBody     = null;


            if (xApiUser != null)
            {
                headerParams.Add("x-api-user", ApiClient.ParameterToString(xApiUser));        // header parameter
            }
            if (xOnBehalfOfUser != null)
            {
                headerParams.Add("x-on-behalf-of-user", ApiClient.ParameterToString(xOnBehalfOfUser));               // header parameter
            }
            if (ifMatch != null)
            {
                headerParams.Add("If-Match", ApiClient.ParameterToString(ifMatch)); // header parameter
            }
            postBody = ApiClient.Serialize(webhookInfo);                            // http body (model) parameter

            // authentication setting, if any
            String[] authSettings = new String[] {  };

            // make the HTTP request
            IRestResponse response = (IRestResponse)ApiClient.CallApi(path, Method.PUT, queryParams, postBody, headerParams, formParams, fileParams, authSettings);

            if (((int)response.StatusCode) >= 400)
            {
                throw new ApiException((int)response.StatusCode, "Error calling UpdateWebhook: " + response.Content, response.Content);
            }
            else if (((int)response.StatusCode) == 0)
            {
                throw new ApiException((int)response.StatusCode, "Error calling UpdateWebhook: " + response.ErrorMessage, response.ErrorMessage);
            }

            return;
        }
 private bool ValidateWebhookUri(WebhookInfo webHookInfo)
 {
     return(string.Equals(webHookInfo.Url, _options.Webhook.Url));
 }
Exemple #15
0
        public async Task <string> GetWebhookInfoJsonAsync()
        {
            WebhookInfo info = await Client.GetWebhookInfoAsync();

            return(JsonConvert.SerializeObject(info));
        }