PythonAnywhere - OSError:[Errno 101] 网络无法访问

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

这个电报机器人的代码以前可以在 pythonanywhere 上运行,直到有人意外地将其删除,现在尝试再次上传它,但遇到一些错误。我尝试关闭防火墙来修复错误,但我不太熟悉 python,所以不确定代码中是否缺少某些内容或其完全是网络问题,我也不知道如何修复。这是机器人。

`# bot
from aiogram import Bot, Dispatcher, executor, types
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton

# datetime
import datetime

# web browser
import webbrowser

# string manipulation
import re

# logging
import logging

BOT_TOKEN = 'XXXXX'

bot = Bot(BOT_TOKEN)

# dispatch bot
dp = Dispatcher(bot)
 
def app_run():
    """
    Prepares environment to start the bot
    """
    executor.start_polling(dp, 
                            timeout=30, 
                            skip_updates=True, 
                            on_startup=logger.info('Starting environment...'),
                            on_shutdown=print('🟢 Program started successfully'))

def setup_applevel_logger(filename):
    logger = logging.getLogger(__name__)
    logger.setLevel(logging.INFO)

    # filename
    file_handler = logging.FileHandler(f"{filename}.log")
    logger.addHandler(file_handler)
    
    stream_handler = logging.StreamHandler()
    logger.addHandler(stream_handler)
    
    formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s:%(message)s')
    file_handler.setFormatter(formatter)
    
    return logger

def get_keyboard():
    markup = InlineKeyboardMarkup()
    markup.row(button1)
    markup.row(button2)
    markup.row(button3, button4)
    return markup

# button functions
button1 = InlineKeyboardButton(text='Apply via Whatsapp 💬', callback_data='apply_via_whatsapp')
button2 = InlineKeyboardButton(text='Apply with Portfolio 🤓', callback_data='apply_via_portfolio')
button3 = InlineKeyboardButton(text='Post a Job 👨‍💻', callback_data='post_job')
button4 = InlineKeyboardButton(text='Visit our Website 👾', callback_data='visit_website')

# keyboard_inline = InlineKeyboardMarkup().row(button1, button2, button3, button4)
keyboard_inline = get_keyboard()
    
#! function after this line can be called by BOTH admins and users

@dp.message_handler(commands=['start'])
async def send_welcome(message: types.Message):
    await message.reply(f'🟢 Version Launch 1.0 is online as of {datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S")}')

@dp.channel_post_handler()
async def channel_post(message: types.Message):
    """
    Handles all channel posts

    Args:
        message (types.Message): Any channel post (in text format)
    """
    global job_id
    
    if re.search(r'Job ID: [A-Z]+[0-9]+', message['text']):
        job_id = re.findall(r'Job ID: [A-Z]+[0-9]+', message['text'])[0].split()[2]
    else:
        job_id = None
    await message.delete()
    await message.answer(f"{message['text']}", reply_markup=keyboard_inline)

@dp.callback_query_handler(text=['apply_via_whatsapp', 'apply_via_portfolio', 'post_job', 'visit_website'])
async def inline_buttons(call: types.CallbackQuery):
    """
    Callback function for button 

    Args:
        call (types.CallbackQuery): Distributes function to button press
    """    
    if call.data == 'apply_via_whatsapp':
        # opens whatsapp with job code/title of the message
        global job_id
        webbrowser.open_new(f'https://wa.me/6596963689?text={job_id}')
    elif call.data == 'apply_via_portfolio':
        # opens telegram @jojoweipop with the text "name, age, experience and address"
        text = 'Name%3A%0AAge%3A%0ANationality%3A%0APast%20Experience%3A%0APlease%20send%20a%20photo%20of%20yourself%20too'
        webbrowser.open_new(f'https://wa.me/6596963689?text={text}')
    elif call.data == 'post_job':
        # opens telegram @jojoweipop with message ‘hi would like to post a job’
        text = "Hi%20would%20like%20to%20post%20a%20job%0ACompany%20name%3A%0AJob%20details%3A"
        webbrowser.open_new(f'https://wa.me/6596963689?text={text}')
    elif call.data == 'visit_website':
        # links to nblgaming.com
        webbrowser.open_new('https://nblgaming.com/')
    await call.answer()

if __name__ == '__main__':    
    # filename tgbot_status.log
    logger = setup_applevel_logger('tgbot_status')
    app_run()
`

下面是错误。

`
$ python bot.py
Starting environment...
🟢 Program started successfully
Goodbye!
Traceback (most recent call last):
  File "/home/telegramBot12345/.local/lib/python3.10/site-packages/aiohttp/connector.py", line 980, in _wrap_create_connection
    return await self._loop.create_connection(*args, **kwargs)  # type: ignore[return-value]  # noqa
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 1064, in create_connection
    raise exceptions[0]
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 1049, in create_connection
    sock = await self._connect_sock(
  File "/usr/local/lib/python3.10/asyncio/base_events.py", line 960, in _connect_sock
    await self.sock_connect(sock, address)
  File "/usr/local/lib/python3.10/asyncio/selector_events.py", line 500, in sock_connect
    return await fut
  File "/usr/local/lib/python3.10/asyncio/selector_events.py", line 505, in _sock_connect
    sock.connect(address)
OSError: [Errno 101] Network is unreachable

The above exception was the direct cause of the following exception:

aiohttp.client_exceptions.ClientConnectorError: Cannot connect to host api.telegram.org:443 ssl:default [Network is unreachable]

During handling of the above exception, another exception occurred:
OSError: [Errno 101] Network is unreachable

The above exception was the direct cause of the following exception:
aiogram.utils.exceptions.NetworkError: Aiohttp client throws an error: ClientConnectorError: Cannot connect to host api.telegram.org:443 s
sl:default [Network is unreachable]
`

我尝试关闭我的防火墙来修复错误,但我不太熟悉Python,所以不确定代码中是否缺少某些内容或其完全是网络问题,我也不知道如何修复。我访问了多个论坛均无济于事,非常感谢您的帮助。顺便说一句,我在 pythonanywhere 上使用免费帐户,但这以前不是问题。

python python-3.x pythonanywhere aiogram
1个回答
0
投票

免费帐户只能通过代理连接到互联网。检查您正在使用的库的文档,了解如何将其配置为使用代理。您需要的详细信息在这里:https://help.pythonanywhere.com/pages/403ForbiddenError/

© www.soinside.com 2019 - 2024. All rights reserved.