Telegram api ssl error

Telegram Bot SSL Error So I have made a small script on my website for my telegram bot. Only problem is that if I set my URL as webhook for the bot it gives an SSL error. Also tried to add an self signed certificate, so has_custom_certificate turned to true, but the same error […]

Содержание

  1. Telegram Bot SSL Error
  2. 2 Answers 2
  3. How to check your certificate:
  4. How to fix:
  5. Ошибка проверки сертификата SSLError python telebot при подключении через proxy
  6. 1 ответ 1
  7. Telegram webhook: Why i get ssl3_get_server_certificate:certificate verify failed Error when i call GetWebhookInfo API command?
  8. Self-Signed Certificate way
  9. Got problems with webhook to Telegram Bot API
  10. 10 Answers 10
  11. webhook is unable to verify ssl cert #299
  12. Comments
  13. I am able to use Postman to call to webhook URL and trigger the bot event.
  14. I am able to cat the SSL cert and key inside the docker container
  15. My code:
  16. I tried to follow HTTPS webhook example as well, but it stuck after launch and unable to receive any message from Telegram, with pending_update_count equals 2:

Telegram Bot SSL Error

So I have made a small script on my website for my telegram bot. Only problem is that if I set my URL as webhook for the bot it gives an SSL error.

Also tried to add an self signed certificate, so has_custom_certificate turned to true, but the same error appeared.

What am I doing wrong?

2 Answers 2

You have to create a self-signed certificate for deploying your server over https. If you are using flask you can follow this nice tutorial — https://blog.miguelgrinberg.com/post/running-your-flask-application-over-https

The problem is with your certificate.

The error in your getWebHookInfo:

Is Telegram saying that it needs the whole certificate chain (it’s also called CA Bundle or full chained certificate).

How to check your certificate:

You can use the SSL Labs SSL Server Test service to check your certificate:

Just pass your URL like the following example, replacing coderade.github.io with your host:

If you see «Chain issues: Incomplete» you do not serve a full chained certificate.

How to fix:

You need to add all the three needed files (.key, .crt, and .ca-bundle). The Namecheap has very good documentation of how to install an SSL certificate in your site in many different ways, like Apache, Node.js, Nginx and etc. Please, check if you can follow one of the available ways: Namecheap — How to Install SSL certificates

Anyway, you need to download the full chained certificate for your SSL certificate provider and install this on your webserver.

I don’t know which service you are using, but for my example, with gunicorn I solved adding the ca-certs with ca-bundle file sent by my SSL Certificate provider (In my case Namecheap Comodo) on my SSL configuration, like the following example:

For further information: @martini answer on this thread and the FIX: Telegram Webhooks Not Working post.

Источник

Ошибка проверки сертификата SSLError python telebot при подключении через proxy

Работаю через корпоративную сеть, есть потребность написать телеграмм бота, пробовал различные библиотеки ( telebot, telepot, telegram, airogram ). Везде сталкиваюсь с проблемой доступа через корпоративный прокси. Сейчас остановился на telebot, подсунул прокси, теперь ошибка с проверкой сертификата. Пробовал использовать http, https, socks5, socks5h, socks4 успеха не принесло.

Получаю в ответ ошибку.

Попробовал общаться через request с телегой, удалось подключиться, только после отключения проверки ssl session.verify = False . Но через запросы очень проблематично писать, собственно и библиотек для этого куча есть.

1 ответ 1

Попробуйте напрямую модифицировать библиотеку для работы с API телеграмма.

Если вы устанавливали библиотеку напрямую в python, то она находится в следующей директории:

Если в виртуальном окружении работаете, то она находится в:

Находите модуль отвечающий за запросы, в большинстве библиотек для взаимодействия с API его проектируют так, что запросы выполняются в одной функции, её и надо модифицировать. На примере я показываю pyTelegramBotAPI, функция _make_request лежит в ../Lib/site-packages/telebot/apihelper.py и выглядит так (код частично срезан чтобы выделить главные детали):

В pyTelegramBotAPI _get_req_session() возвращает объект requests.Session(), а значит чтобы убрать сертификат или добавить свой, здесь хватит модифицировать строки с отправкой запроса (в примере кода отключается проверка сертификата):

Если библиотека асинхронная, там используется aiohttp, как там работать с сертификатами описано в документации. Я привёл пример только с одной синхронной библиотекой, но во всех +- принцип решения данной проблемы такой же.

Источник

Telegram webhook: Why i get ssl3_get_server_certificate:certificate verify failed Error when i call GetWebhookInfo API command?

I bought a wildcard SSL certification for my domain and its subdomains and installed it on my server and bound to the website (in IIS).

It show green secure HTTPS in browser.

I used Telegram SetWebhook with my webhook URL (Something like this: https://webhook.example.com/api/WebhookAction/ )

But when i run Telegram GetWebhookInfo it return certificate verify failed error:

What do you think about this problem?

  • Should i change the Webhook Url to a None-SubDomain address like this: https://mydomain:8443/api/WebhookAction ?
  • Has my SSL any problem (for example should be a None-Wildcard SSL)?

Edit

Self-Signed Certificate way

A) I Created a Self Signed Certificate by the following OpenSSL command instead of the Wildcard SSL

B) Then i created a PFX from the output files by this command:

C) Then i installed the MyDomain.pfx on the server and bind it to the Https://webhook.mydomain.com .

D) Also i used the MyDomain_public.pem file in the SetWebhook command as the certification file (with both a third library and Curl command).

The Curl command:

But when i call GetWebhookInfo API command, it return this error:

Источник

Got problems with webhook to Telegram Bot API

Why is my webhook not working? I do not get any data from telegram bot API. Here is the detailed explanation of my problem:

I got SSL cert from StartSSL, it works fine on my website (according to GeoCerts SSL checker), but still seems like my webhook to Telegram Bot API doesn’t work (despite it says that webhook was set I do not get any data).

I am making a webhook to my script on my website in this form:

I get this text in response:

So it must be working, but it actually doesn’t.

Here is my script code:

I don’t actually receive any data to $update. So webhook is not working. Why?

10 Answers 10

Just another one moment, why your webhooks not work.

In my case the reason was in allowed_updates webhook parameter.

It means, that your bot can’t react to your text messages, and you will not receive any webhooks!

You can note, that «allowed_updates» contains array. So, currently it will react only to inline button events (passed as keyboard layout!). According to the setWebhook documentation, allowed_updates is an «optional» parameter.

To start receieve text messages, you need to add «message» to your «allowed_updates» prop. To do it, just again set your webhooks and add it to query. Like here :

You will receive something like «url already added», but don’t worry, allowed_updates will be updated even in this case. Just try type your message to bot and test your webhooks.

That’s all, now, telegram will send webhooks to each direct message from you to your bot. Hope, it helps someone.

Источник

webhook is unable to verify ssl cert #299

However, I received the following error when calling getWebHookInfo :

I am able to use Postman to call to webhook URL and trigger the bot event.

I am able to cat the SSL cert and key inside the docker container

My code:

I tried to follow HTTPS webhook example as well, but it stuck after launch and unable to receive any message from Telegram, with pending_update_count equals 2:

Much appreciate if you can point out any of my mistake above, as I was stuck for couple days already.

The text was updated successfully, but these errors were encountered:

Connection to https://siutsin.com is timing out! Can’t seem to connect to your server.

The first guess off my head is that you are having an issue with your SSL certificates.

@GochoMugo I turned off the testing instance. As you can see from the postman’s screenshot. POST to https returns OK. The SSL cert is generated from GoDaddy.

I have not used SSL certs from GoDaddy before, so I can not comment on that.

Side note: However, you might consider running a reverse proxy, say Nginx, that handles all the SSL stuff. That way you don’t have to use SSL certs in your container. That setup seems easier to me.

Thanks for the hint and good point @GochoMugo, will try it out in the weekend

@siutsin have you signed you certificate? I generated a root certificate and sign the other one that I used for webhook. Before that I got the same exact error.

@arashthk it’s not a self-signed certificate, I got it from Godaddy.

@arashthk it’s not a self-signed certificate, I got it from Godaddy.

Hi @siutsin. Have you solved the problem? I have same issue.
Probably problem with certificates but, it have been working before.

Hey @GuillermoPena sorry I changed my architecture so I am not able to verify this issue now.

Thanks @siutsin
@arashthk, when you created your .CSR file, you set in ‘common name’ parameter your server ip, don’t you?
I have created a root certificate and I have signed the other one but issue persists.

I meet the same problem and I’ve solved it. If you use a none-self-signed certificate, the WebhookInfo should be as follows, the has_custom_certificate should be false or you may edit your code. Now check it.

same error on let’s encrypt certificate installed by cPanel.
someone please tell the whole complete story about this god damned error!
any manual actions about putting certificate files is needed? so what.

i’m using webhook method on my framework on PHP and it works by same installed certificate like charm!
but in this unknown,un-well documented framework developed by Yagop, it’s not working.
tell a complete story please.

@makhloughi This issue was opened way back to early 2017. I am not aware of what is the new fixes or development implemented here. However, I believe it stated quite clearly in the license that there is no warranty or liability. You are on your own, and I think @yagop never forced you to use only his library.

I will suggest you open another issue and provide useful information instead.

@siutsin i’m agree with you. no one forced me to use this library. but the problem still exist and i asked if some one can help solve this issue which is appearing in google’s 1st result in SERP. all technical information is mentioned by others above and i don’t wanna open a duplicate issue and confuse same visitors.
apparently no one knows any technical solution. just chatting and advising.
if anyone can help with technical solution, please reply.
regards.

@siutsin i’m agree with you. no one forced me to use this library. but the problem still exist and i asked if some one can help solve this issue which is appearing in google’s 1st result in SERP. all technical information is mentioned by others above and i don’t wanna open a duplicate issue and confuse same visitors.
apparently no one knows any technical solution. just chatting and advising.
if anyone can help with technical solution, please reply.
regards.

Источник

@gersonfreire

I have a question or need help

Please DO NOT post it! We don’t provide support in GitHub issues any more.

We would be happy if you join our group chat on Telegram @tgbots_dotnet and ask the community to help.

If you open an issue asking for support, the issue would be closed without providing any answer.

@Ayanami251379

I have the same error. I am adding my report based on the but report guidelines.

Steps to reproduce:
Download Telegram.Bot repo
Include in project
Add calls to project
Run application
Expected behavior
Receive messages from Telegram users.
Actual behavior
Receiving Error: «An error occurred while sending the request.» & vbCrLf & «The request was aborted: Could not create SSL/TLS secure channel.»
Screenshots
image
Environment data
Latest Telegram.Bot (Version 15.3.0, Last update 2020-02-01)
Compiler, Visual Studio 2017
.Net Version 4.5
App: Windows 10 (Desktop, Modified console app)

@Chrislie7

@Ayanami251379 i have some problem but im on production, Maybe anyone can help?

@Serproger

The same problem reproduces for old library version (14.10.0). Our bot isn’t working.

@zkolobov

@bukanfarid

Well same here. but my application works just fine around 18 hours ago with old library version (13.x.x).
Updated to the latest version but still not working.

@Mahdi-Farhani

@bukanfarid Me 2, My bot works fine about 12Hrs ago I’ve used V14.x.x
also, I update to the new version but it won’t work

@Sitedh

I have some issue, that appeared this morning
Version of Telegram.Bot: 14.10.0.0
.Net Version: 4.6.1
System: Windows 10
App type: Console

@Chrislie7

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

before :
var me = await Bot.GetMeAsync();

this is working for me

Sitedh, dturevski, Mahdi-Farhani, falcantara79, Garfius, RangerRU, SergeyShabanov, MaxKlaxxMiner, VladTishchenko, bermoodastar, and 5 more reacted with thumbs up emoji
SergeyShabanov and ToxaDev reacted with heart emoji

@bukanfarid

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12

Thanks for your reply @Chrislie7 , i tried it and it working like a charm! 👍

@Ayanami251379

System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

before :
var me = await Bot.GetMeAsync();

this is working for me

I can confirm this is working for me as well, thank you @Chrislie7
I added the security change outside the TelegramBot library as the correct dependency is not part of the TelegramBot library.

@tuscen

So, the problem is due to Telegram disabling everything older than TLS v1.2 (which is not used as the default in .NET Framework 4.5). The best way to mitigate this problem is to update to .NET Framework 4.6-4.8 or even to .NET Core 3.1 (this is preferrable if you can do that).

If you can’t upgrade your system or .NET Framework to a newer one there might be a solution. One of the members in our group came up with a guide how it can be mitigated:

So, this is the final instruction for those who faces the problem «The request was aborted: Could not create SSL / TLS secure channel»

Windows 7 / Server 2008 R2:

  1. Update your system.

  2. If you use .NET Framework 4.5, add this line somewhere before you initialize TelegramBotClient:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

or target .NET Framework 4.6 and higher to use TLS 1.2 as default.

  1. If the error is still here, try to follow these instructions to enable TLS 1.1 and TLS 1.2 as default secure protocols in WinHTTP in Windows (https://support.microsoft.com/en-us/help/3140245/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-wi) (but this didn’t work for me until I updated my system).

Windows 8.1/Server 2012 R2 and higher:

  • use step 2 of instructions above.

@VladAlexaRW

My thanks to both @Chrislie7 and @tuscen . The solution provided works for .NET Framework 4.5.1

@amoamare

This is not working for me, even forcing Tls12 as you can see here
Version of Telegram.Bot: 15.3.0
Windows Server 2012 R2 Version 6.3 (Build 9600)
Framework installed: 4.8
Targeted Framework: 4.8
App Type: GUI

Forced Tls12 and tried to enable all of them
Just for testing in the I added the following to ensure as well.

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls13;

Created my own httpClient to pass to the bot, nothing works. Continuously getting this error since
2/5/2020 at approx 11:00PM MST works perfectly fine on Windows 10 and Windows 10 server

image

Even tried creating my own httpClient to pass to it including handler with Customer validation callback set to always true just to see if that would do anything (pretty sure it wouldn’t have but ruling it out)

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpClientHandler _httpClientHandler = new HttpClientHandler
        {
            UseProxy = false,
            ServerCertificateCustomValidationCallback = (HttpRequestMessage arg1, X509Certificate2 certificate, X509Chain arg3, SslPolicyErrors sslPolicyErrors) => { return true; }
        };
            _httpClient = new HttpClient(_httpClientHandler, false);
            Client = new TelegramBotClient("xxxxxxxxxxxxxx", _httpClient);

            var assembly = Assembly.GetExecutingAssembly();
            var attributes = assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute), false);
            var target = (TargetFrameworkAttribute)attributes[0];
            AppendText($"Target Framework: {target.FrameworkDisplayName}");
            AppendText($"Enabled Protocols: {ServicePointManager.SecurityProtocol}");

   Telegram.Bot.Types.User me;
            try
            {
                me = await Client.GetMeAsync();
            }
            catch(Exception ex) <- caught here.
            {
                AppendText(ex.ToString());
            }

The bot is also targeting dotnet 4.8
image

@amoamare

Just a quick update, I was able to resolve my issue on my Windows Server in case anyone else that may be having the same issue as me.

It appears that TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 must be enabled and you can enable this using IISCrypto
Just to be clear this was not a requirement to have before, not sure why it is now.
image

@Dragonsangel

Additionally to what @amoamare said, these are the only ciphers that are currently (2020/02/07) usable for TLS1.2 for the API (Viewable on the SSL Labs site):

TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 (0xc02f)
TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 (0xc030)
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 (0xcca8)
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 (0x9e)
TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 (0x9f)

For those on Windows Server 2012 R2, forget trying to find the first three since they are only available from Windows Server 2016 onwards.
Enabling one of the last two will allow your connections to work.

Additionally, the error message that I got was different than the one reported here, but all had to do with TLS configurations. Adding it here for the searches and knowledge.

System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
—> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception.
—> System.ComponentModel.Win32Exception: The message received was unexpected or badly formatted
this was due to the missing ciphers and the server then not responding with a «Server Hello» but with a «Fatal Alert: handshake_failure» response.

@Scryptor

Hi, i have solved this problem, setting my dns to google 8.8.8.8 and 8.8.4.4
And everything started to work
Before it you shoud use .net >= 4.6.1 or write this in your c# program,

  public Form1()
        {

            InitializeComponent();
            ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; // in .net 4.6 it's default, in 4.5 this code you need to use
        } 

Sorry for my english )

@ahvahsky2008

Set dns names to 8.8.8.8 — all works!!!

@drrobincroft

This is not working for me, even forcing Tls12 as you can see here Version of Telegram.Bot: 15.3.0 Windows Server 2012 R2 Version 6.3 (Build 9600) Framework installed: 4.8 Targeted Framework: 4.8 App Type: GUI

Forced Tls12 and tried to enable all of them Just for testing in the I added the following to ensure as well.

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls13;

Created my own httpClient to pass to the bot, nothing works. Continuously getting this error since 2/5/2020 at approx 11:00PM MST works perfectly fine on Windows 10 and Windows 10 server

image

Even tried creating my own httpClient to pass to it including handler with Customer validation callback set to always true just to see if that would do anything (pretty sure it wouldn’t have but ruling it out)

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
HttpClientHandler _httpClientHandler = new HttpClientHandler
        {
            UseProxy = false,
            ServerCertificateCustomValidationCallback = (HttpRequestMessage arg1, X509Certificate2 certificate, X509Chain arg3, SslPolicyErrors sslPolicyErrors) => { return true; }
        };
            _httpClient = new HttpClient(_httpClientHandler, false);
            Client = new TelegramBotClient("xxxxxxxxxxxxxx", _httpClient);

            var assembly = Assembly.GetExecutingAssembly();
            var attributes = assembly.GetCustomAttributes(typeof(TargetFrameworkAttribute), false);
            var target = (TargetFrameworkAttribute)attributes[0];
            AppendText($"Target Framework: {target.FrameworkDisplayName}");
            AppendText($"Enabled Protocols: {ServicePointManager.SecurityProtocol}");

   Telegram.Bot.Types.User me;
            try
            {
                me = await Client.GetMeAsync();
            }
            catch(Exception ex) <- caught here.
            {
                AppendText(ex.ToString());
            }

The bot is also targeting dotnet 4.8 image

I have finally solved this awful problem by updating windows. Believe me, adding some code or forcing tls 1.2 do not work. The only reason for this is your operating system lack some basic libraries or something like to support the communication with telegram interface.
Therefore, you should download updating packages for your windows. Take my computer with win 7 as an example, download the latest updating package collection UpdatePack7R2.exe and run it. It is big and the installation time is very costly. It may be hours. There are also many reboots. The only thing you can do is waiting. After all is done, running your program and you will find everything is fine.
Let’s praise Microsoft and Telegram!

Error handling

There will be errors when working with the API, and they must be correctly handled on the client.
An error is characterized by several parameters:

Numerical value similar to HTTP status. Contains information on the type of error that occurred: for example, a data input error, privacy error, or server error. This is a required parameter.

A string literal in the form of /[A-Z_0-9]+/ , which summarizes the problem. For example, AUTH_KEY_UNREGISTERED . This is an optional parameter.

A full machine-readable JSON list of RPC errors that can be returned by all methods in the API can be found here », what follows is a description of its fields:

  • errors — All error messages and codes for each method (object).
    • Keys: Error codes as strings (numeric strings)
    • Values: All error messages for each method (object)
      • Keys: Error messages (string)
      • Values: An array of methods which may emit this error (array of strings)
  • descriptions — Descriptions for every error mentioned in errors (and a few other errors not related to a specific method)
    • Keys: Error messages
    • Values: Error descriptions
  • user_only — A list of methods that can only be used by users, not bots.

Error messages and error descriptions may contain printf placeholders in key positions, for now only %d is used to map durations contained in error messages to error descriptions.

There should be a way to handle errors that are returned in rpc_error constructors.

Below is a list of error codes and their meanings:

The request must be repeated, but directed to a different data center.

  • FILE_MIGRATE_X: the file to be accessed is currently stored in a different data center.
  • PHONE_MIGRATE_X: the phone number a user is trying to use for authorization is associated with a different data center.
  • NETWORK_MIGRATE_X: the source IP address is associated with a different data center (for registration)
  • USER_MIGRATE_X: the user whose identity is being used to execute queries is associated with a different data center (for registration)

In all these cases, the error description’s string literal contains the number of the data center (instead of the X) to which the repeated query must be sent. More information about redirects between data centers »

The query contains errors. In the event that a request was created using a form and contains user generated data, the user should be notified that the data must be corrected before the query is repeated.

  • FIRSTNAME_INVALID: The first name is invalid
  • LASTNAME_INVALID: The last name is invalid
  • PHONE_NUMBER_INVALID: The phone number is invalid
  • PHONE_CODE_HASH_EMPTY: phone_code_hash is missing
  • PHONE_CODE_EMPTY: phone_code is missing
  • PHONE_CODE_EXPIRED: The confirmation code has expired
  • API_ID_INVALID: The api_id/api_hash combination is invalid
  • PHONE_NUMBER_OCCUPIED: The phone number is already in use
  • PHONE_NUMBER_UNOCCUPIED: The phone number is not yet being used
  • USERS_TOO_FEW: Not enough users (to create a chat, for example)
  • USERS_TOO_MUCH: The maximum number of users has been exceeded (to create a chat, for example)
  • TYPE_CONSTRUCTOR_INVALID: The type constructor is invalid
  • FILE_PART_INVALID: The file part number is invalid
  • FILE_PARTS_INVALID: The number of file parts is invalid
  • FILE_PART_X_MISSING: Part X (where X is a number) of the file is missing from storage
  • MD5_CHECKSUM_INVALID: The MD5 checksums do not match
  • PHOTO_INVALID_DIMENSIONS: The photo dimensions are invalid
  • FIELD_NAME_INVALID: The field with the name FIELD_NAME is invalid
  • FIELD_NAME_EMPTY: The field with the name FIELD_NAME is missing
  • MSG_WAIT_FAILED: A request that must be completed before processing the current request returned an error
  • MSG_WAIT_TIMEOUT: A request that must be completed before processing the current request didn’t finish processing yet

There was an unauthorized attempt to use functionality available only to authorized users.

  • AUTH_KEY_UNREGISTERED: The key is not registered in the system
  • AUTH_KEY_INVALID: The key is invalid
  • USER_DEACTIVATED: The user has been deleted/deactivated
  • SESSION_REVOKED: The authorization has been invalidated, because of the user terminating all sessions
  • SESSION_EXPIRED: The authorization has expired
  • AUTH_KEY_PERM_EMPTY: The method is unavailable for temporary authorization key, not bound to permanent

Privacy violation. For example, an attempt to write a message to someone who has blacklisted the current user.

An attempt to invoke a non-existent object, such as a method.

Similar to 400 BAD_REQUEST, but the app must display the error to the user a bit differently.
Do not display any visible error to the user when receiving the rpc_error constructor: instead, wait for an updateServiceNotification update, and handle it as usual.
Basically, an updateServiceNotification popup update will be emitted independently (ie NOT as an Updates constructor inside rpc_result but as a normal update) immediately after emission of a 406 rpc_error : the update will contain the actual localized error message to show to the user with a UI popup.

An exception to this is the AUTH_KEY_DUPLICATED error, which is only emitted if any of the non-media DC detects that an authorized session is sending requests in parallel from two separate TCP connections, from the same or different IP addresses.
Note that parallel connections are still allowed and actually recommended for media DCs.
Also note that by session we mean a logged-in session identified by an authorization constructor, fetchable using account.getAuthorizations, not an MTProto session.

If the client receives an AUTH_KEY_DUPLICATED error, the session is already invalidated by the server and the user must generate a new auth key and login again.

The maximum allowed number of attempts to invoke the given method with the given input parameters has been exceeded. For example, in an attempt to request a large number of text messages (SMS) for the same phone number.

  • FLOOD_WAIT_X: A wait of X seconds is required (where X is a number)

An internal server error occurred while a request was being processed; for example, there was a disruption while accessing a database or file storage.

If a client receives a 500 error, or you believe this error should not have occurred, please collect as much information as possible about the query and error and send it to the developers.

If a server returns an error with a code other than the ones listed above, it may be considered the same as a 500 error and treated as an internal server error.

Источник

error The request was canceled: A secure channel for SSL / TLS could not be created on create new TelegramBotClient #867

Comments

gersonfreire commented Feb 6, 2020

I have a question or need help

Please DO NOT post it! We don’t provide support in GitHub issues any more.

We would be happy if you join our group chat on Telegram and ask the community to help.

If you open an issue asking for support, the issue would be closed without providing any answer.

The text was updated successfully, but these errors were encountered:

Ayanami251379 commented Feb 6, 2020

I have the same error. I am adding my report based on the but report guidelines.

Steps to reproduce:
Download Telegram.Bot repo
Include in project
Add calls to project
Run application
Expected behavior
Receive messages from Telegram users.
Actual behavior
Receiving Error: «An error occurred while sending the request.» & vbCrLf & «The request was aborted: Could not create SSL/TLS secure channel.»
Screenshots

Environment data
Latest Telegram.Bot (Version 15.3.0, Last update 2020-02-01)
Compiler, Visual Studio 2017
.Net Version 4.5
App: Windows 10 (Desktop, Modified console app)

Chrislie7 commented Feb 6, 2020

@Ayanami251379 i have some problem but im on production, Maybe anyone can help?

Serproger commented Feb 6, 2020

The same problem reproduces for old library version (14.10.0). Our bot isn’t working.

zkolobov commented Feb 6, 2020

same issue. any updates?

bukanfarid commented Feb 6, 2020

Well same here. but my application works just fine around 18 hours ago with old library version (13.x.x).
Updated to the latest version but still not working.

Mahdi-Farhani commented Feb 6, 2020

@bukanfarid Me 2, My bot works fine about 12Hrs ago I’ve used V14.x.x
also, I update to the new version but it won’t work

Sitedh commented Feb 6, 2020

I have some issue, that appeared this morning
Version of Telegram.Bot: 14.10.0.0
.Net Version: 4.6.1
System: Windows 10
App type: Console

Chrislie7 commented Feb 6, 2020

before :
var me = await Bot.GetMeAsync();

this is working for me

bukanfarid commented Feb 6, 2020

Thanks for your reply @Chrislie7 , i tried it and it working like a charm! 👍

Ayanami251379 commented Feb 6, 2020

before :
var me = await Bot.GetMeAsync();

this is working for me

I can confirm this is working for me as well, thank you @Chrislie7
I added the security change outside the TelegramBot library as the correct dependency is not part of the TelegramBot library.

tuscen commented Feb 6, 2020 •

So, the problem is due to Telegram disabling everything older than TLS v1.2 (which is not used as the default in .NET Framework 4.5). The best way to mitigate this problem is to update to .NET Framework 4.6-4.8 or even to .NET Core 3.1 (this is preferrable if you can do that).

If you can’t upgrade your system or .NET Framework to a newer one there might be a solution. One of the members in our group came up with a guide how it can be mitigated:

So, this is the final instruction for those who faces the problem «The request was aborted: Could not create SSL / TLS secure channel»

Windows 7 / Server 2008 R2:

Update your system.

If you use .NET Framework 4.5, add this line somewhere before you initialize TelegramBotClient:

or target .NET Framework 4.6 and higher to use TLS 1.2 as default.

  1. If the error is still here, try to follow these instructions to enable TLS 1.1 and TLS 1.2 as default secure protocols in WinHTTP in Windows (https://support.microsoft.com/en-us/help/3140245/update-to-enable-tls-1-1-and-tls-1-2-as-default-secure-protocols-in-wi) (but this didn’t work for me until I updated my system).

Windows 8.1/Server 2012 R2 and higher:

VladAlexaRW commented Feb 6, 2020

My thanks to both @Chrislie7 and @tuscen . The solution provided works for .NET Framework 4.5.1

amoamare commented Feb 6, 2020 •

This is not working for me, even forcing Tls12 as you can see here
Version of Telegram.Bot: 15.3.0
Windows Server 2012 R2 Version 6.3 (Build 9600)
Framework installed: 4.8
Targeted Framework: 4.8
App Type: GUI

Forced Tls12 and tried to enable all of them
Just for testing in the I added the following to ensure as well.

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls13;

Created my own httpClient to pass to the bot, nothing works. Continuously getting this error since
2/5/2020 at approx 11:00PM MST works perfectly fine on Windows 10 and Windows 10 server

Even tried creating my own httpClient to pass to it including handler with Customer validation callback set to always true just to see if that would do anything (pretty sure it wouldn’t have but ruling it out)

The bot is also targeting dotnet 4.8

amoamare commented Feb 6, 2020 •

Just a quick update, I was able to resolve my issue on my Windows Server in case anyone else that may be having the same issue as me.

It appears that TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 must be enabled and you can enable this using IISCrypto
Just to be clear this was not a requirement to have before, not sure why it is now.

Dragonsangel commented Feb 6, 2020 •

Additionally to what @amoamare said, these are the only ciphers that are currently (2020/02/07) usable for TLS1.2 for the API (Viewable on the SSL Labs site):

For those on Windows Server 2012 R2, forget trying to find the first three since they are only available from Windows Server 2016 onwards.
Enabling one of the last two will allow your connections to work.

Additionally, the error message that I got was different than the one reported here, but all had to do with TLS configurations. Adding it here for the searches and knowledge.

System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
—> System.Security.Authentication.AuthenticationException: Authentication failed, see inner exception.
—> System.ComponentModel.Win32Exception: The message received was unexpected or badly formatted
this was due to the missing ciphers and the server then not responding with a «Server Hello» but with a «Fatal Alert: handshake_failure» response.

Scryptor commented Feb 22, 2020

Hi, i have solved this problem, setting my dns to google 8.8.8.8 and 8.8.4.4
And everything started to work
Before it you shoud use .net >= 4.6.1 or write this in your c# program,

Sorry for my english )

ahvahsky2008 commented Mar 3, 2020

Set dns names to 8.8.8.8 — all works.

drrobincroft commented Dec 20, 2022

This is not working for me, even forcing Tls12 as you can see here Version of Telegram.Bot: 15.3.0 Windows Server 2012 R2 Version 6.3 (Build 9600) Framework installed: 4.8 Targeted Framework: 4.8 App Type: GUI

Forced Tls12 and tried to enable all of them Just for testing in the I added the following to ensure as well.

ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls13;

Created my own httpClient to pass to the bot, nothing works. Continuously getting this error since 2/5/2020 at approx 11:00PM MST works perfectly fine on Windows 10 and Windows 10 server

Even tried creating my own httpClient to pass to it including handler with Customer validation callback set to always true just to see if that would do anything (pretty sure it wouldn’t have but ruling it out)

The bot is also targeting dotnet 4.8

I have finally solved this awful problem by updating windows. Believe me, adding some code or forcing tls 1.2 do not work. The only reason for this is your operating system lack some basic libraries or something like to support the communication with telegram interface.
Therefore, you should download updating packages for your windows. Take my computer with win 7 as an example, download the latest updating package collection UpdatePack7R2.exe and run it. It is big and the installation time is very costly. It may be hours. There are also many reboots. The only thing you can do is waiting. After all is done, running your program and you will find everything is fine.
Let’s praise Microsoft and Telegram!

Источник

Добрый день.
Использую dialogflow.com для ИИ, на одной машине все хорошо запускается, но на моем компьютере выдает ошибку SSL сертификата, хотя все идентично. Как вылечить?
Код фуункции:

def SmartAnswer(message): #Умные ответы
    request = apiai.ApiAI('TOKEN').text_request() # Токен API к Dialogflow
    request.lang = 'ru' # На каком языке будет послан запрос
    request.session_id = 'Hxfhcf_bot' # ID Сессии диалога (нужно, чтобы потом учить бота)
    request.query = message.text # Посылаем запрос к ИИ с сообщением от юзера
    responseJson = json.loads(request.getresponse().read().decode('utf-8'))
    response = responseJson['result']['fulfillment']['speech'] # Разбираем JSON и вытаскиваем ответ
    bot.send_message(message.chat.id, response)

Код ошибки:

2019-12-11 16:06:55,607 (util.py:65 WorkerThread2) ERROR - TeleBot: "SSLCertVerificationError occurred, args=(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)')
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/telebot/util.py", line 59, in run
    task(*args, **kwargs)
  File "/Users/danilavoronov/Documents/DAV'dev/davinfobot/main.py", line 58, in SmartAnswer
    responseJson = json.loads(request.getresponse().read().decode('utf-8'))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/apiai/requests/request.py", line 128, in getresponse
    self._connect()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/apiai/requests/request.py", line 82, in _connect
    self._connection.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1399, in connect
    self.sock = self._context.wrap_socket(self.sock,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1040, in _create
    self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)
"
Traceback (most recent call last):
  File "/Users/danilavoronov/Documents/DAV'dev/davinfobot/main.py", line 84, in <module>
    bot.polling() #Эта команда нужна для того, что бы бот не выключался и ожидал команды
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/telebot/__init__.py", line 389, in polling
    self.__threaded_polling(none_stop, interval, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/telebot/__init__.py", line 413, in __threaded_polling
    self.worker_pool.raise_exceptions()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/telebot/util.py", line 108, in raise_exceptions
    six.reraise(self.exc_info[0], self.exc_info[1], self.exc_info[2])
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/six.py", line 696, in reraise
    raise value
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/telebot/util.py", line 59, in run
    task(*args, **kwargs)
  File "/Users/danilavoronov/Documents/DAV'dev/davinfobot/main.py", line 58, in SmartAnswer
    responseJson = json.loads(request.getresponse().read().decode('utf-8'))
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/apiai/requests/request.py", line 128, in getresponse
    self._connect()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/apiai/requests/request.py", line 82, in _connect
    self._connection.connect()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/http/client.py", line 1399, in connect
    self.sock = self._context.wrap_socket(self.sock,
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1040, in _create
    self.do_handshake()
  File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)

There will be errors when working with the API, and they must be correctly handled on the client.
An error is characterized by several parameters:

Error Code

Numerical value similar to HTTP status. Contains information on the type of error that occurred: for example, a data input error, privacy error, or server error. This is a required parameter.

Error Type

A string literal in the form of /[A-Z_0-9]+/, which summarizes the problem. For example, AUTH_KEY_UNREGISTERED. This is an optional parameter.

Error Database

A full machine-readable JSON list of RPC errors that can be returned by all methods in the API can be found here », what follows is a description of its fields:

  • errors — All error messages and codes for each method (object).
    • Keys: Error codes as strings (numeric strings)
    • Values: All error messages for each method (object)
      • Keys: Error messages (string)
      • Values: An array of methods which may emit this error (array of strings)
  • descriptions — Descriptions for every error mentioned in errors (and a few other errors not related to a specific method)
    • Keys: Error messages
    • Values: Error descriptions
  • user_only — A list of methods that can only be used by users, not bots.

Error messages and error descriptions may contain printf placeholders in key positions, for now only %d is used to map durations contained in error messages to error descriptions.

Example:

{
    "errors": {
        "420": {
            "2FA_CONFIRM_WAIT_%d": [
                "account.deleteAccount"
            ],
            "SLOWMODE_WAIT_%d": [
                "messages.forwardMessages",
                "messages.sendInlineBotResult",
                "messages.sendMedia",
                "messages.sendMessage",
                "messages.sendMultiMedia"
            ]
        }
    },
    "descriptions": {
        "2FA_CONFIRM_WAIT_%d": "Since this account is active and protected by a 2FA password, we will delete it in 1 week for security purposes. You can cancel this process at any time, you'll be able to reset your account in %d seconds.",
        "SLOWMODE_WAIT_%d": "Slowmode is enabled in this chat: wait %d seconds before sending another message to this chat.",
        "FLOOD_WAIT_%d": "Please wait %d seconds before repeating the action."
    },
    "user_only": {
        "account.deleteAccount"
    }
}

Error Constructors

There should be a way to handle errors that are returned in rpc_error constructors.

Below is a list of error codes and their meanings:

303 SEE_OTHER

The request must be repeated, but directed to a different data center.

Examples of Errors:

  • FILE_MIGRATE_X: the file to be accessed is currently stored in a different data center.
  • PHONE_MIGRATE_X: the phone number a user is trying to use for authorization is associated with a different data center.
  • NETWORK_MIGRATE_X: the source IP address is associated with a different data center (for registration)
  • USER_MIGRATE_X: the user whose identity is being used to execute queries is associated with a different data center (for registration)

In all these cases, the error description’s string literal contains the number of the data center (instead of the X) to which the repeated query must be sent.
More information about redirects between data centers »

400 BAD_REQUEST

The query contains errors. In the event that a request was created using a form and contains user generated data, the user should be notified that the data must be corrected before the query is repeated.

Examples of Errors:

  • FIRSTNAME_INVALID: The first name is invalid
  • LASTNAME_INVALID: The last name is invalid
  • PHONE_NUMBER_INVALID: The phone number is invalid
  • PHONE_CODE_HASH_EMPTY: phone_code_hash is missing
  • PHONE_CODE_EMPTY: phone_code is missing
  • PHONE_CODE_EXPIRED: The confirmation code has expired
  • API_ID_INVALID: The api_id/api_hash combination is invalid
  • PHONE_NUMBER_OCCUPIED: The phone number is already in use
  • PHONE_NUMBER_UNOCCUPIED: The phone number is not yet being used
  • USERS_TOO_FEW: Not enough users (to create a chat, for example)
  • USERS_TOO_MUCH: The maximum number of users has been exceeded (to create a chat, for example)
  • TYPE_CONSTRUCTOR_INVALID: The type constructor is invalid
  • FILE_PART_INVALID: The file part number is invalid
  • FILE_PARTS_INVALID: The number of file parts is invalid
  • FILE_PART_X_MISSING: Part X (where X is a number) of the file is missing from storage
  • MD5_CHECKSUM_INVALID: The MD5 checksums do not match
  • PHOTO_INVALID_DIMENSIONS: The photo dimensions are invalid
  • FIELD_NAME_INVALID: The field with the name FIELD_NAME is invalid
  • FIELD_NAME_EMPTY: The field with the name FIELD_NAME is missing
  • MSG_WAIT_FAILED: A request that must be completed before processing the current request returned an error
  • MSG_WAIT_TIMEOUT: A request that must be completed before processing the current request didn’t finish processing yet

401 UNAUTHORIZED

There was an unauthorized attempt to use functionality available only to authorized users.

Examples of Errors:

  • AUTH_KEY_UNREGISTERED: The key is not registered in the system
  • AUTH_KEY_INVALID: The key is invalid
  • USER_DEACTIVATED: The user has been deleted/deactivated
  • SESSION_REVOKED: The authorization has been invalidated, because of the user terminating all sessions
  • SESSION_EXPIRED: The authorization has expired
  • AUTH_KEY_PERM_EMPTY: The method is unavailable for temporary authorization key, not bound to permanent

403 FORBIDDEN

Privacy violation. For example, an attempt to write a message to someone who has blacklisted the current user.

404 NOT_FOUND

An attempt to invoke a non-existent object, such as a method.

406 NOT_ACCEPTABLE

Similar to 400 BAD_REQUEST, but the app must display the error to the user a bit differently.
Do not display any visible error to the user when receiving the rpc_error constructor: instead, wait for an updateServiceNotification update, and handle it as usual.
Basically, an updateServiceNotification popup update will be emitted independently (ie NOT as an Updates constructor inside rpc_result but as a normal update) immediately after emission of a 406 rpc_error: the update will contain the actual localized error message to show to the user with a UI popup.

An exception to this is the AUTH_KEY_DUPLICATED error, which is only emitted if any of the non-media DC detects that an authorized session is sending requests in parallel from two separate TCP connections, from the same or different IP addresses.
Note that parallel connections are still allowed and actually recommended for media DCs.
Also note that by session we mean a logged-in session identified by an authorization constructor, fetchable using account.getAuthorizations, not an MTProto session.

If the client receives an AUTH_KEY_DUPLICATED error, the session is already invalidated by the server and the user must generate a new auth key and login again.

420 FLOOD

The maximum allowed number of attempts to invoke the given method with the given input parameters has been exceeded. For example, in an attempt to request a large number of text messages (SMS) for the same phone number.

Error Example:

  • FLOOD_WAIT_X: A wait of X seconds is required (where X is a number)

500 INTERNAL

An internal server error occurred while a request was being processed; for example, there was a disruption while accessing a database or file storage.

If a client receives a 500 error, or you believe this error should not have occurred, please collect as much information as possible about the query and error and send it to the developers.

Other Error Codes

If a server returns an error with a code other than the ones listed above, it may be considered the same as a 500 error and treated as an internal server error.

 c, ssl, telegram


0

1

Делаю бота для telegram.
Бот создан из самой программы telegram с помощью бота.
там выдаётся токен. Название бота известно.
Создаётся ssl соединение c api.telegram.org
Отправляется запрос с таким содержанием

https://api.telegram.org/<название бота><токен>/getMe

Ответ не приходит.
Запрос наверное неправильно составлен, но как правильно, если в запросе дело.

  • Ссылка

Оффтопик. Ненужно. Язабан

mittorn ★★★★★

(04.01.17 20:07:29 MSK)

  • Ссылка

На некорректный запрос должен приходить ответ, что запрос некорректен.

evilface ★★

(04.01.17 20:48:59 MSK)

  • Ссылка

Можно пользоваться другими системами мгновенного обмена сообщениями.

  • Ссылка

Ответ на:

комментарий
от XMs 04.01.17 21:20:29 MSK

Ответ на:

комментарий
от vvn_black 04.01.17 22:41:09 MSK

В отправке запроса указал ноль байт отправить. Исправил. Теперь пишет,

HTTP/1.1.400.Bad
.Request..Server
:.nginx/1.10.0..
Date:.Wed,.04.Ja
n.2017.19:54:20.
GMT..Content-Typ
e:.text/html..Co
ntent-Length:.17
3..Connection:.c
lose..Access-Con
trol-Allow-Origi
n:.*..Access-Con
trol-Expose-Head
ers:.Content-Len
gth,Content-Type
,Date,Server,ConHTTP/1.1 400 Bad Request
Server: nginx/1.10.0
Date: Wed, 04 Jan 2017 19:54:20 GMT
Content-Type: text/html
Content-Length: 173
Connection: close
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Length,Content-Type,Date,Server,Connection

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.10.0</center>
</body>
</html>

Теперь надо всё таки запрос составить правильно.

  • Показать ответ
  • Ссылка

Ответ на:

комментарий
от u0atgKIRznY5 04.01.17 22:56:22 MSK

Ответ на:

комментарий
от vvn_black 04.01.17 23:03:26 MSK

Ответ на:

комментарий
от u0atgKIRznY5 04.01.17 23:22:26 MSK

Это ответ не от телеги. От телеграммовского API в любом случае JSON приходит.

Можно начать с браузера, запросы к API попробовать.

vvn_black ★★★★★

(04.01.17 23:26:16 MSK)



Последнее исправление: vvn_black 04.01.17 23:27:32 MSK
(всего

исправлений: 1)

  • Показать ответы
  • Ссылка

Ответ на:

комментарий
от vvn_black 04.01.17 23:26:16 MSK

А через браузер работает.

  • Ссылка

Вот что не так?

OU=Domain Control Validated, CN=api.telegram.org
https://api.telegram.org/bot<token>/getMe
отправлено 80
строка 80
HTTP/1.1 400 Bad Request
Server: nginx/1.10.0
Date: Wed, 04 Jan 2017 23:08:06 GMT
Content-Type: text/html
Content-Length: 173
Connection: close
Access-Control-Allow-Origin: *
Access-Control-Expose-Headers: Content-Length,Content-Type,Date,Server,Connection

<html>
<head><title>400 Bad Request</title></head>
<body bgcolor="white">
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx/1.10.0</center>
</body>
</html>
  • Ссылка

Ответ на:

комментарий
от vvn_black 04.01.17 23:26:16 MSK

Неправильно запрос был сделан. В curl добавил printf с запросом, по этому запросу составил свой и заработало.

  • Ссылка

Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.

Понравилась статья? Поделить с друзьями:
  • Tele2 ошибка 28 что это
  • Tele2 ошибка 28 не отправляет сообщения
  • Teams ошибка при входе
  • Teams код ошибки caa70004
  • Teams код ошибки 80080300