#python #python-3.x #telegram #python-telegram-bot
#python #python-3.x #telegram #python-telegram-bot
Вопрос:
Я начал писать telegram-бота и использовал для этого пример freeCodeCamp.
from telegram.ext import Updater, CommandHandler
import requests
import re
contents = requests.get('https://random.dog/woof.json').json()
image_url = contents['url']
def get_url():
contents = requests.get('https://random.dog/woof.json').json()
url = contents['url']
return url
def get_image_url():
allowed_extension = ['jpg','jpeg','png']
file_extension = ''
while file_extension not in allowed_extension:
url = get_url()
file_extension = re.search("([^.]*)$",url).group(1).lower()
return url
def bop(bot, update):
url = get_url()
chat_id = update.message.chat_id
bot.send_photo(chat_id=chat_id, photo=url)
def main():
updater = Updater('<MY-PRIVATE-BOT-TOKEN>')
dp = updater.dispatcher
dp.add_handler(CommandHandler('bop', bop))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
main()
После запуска этого кода я получил эту ошибку. Кроме того, я получаю эту ошибку после запуска любого бота telegram, который я пишу.
Traceback (most recent call last):
File "D:workbotvenvlibsite-packagesurllib3connection.py", line 159, in _new_conn
conn = connection.create_connection(
File "D:workbotvenvlibsite-packagesurllib3utilconnection.py", line 61, in create_connection
for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
File "C:UsersaAppDataLocalProgramsPythonPython38libsocket.py", line 918, in getaddrinfo
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11002] getaddrinfo failed
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='random.dog', port=443): Max retries exceeded with url: /woof.json (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000026811517F10>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/workbot/main.py", line 5, in <module>
contents = requests.get('https://random.dog/woof.json').json()
File "D:workbotvenvlibsite-packagesrequestsapi.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "D:workbotvenvlibsite-packagesrequestsapi.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "D:workbotvenvlibsite-packagesrequestssessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "D:workbotvenvlibsite-packagesrequestssessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "D:workbotvenvlibsite-packagesrequestsadapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='random.dog', port=443): Max retries exceeded with url: /woof.json (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x0000026811517F10>: Failed to establish a new connection: [Errno 11002] getaddrinfo failed'))
Мне также приходится использовать прокси или VPN для подключения к telegram из-за фильтрации.
Я получил еще одну ошибку подключения в эхо-боте. Я использовал код документации бота telegram. Я получил эту ошибку:
raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='google', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000199A2C37DF0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "D:/workbot/main.py", line 5, in <module>
contents = requests.get('https://google').json()
File "D:workbotvenvlibsite-packagesrequestsapi.py", line 75, in get
return request('get', url, params=params, **kwargs)
File "D:workbotvenvlibsite-packagesrequestsapi.py", line 60, in request
return session.request(method=method, url=url, **kwargs)
File "D:workbotvenvlibsite-packagesrequestssessions.py", line 533, in request
resp = self.send(prep, **send_kwargs)
File "D:workbotvenvlibsite-packagesrequestssessions.py", line 646, in send
r = adapter.send(request, **kwargs)
File "D:workbotvenvlibsite-packagesrequestsadapters.py", line 516, in send
raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='google', port=443): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x00000199A2C37DF0>: Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))
Комментарии:
1. Ваш токен БОТА был в вопросе. Я удалил ее, но она все еще видна в истории. Подумайте о том, чтобы обновить токен в @BotFather, чтобы другие люди не злоупотребляли им!
2. Можете ли вы опубликовать полную трассировку ошибки в стеке?
3.
getaddrinfo failed
означает, что ваш DNS-сервер не может разрешить хостrandom.dog
. Похоже, это проблема с подключением между вашим сервером и этим хостом, поэтому вы можете также использовать прокси / vpn для этой части.4. но у меня была эта проблема, даже когда я создавал простого эхо-бота