This code for a Telegram bot was working previously on pythonanywhere
until someone took it down accidentally, now trying to upload it again, but facing some errors. I’ve tried turning off my firewall to fix the error, but I’m not very well versed in Python, so I’m not sure if there’s something missing in the code or it’s completely a network issue, for which I also don’t know how to fix. This is the bot.
# 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()
And below is the error:
$ 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]
I’ve tried turning off my firewall to fix the error, but I’m not very well versed in Python, so I’m not sure if there’s something missing in the code or it’s completely a network issue, for which I also don’t know how to fix. I’ve visited multiple forums to no avail, any help is much appreciated. I’m using a free account on pythonanywhere
. Btw, but this hasn’t been an issue before.
2
Answers
Free accounts can only connect to the internet through the proxy. Check the documentation for the library that you’re using to see how to configure it to use a proxy. The details you need are here: https://help.pythonanywhere.com/pages/403ForbiddenError/
I solved this issue by configuring a proxy for PythonAnywhere:
First, install
aiohttp-socks
:Then, use the proxy in your code like this:
This method works with
aiogram 3.x
on a free PythonAnywhere account.