使用python连接到电报api

问题描述 投票:0回答:1

我想用python创建电报机器人。我从https://github.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot2.py复制了代码,并在代码中添加了代理。因为在我国禁止电报。这是我的代码:

#!/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)')': /bot93026728:AAFUgtNpa1FDJxB5n5nhS--MCLNzVS9a-zs/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)')': /bot93026728:AAFUgtNpa1FDJxB5n5nhS--MCLNzVS9a-zs/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)')': /bot93026728:AAFUgtNpa1FDJxB5n5nhS--MCLNzVS9a-zs/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: /bot93026728:AAFUgtNpa1FDJxB5n5nhS--MCLNzVS9a-zs/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

如果有人能帮助我,我会非常感谢。

python proxy telegram telegram-bot python-telegram-bot
1个回答
1
投票
© www.soinside.com 2019 - 2024. All rights reserved.