Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用python连接到电报api_Python_Proxy_Telegram_Telegram Bot_Python Telegram Bot - Fatal编程技术网

用python连接到电报api

用python连接到电报api,python,proxy,telegram,telegram-bot,python-telegram-bot,Python,Proxy,Telegram,Telegram Bot,Python Telegram Bot,我想用python创建电报机器人。我从中复制了代码,并在代码中添加了代理。因为在我的国家,电报是被禁止的。 这是我的密码: #!/usr/bin/env python # -*- coding: utf-8 -*- # This program is dedicated to the public domain under the CC0 license. """ Simple Bot to reply to Telegram messages. First, a few handler fu

我想用python创建电报机器人。我从中复制了代码,并在代码中添加了代理。因为在我的国家,电报是被禁止的。 这是我的密码:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This program is dedicated to the public domain under the CC0 license.

"""
Simple Bot to reply to Telegram messages.
First, a few handler functions are defined. Then, those functions are passed to
the Dispatcher and registered at their respective places.
Then, the bot is started and runs until we press Ctrl-C on the command line.
Usage:
Basic Echobot example, repeats messages.
Press Ctrl-C on the command line or send a signal to the process to stop the
bot.
"""

import logging

from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

REQUEST_KWARGS = {
        'proxy_url': 'socks5://grsst.s5.opennetwork.cc:999',
        # Optional, if you need authentication:
        'urllib3_proxy_kwargs': {
            'username': '107727736',
            'password': 'Pqcccqku',
        }
    }

# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

logger = logging.getLogger(__name__)


# Define a few command handlers. These usually take the two arguments update and
# context. Error handlers also receive the raised TelegramError object in error.
def start(update, context):
    """Send a message when the command /start is issued."""
    update.message.reply_text('Hi!')


def help(update, context):
    """Send a message when the command /help is issued."""
    update.message.reply_text('Help!')


def echo(update, context):
    """Echo the user message."""
    update.message.reply_text(update.message.text)


def error(update, context):
    """Log Errors caused by Updates."""
    logger.warning('Update "%s" caused error "%s"', update, context.error)


def main():
    """Start the bot."""
    # Create the Updater and pass it your bot's token.
    # Make sure to set use_context=True to use the new context based callbacks
    # Post version 12 this will no longer be necessary
    updater = Updater("My_Token", use_context=True, request_kwargs=REQUEST_KWARGS)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help))

    # on noncommand i.e message - echo the message on Telegram
    dp.add_handler(MessageHandler(Filters.text, echo))

    # log all errors
    dp.add_error_handler(error)

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C or the process receives SIGINT,
    # SIGTERM or SIGABRT. This should be used most of the time, since
    # start_polling() is non-blocking and will stop the bot gracefully.
    updater.idle()


if __name__ == '__main__':
    main()
我实际上使用了我从@BotFather那里得到的代币。 但在执行此代码后,我得到以下错误:

D:\Software\Python\Python38-32\pythonw.exe "D:/PythonProject/Telegram Bot/echobot2.py"
2020-03-11 03:56:51,769 - telegram.vendor.ptb_urllib3.urllib3.connectionpool - WARNING - Retrying (Retry(total=2, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x066B8778>, 'Connection to api.telegram.org timed out. (connect timeout=5.0)')': /bot9<MY-_TOKEN>/getMe
2020-03-11 03:56:57,271 - telegram.vendor.ptb_urllib3.urllib3.connectionpool - WARNING - Retrying (Retry(total=1, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x066B8850>, 'Connection to api.telegram.org timed out. (connect timeout=5.0)')': /bot9<MY-_TOKEN>/getMe
2020-03-11 03:57:02,809 - telegram.vendor.ptb_urllib3.urllib3.connectionpool - WARNING - Retrying (Retry(total=0, connect=None, read=None, redirect=None)) after connection broken by 'ConnectTimeoutError(<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x066B8928>, 'Connection to api.telegram.org timed out. (connect timeout=5.0)')': /bot9<MY-_TOKEN>/getMe
Traceback (most recent call last):
  File "D:\Software\Python\Python38-32\lib\site-packages\socks.py", line 809, in connect
    negotiate(self, dest_addr, dest_port)
  File "D:\Software\Python\Python38-32\lib\site-packages\socks.py", line 443, in _negotiate_SOCKS5
    self.proxy_peername, self.proxy_sockname = self._SOCKS5_request(
  File "D:\Software\Python\Python38-32\lib\site-packages\socks.py", line 470, in _SOCKS5_request
    chosen_auth = self._readall(reader, 2)
  File "D:\Software\Python\Python38-32\lib\site-packages\socks.py", line 276, in _readall
    d = file.read(count - len(data))
  File "D:\Software\Python\Python38-32\lib\socket.py", line 669, in readinto
    return self._sock.recv_into(b)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\contrib\socks.py", line 79, in _new_conn
    conn = socks.create_connection(
  File "D:\Software\Python\Python38-32\lib\site-packages\socks.py", line 209, in create_connection
    raise err
  File "D:\Software\Python\Python38-32\lib\site-packages\socks.py", line 199, in create_connection
    sock.connect((remote_host, remote_port))
  File "D:\Software\Python\Python38-32\lib\site-packages\socks.py", line 47, in wrapper
    return function(*args, **kwargs)
  File "D:\Software\Python\Python38-32\lib\site-packages\socks.py", line 814, in connect
    raise GeneralProxyError("Socket error", error)
socks.GeneralProxyError: Socket error: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 614, in urlopen
    httplib_response = self._make_request(conn, method, url,
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 360, in _make_request
    self._validate_conn(conn)
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 857, in _validate_conn
    super(HTTPSConnectionPool, self)._validate_conn(conn)
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 289, in _validate_conn
    conn.connect()
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connection.py", line 284, in connect
    conn = self._new_conn()
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\contrib\socks.py", line 102, in _new_conn
    raise ConnectTimeoutError(
telegram.vendor.ptb_urllib3.urllib3.exceptions.ConnectTimeoutError: (<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x066B8A18>, 'Connection to api.telegram.org timed out. (connect timeout=5.0)')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\utils\request.py", line 225, in _request_wrapper
    resp = self._con_pool.request(*args, **kwargs)
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 64, in request
    return self.request_encode_url(method, url, fields=fields,
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\request.py", line 87, in request_encode_url
    return self.urlopen(method, url, **extra_kw)
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\poolmanager.py", line 244, in urlopen
    response = conn.urlopen(method, u.request_uri, **kw)
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 691, in urlopen
    return self.urlopen(method, url, body, headers, retries,
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 691, in urlopen
    return self.urlopen(method, url, body, headers, retries,
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 691, in urlopen
    return self.urlopen(method, url, body, headers, retries,
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\connectionpool.py", line 665, in urlopen
    retries = retries.increment(method, url, error=e, _pool=self,
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\vendor\ptb_urllib3\urllib3\util\retry.py", line 376, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
telegram.vendor.ptb_urllib3.urllib3.exceptions.MaxRetryError: SOCKSHTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot9<MY-_TOKEN>/getMe (Caused by ConnectTimeoutError(<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x066B8A18>, 'Connection to api.telegram.org timed out. (connect timeout=5.0)'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "D:/PythonProject/Telegram Bot/echobot2.py", line 88, in <module>
    main()
  File "D:/PythonProject/Telegram Bot/echobot2.py", line 79, in main
    updater.start_polling()
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\ext\updater.py", line 258, in start_polling
    self.job_queue.start()
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\ext\jobqueue.py", line 311, in start
    name="Bot:{}:job_queue".format(self._dispatcher.bot.id))
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\bot.py", line 54, in decorator
    self.get_me()
  File "<decorator-gen-1>", line 2, in get_me
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\bot.py", line 67, in decorator
    result = func(*args, **kwargs)
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\bot.py", line 251, in get_me
    result = self._request.get(url, timeout=timeout)
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\utils\request.py", line 277, in get
    result = self._request_wrapper('GET', url, **urlopen_kwargs)
  File "D:\Software\Python\Python38-32\lib\site-packages\telegram\utils\request.py", line 231, in _request_wrapper
    raise NetworkError('urllib3 HTTPError {0}'.format(error))
telegram.error.NetworkError: urllib3 HTTPError SOCKSHTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot{My_token}/getMe (Caused by ConnectTimeoutError(<telegram.vendor.ptb_urllib3.urllib3.contrib.socks.SOCKSHTTPSConnection object at 0x066B8A18>, 'Connection to api.telegram.org timed out. (connect timeout=5.0)'))

Process finished with exit code 1
D:\Software\Python\Python38-32\pythonw.exe“D:/PythonProject/Telegram Bot/echobot2.py”
2020-03-11 03:56:51769-telegram.vendor.ptb_urlib3.urlib3.connectionpool-警告-在连接被“ConnectTimeoutError(,”到api.telegram.org的连接超时(连接超时=5.0)”:/bot9/getMe中断后重试(重试(总计=2,连接=None,读取=None,重定向=None))
2020-03-11 03:56:57271-telegram.vendor.ptb_urlib3.urlib3.connectionpool-警告-连接中断后重试(重试(总计=1,连接=None,读取=None,重定向=None):/bot9/getMe
2020-03-11 03:57:02809-telegram.vendor.ptb_urlib3.urlib3.connectionpool-警告-连接被“ConnectTimeoutError(,”连接到api.telegram.org超时(连接超时=5.0)”:bot9/getMe中断后重试(重试(总计=0,连接=None,读取=None,重定向=None))
回溯(最近一次呼叫最后一次):
文件“D:\Software\Python\Python38-32\lib\site packages\socks.py”,第809行,在connect中
协商(自身、目的地地址、目的地端口)
文件“D:\Software\Python\Python38-32\lib\site packages\socks.py”,第443行,位于\u SOCKS5中
self.proxy\u peername,self.proxy\u sockname=self.\u SOCKS5\u请求(
文件“D:\Software\Python\Python38-32\lib\site packages\socks.py”,第470行,在_SOCKS5_请求中
已选择\u auth=self.\u readall(读卡器,2)
文件“D:\Software\Python\Python38-32\lib\site packages\socks.py”,第276行,在_readall中
d=file.read(计数-len(数据))
readinto中第669行的文件“D:\Software\Python\Python38-32\lib\socket.py”
返回自我。将袜子重新放入(b)
socket.timeout:超时
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb\u urlib3\urlib3\contrib\socks.py”,第79行,位于康涅狄格州的新州
conn=socks.create\u连接(
文件“D:\Software\Python\Python38-32\lib\site packages\socks.py”,第209行,位于create\u connection中
提出错误
文件“D:\Software\Python\Python38-32\lib\site packages\socks.py”,第199行,位于create\u connection中
sock.connect((远程主机、远程端口))
文件“D:\Software\Python\Python38-32\lib\site packages\socks.py”,第47行,在包装器中
返回函数(*args,**kwargs)
文件“D:\Software\Python\Python38-32\lib\site packages\socks.py”,第814行,在connect中
引发GeneralProxyError(“套接字错误”,错误)
socks.GeneralProxyError:套接字错误:超时
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb_urlib3\urlib3\connectionpool.py”,第614行,在urlopen中
httplib\u response=self.\u发出请求(连接、方法、url、,
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb\u urlib3\urlib3\connectionpool.py”,第360行,在请求中
自我验证连接(连接)
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb\u urlib3\urlib3\connectionpool.py”,第857行,位于\u validate\u conn
超级(HTTPSConnectionPool,self)。\u验证\u连接(conn)
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb\u urlib3\urlib3\connectionpool.py”,第289行,位于\u validate\u conn
连接
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb_urlib3\urlib3\connection.py”,第284行,在connect中
conn=自我。_new_conn()
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb\u urlib3\urlib3\contrib\socks.py”,位于康涅狄格州新州第102行
提升连接超时错误(
telegram.vendor.ptb_urlib3.urlib3.exceptions.ConnectTimeoutError:(,“与api.telegram.org的连接超时。(连接超时=5.0)”
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\utils\request.py”,第225行,在请求包装中
resp=self.\u con\u pool.request(*args,**kwargs)
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb\u urlib3\urlib3\request.py”,请求中的第64行
返回self.request\u encode\u url(方法,url,字段=字段,
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb\u urlib3\urlib3\request.py”,第87行,在request\u encode\u url中
返回self.urlopen(方法,url,**额外\u kw)
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb\u urlib3\urlib3\poolmanager.py”,第244行,在urlopen中
response=conn.urlopen(方法,u.request\u uri,**kw)
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb_urlib3\urlib3\connectionpool.py”,第691行,在urlopen中
返回self.urlopen(方法、url、正文、标题、重试、,
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb_urlib3\urlib3\connectionpool.py”,第691行,在urlopen中
返回self.urlopen(方法、url、正文、标题、重试、,
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb_urlib3\urlib3\connectionpool.py”,第691行,在urlopen中
返回self.urlopen(方法、url、正文、标题、重试、,
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb\u urlib3\urlib3\connectionpool.py”,第665行,在urlopen中
retries=retries.increment(方法,url,error=e,_pool=self,
文件“D:\Software\Python\Python38-32\lib\site packages\telegram\vendor\ptb_urlib3\urlib3\util\retry.py”,第376行,增量
引发MaxRetryError(_池、url、错误或响应错误(原因))
电报.vendor.ptb_urlib3.urlib3.exceptions.MaxR