Telegram bot 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.

Источник

Добрый день.
Использую 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)

За последние 24 часа нас посетили 11563 программиста и 1163 робота. Сейчас ищут 303 программиста …


  1. Unify

    С нами с:
    19 ноя 2022
    Сообщения:
    1
    Симпатии:
    0

    Нужно создать простенького бота и через него отправить форму в чат, но при отправке формы выдает ошибку

    Fatal error: Uncaught TelegramBotApiHttpException: SSL certificate problem: self signed certificate in certificate chain in C:Serverdatahtdocstelbotvendortelegram-botapisrcBotApi.php:265 Stack trace: #0 C:Serverdatahtdocstelbotvendortelegram-botapisrcBotApi.php(232): TelegramBotApiBotApi->executeCurl(Array) #1 C:Serverdatahtdocstelbotvendortelegram-botapisrcBotApi.php(342): TelegramBotApiBotApi->call(‘sendMessage’, Array) #2 [internal function]: TelegramBotApiBotApi->sendMessage(‘@SvguBotTest49’, ‘456’) #3 C:Serverdatahtdocstelbotvendortelegram-botapisrcClient.php(412): call_user_func_array(Array, Array) #4 C:Serverdatahtdocstelbottelegram.php(14): TelegramBotApiClient->__call(‘sendMessage’, Array) #5 {main} thrown in C:Serverdatahtdocstelbotvendortelegram-botapisrcBotApi.php on line 265

    Сам код 265 строки: throw new HttpException(curl_error($this->curl), curl_errno($this->curl));


  2. ADSoft

    ну наверное не по https:// запускаете
    либо сертификат самоподписанный … используйте адекватный …

0 / 0 / 0

Регистрация: 16.05.2019

Сообщений: 5

1

Telegram Bot

02.02.2023, 11:11. Показов 176. Ответов 0


Здравствуйте, честно гуглил, но не смог ничего найти. Есть кусочек кода телеграмм бота + ChatGPT:

C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
string YOUR_QUERY = $"Что такое ананас?";
string API_KEY = "мой ключ";
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {API_KEY}");
var request = new HttpRequestMessage
{
     RequestUri = new Uri("https://api.openai.com/v1/completions"),
     Method = HttpMethod.Post,
     Content = new StringContent("{"model": "text-davinci-003", "prompt": "" + YOUR_QUERY + "", "max_tokens": 3950, "temperature": 0.5}", Encoding.UTF8, "application/json")
};
var response = client.SendAsync(request).Result;
var content = response.Content.ReadAsStringAsync().Result;
var result = JsonConvert.DeserializeObject<dynamic>(content);
string text = result.choices[0].text;
await botClient.SendTextMessageAsync(message.Chat, text, disableNotification: true, replyToMessageId: message.MessageId);

Он работает, но только на моем локальном компьютере, когда я загружаю это на сервер (win server 2012 r2) возникает ошибка:

C#
1
2
3
4
System.AggregateException: One or more errors occurred. (The SSL connection could not be established, see inner exception.)
 ---> System.Net.Http.HttpRequestException: The SSL connection could not be established, see inner exception.
 ---> System.Security.Authentication.AuthenticationException: Authentication failed because the remote party sent a TLS alert: 'HandshakeFailure'.
 ---> System.ComponentModel.Win32Exception (0x80090326): Получено непредвиденное сообщение или оно имеет неправильный формат.

И такая:

C#
1
One or more errors occurred. (The SSL connection could not be established, see inner exception.)

Отключить проверку таким образом не получается (ошибка все равно выходит):

C#
1
ServicePointManager.ServerCertificateValidationCallback = delegate { return true; };

Я понимаю, что на сервере что-то не установлено, понимаю что проблема с ssl сертификатами, но никак не могу это решить.. Прошу помощи, куда копать, как решить?
.net core 6 — он на сервере установлен

Спасибо за уделенное время

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь



0



Понравилась статья? Поделить с друзьями:
  • Telegram api ssl error
  • Telegram api bot error code
  • Tele2 ошибка при загрузке приложения
  • Tele2 ошибка 28 что это
  • Tele2 ошибка 28 не отправляет сообщения